Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to read Paginator in django template
I am setting up a pagination in my Django APP. Following is my view code: class ClaimsView(ListView): context_object_name = "archives" template_name = "myapp/claims.html" def get_queryset(self, **kwargs): query = self.request.GET.get("q", "") response = self.get_archives(query) paginator =Paginator(response, 4) pages = paginator.get_pages(4) return {'archives': response, 'pages': pages} When I print pages in the viwes file. It give correct result "<page 1 of 1>" but when I am passing it to the HTML file its not give any results there. 'archives' in above dict has a list as value its working fine but not the 'pages' This is how I am reading it in HTML file: {{pages}} -
raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) TypeError: 'class Meta' got invalid attribute(s): constraints
#For Battery Manger Project 16-12-2021 class BatteryManager(models.Model): slno = models.AutoField(db_column='Slno', primary_key=True) # Field name made lowercase. lithiumionbattery = models.DecimalField(db_column='LithiumIonBattery', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_voltage = models.DecimalField(db_column='Bty_Voltage', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_current = models.DecimalField(db_column='Bty_Current', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. batterytemp = models.DecimalField(db_column='BatteryTemp', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. ambienttemp = models.DecimalField(db_column='AmbientTemp', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_username = models.CharField(db_column='Bty_Username', max_length=30, blank=True, null=True) # Field name made lowercase. bty_circlename = models.CharField(db_column='Bty_circlename', max_length=30, blank=True, null=True) # Field name made lowercase. bty_payload = models.CharField(db_column='Bty_payload', max_length=100, blank=True, null=True) # Field name made lowercase. bty_createddate = models.DateTimeField(db_column='Bty_createdDate', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'BatteryManager' def __str__(self): return str(self.Slno) -
Embed tag not showing the pdf inside "Django template"
I need to display a pdf inside the table, but the embed tag there is not working. The HTML file, I am using is a template of the Django app. Following is the code, I am writing to display the pdf:- {% if awp.Supporting_documents %} <td id=displayrecord><a href="{%url 'component_progress:download_file_Supporting_documents' awp.id %}">download</a> <embed src="/home/vvdn/Downloads/Preview.pdf" width="500" height="375" type="application/pdf"> </td> {% else %} The output that is being displayed in the UI is as follows:- -
prevent user to access login page in django when already logged in?
def admin_login(request): if request.method == 'POST': username = request.POST["username"] password = request.POST["password"] user = authenticate(request,username = username, password = password) if user is not None: if(user.is_superuser): auth_login(request, user) return redirect(reverse("dashboard")) else: messages.info(request, "invalid credentials") return redirect(reverse("admin")) return render(request,'login.html') this is mylogin function for admin , how to prevent user to access login page once logged in? -
Python Django, struggling to create a dynamic list
I want to create a section on my site, where for each subject, links to corresponding past papers can be found, but I am struggling to get any output. Looking for ideas: My views.py: def index(request): subjects = Subject.objects.all() context = {'subjects': subjects} return render(request, 'alevelspastpapers/index.html', context=context) My models.py: class Subject(models.Model): subject = models.CharField(max_length=30) def __str__(self): return self.subject class past_paper(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) exam_date = models.DateField('Examination Date') paper_number = models.IntegerField('Paper Number: ') paper_urllink = models.TextField() markscheme_urllink = models.TextField() solved_paperslink = models.TextField(null=True) def __str__(self): return f"{self.subject} Paper {self.paper_number}, {self.exam_date}" My html content: {% if subjects %} {% for subject in subjects %} <p>{{ subject.subject }}</p> {% for papers in subject.subject.past_papers_set.all %} <p>{{ papers.paper_urllink }}</p> {%endfor%} {% endfor %} {% endif %} -
Django TypeError: Expected str, bytes or os.PathLike object, not NoneType
I am writing a webpage that can run a python script by clicking a button on html. Here is what I have: views.py from django.shortcuts import render import requests import sys from subprocess import run,PIPE def external(request): inp= request.POST.get('param') out= run([sys.executable,'test.py',inp],shell=False,stdout=PIPE) print(out) return render(request,'home.html',{'data1':out.stdout}) urls.py from django.urls import path from . import views # urlconf urlpatterns = [ path('external/', views.external) ] home.html <html> <head> <title> Python button script </title> </head> <body> <form action="/external/" method="post"> {% csrf_token %} Input Text: <input type="text" name="param" required><br><br> {{data_external}}<br><br> {{data1}} <br><br> <input type="submit" value="Execute External Python Script"> </form> </body> </html> directory screenshot The problem is with this line of code: out= run([sys.executable,'test.py',inp],shell=False,stdout=PIPE) from views.py. How can I fix this? Thanks! -
How to execute a django or SQL query after clicking the toggle button?
I have two tables: class DibbsSpiderDibbsMatchedProductFieldsDuplicate(models.Model): nsn = models.TextField() nsn2 = models.TextField() cage = models.TextField() part_number = models.TextField() company_name = models.TextField(blank=True, null=True) supplier = models.TextField(db_column='Supplier', blank=True, null=True) # Field name made lowercase. cost = models.CharField(db_column='Cost', max_length=15, blank=True, null=True) # Field name made lowercase. list_price = models.CharField(db_column='List_Price', max_length=15, blank=True, null=True) # Field name made lowercase. gsa_price = models.CharField(db_column='GSA_Price', max_length=15, blank=True, null=True) # Field name made lowercase. hash = models.TextField() nomenclature = models.TextField() technical_documents = models.TextField() solicitation = models.CharField(max_length=32) status = models.CharField(max_length=16) purchase_request = models.TextField() issued = models.DateField() return_by = models.DateField() file = models.TextField() vendor_part_number = models.TextField() manufacturer_name = models.TextField(blank=True, null=True) product_name = models.TextField(blank=True, null=True) unit = models.CharField(max_length=15, blank=True, null=True) class Meta: managed = False db_table = 'dibbs_spider_dibbs_matched_product_fields_duplicate' class DibbsSpiderSolicitation(models.Model): line_items = models.IntegerField() nsn = models.TextField() nomenclature = models.TextField() technical_documents = models.TextField() purchase_request = models.TextField() class Meta: managed = False db_table = 'dibbs_spider_solicitation' I want to display these in the format : The original link is on : http://develop-330.gsa-cs.com/test/ After Clicking on the toggle button, how to execute the query ? Line #1 means Line line_items First row is of first table. After clicking on the toggle, I want to execute a django query or a sql query which joins two tables … -
How to render month and monthly total using attributes in django filter class and calling to a class based view?
in my models.py, i have this, class Expenditure(models.Model): item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True, related_name='items') author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING, null=True) bank = models.ForeignKey(Bank, on_delete=models.DO_NOTHING, blank=True, null=True) date = models.DateField(blank=False, null=False, default=datetime.date.today) amount = models.DecimalField(max_digits=20, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))]) remarks = models.CharField(max_length=200, blank=True, null=True) def __str__(self): template = '{0.item}, {0.date}' return template.format(self) def get_absolute_url(self): return reverse('expenditure_detail',kwargs={'pk':self.pk}) in my filters.py, i have this MONTH_CHOICES = [ ('1','January'),('2','February'),('3','March'),('4','April'),('5','May'),('6','June'), ('7','July'),('8','August'),('9','September'),('10','October'),('11','November'),('12','December'), ] YEAR_CHOICES = [ ('2021','2021'),('2022','2022'),('2023','2023'),('2024','2024'),('2025','2025'), ] class ExpenditureFilter(django_filters.FilterSet): month = django_filters.ChoiceFilter(field_name='date',label='Month',choices=MONTH_CHOICES,widget=forms.Select(attrs={'class':'form-control'}),lookup_expr='month') year = django_filters.ChoiceFilter(field_name='date',label='Year',choices=YEAR_CHOICES,widget=forms.Select(attrs={'class':'form-control'}),lookup_expr='year') class Meta: model = Expenditure fields = ('year','month') in my views.py, i have this class ExpenditureListView(LoginRequiredMixin, ListView): context_object_name = 'expenditures' login_url = 'login/' model = Expenditure # paginate_by = 10 ordering = ["-date"] today = datetime.date.today() def get_queryset(self): queryset = super().get_queryset() filter = ExpenditureFilter(self.request.GET, queryset) return filter.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) queryset = self.get_queryset() filter = ExpenditureFilter(self.request.GET, queryset) context["filter"] = filter context['total'] = float(Expenditure.objects.aggregate(Sum('amount')).get('amount__sum', 0.00)) context['current_month_total'] = float(Expenditure.objects.filter(date__year=self.today.year, date__month=self.today.month).aggregate(Sum('amount')).get('amount__sum', 0.00)) return context in my HTML template i have this, <section class="section"> <div class="container"> <div class="row"> <div class="col-lg-2 col-md-2 mb-80"> <div class="row"> <div class="col-lg-10 mx-auto text-center"> <p class="font-tertiary"> Total amount spent<br> <span class="font-red">৳ {{ total|intcomma }}</span> </p> <p class="font-tertiary"> {% now "F Y" %} total <br> <span>৳ {{ current_month_total|intcomma }}</span> </p> </div> … -
python requests not recognizing params
I am requesting to mindbodyapi to get token with the following code using requests library def get_staff_token(request): URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue" payload = { 'Api-Key': API_KEY, 'SiteId': "1111111", 'Username': 'user@xyz.com', 'Password': 'xxxxxxxx', } r = requests.post(url=URL, params=payload) print(r.text) return HttpResponse('Done') gives a response as follows {"Error":{"Message":"Missing API key","Code":"DeniedAccess"}} But if I request the following way it works, what I am doing wrong with requests library conn = http.client.HTTPSConnection("api.mindbodyonline.com") payload = "{\r\n\t\"Username\": \"username\",\r\n\t\"Password\": \"xxxxx\"\r\n}" headers = { 'Content-Type': "application/json", 'Api-Key': API_KEY, 'SiteId': site_id, } conn.request("POST", "/public/v6/usertoken/issue", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -
How can I display Error Messages for the logging funtion in Django?
I am a new Django Developer, and I have some trouble with the login function. My problem is that my system does not show error messages even though it is invalid. I try to enter the wrong username and password, and I expect there are some error messages displayed. However, it does not work. Here is my code: login_register.html <div class="login-form"> <form action="" method="POST"> {% csrf_token %} {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p> {{ error }} </p> {% endfor %} {% endfor %} {% endif %} <h2 class="text-center">Sign in</h2> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <span class="fa fa-user"></span> </span> </div> <input type="text" class="form-control" name="username" placeholder="Username" required="required" /> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-lock"></i> </span> </div> <input type="password" class="form-control" name="password" placeholder="Password" required="required" /> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary login-btn btn-block"> Sign in </button> </div> <div class="clearfix"> <a href="{% url 'reset_password' %}" class="text-center" >Forgot Password?</a > </div> </form> <p class="text-center text-muted small"> Don't have an account? <a href="{% url 'register' %}">Register here!</a> </p> </div> view.py def loginUser(request): page = 'login' if request.user.is_authenticated: return redirect('starting-page') if request.method == 'POST': username … -
XOR showing same value after 17 characters in python
Am trying to encrypt a integer for hiding primary keys in URLs of Django. So after research I found that encrypting "int" can be done using XOR! So I thought of trying those for example: id = 1 masked_id = id ^ 0xABCDEFAB unmasked_id = masked_id ^ 0xABCDEFAB print(masked_id) //2882400170 print(unmasked_id) //1 The above works well until the id character count reaches to 10. For example check below Output: When id character count is greater than 10, id = 11111111111 masked_id = 1032582764 unmasked_id = 2521176519 Its weird that, the output is not as expected when it crosses 10 count. So how this works and how to fix this ? Is there any way to encrypt int (pk) form database ? -
How to request existing files from a form in django
i'm trying to add a feature for users to update thier profile, but i want to be able to get thier existing informations so they don't have to fill all the form again. I have tried request.POST on the form but it doesn't work, it does not update the form with the existing user informations. views.py def profile_update(request): info = Announcements.objects.all() categories = Category.objects.all() Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('userauths:profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) # profile update function def profile_update(request): info = Announcements.objects.all() categories = Category.objects.all() Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('userauths:profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) -
Django AttributeError: 'int' object has no attribute 'pk'
I am stuck :(. I have an API that I can't seem to get working with the DRF. I am forming my queryset in my view and the result that I want is coming out in the console: web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 5, 'periodic_sell_period': 10, 'month': datetime.datetime(2021, 11, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('1.2300000000')} web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 2, 'periodic_sell_period': 14, 'month': datetime.datetime(2021, 12, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('7.4200000000')} web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 13, 'periodic_sell_period': 11, 'month': datetime.datetime(2021, 12, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('100.9600000000')} I can see that the obj gets passed into my serializer, but for the life of me I can not understand where I am going wrong. Here is my view.py class TopHistoricalGainViewSet(viewsets.ModelViewSet): queryset = TopHistoricalGains.objects.all() twelve_months_ago = datetime.datetime.now()+relativedelta(months=-12) serializer_class = TopHistoricalGainsSerializer def get_queryset(self): ids = self.queryset\ .values('id')\ .order_by('company_exchange__id') twelve_months_ago = datetime.datetime.now()+relativedelta(months=-12) hg_list = TopHistoricalGains.objects.filter(id__in=ids, periodic_date_time__gte=twelve_months_ago) hg_list = hg_list\ .annotate(month=TruncMonth('periodic_date_time')) \ .values('month') \ .annotate(periodic_sum=Sum('periodic_gain_max')) \ .values('company_exchange', 'company_exchange__company__name', 'company_exchange__stock_symbol', 'month', 'periodic_sum', 'strategy', 'periodic_buy_period', 'periodic_sell_period') \ #.order_by('company_exchange', '-periodic_sum', 'strategy', 'periodic_buy_period', 'periodic_sell_period')[:10] for hg in hg_list: print(hg) return hg_list class Meta: ordering = ['periodic_sum', … -
How to get the user id of the currently connected account in models.py
I want to give a condition by distinguishing when the user.id of the Leave object and the user id of the current access account are the same and when they are not. The original get_html_url function only had a 'self' argument. If 'request' is added to the argument to get the user id of the currently connected account, the error get_html_url() missing 1 required positional argument: 'request' occurs. It seems that I need to add request to utils.py to fix the error. But I don't know which function to add. Help. [models.py] class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) kind = models.CharField(choices=KIND_CHOICES, max_length=20, blank=True, null=True) from_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) memo = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self, request -----> dAre there any errors?): url = reverse('leave:leave_edit', args=(self.id,)) user = request.user.id -----> Are there any errors? if self.kind == 'Annual' and self.user.id == user: return f'<div class="Annual-title"><a href="{url}" style="color:black;"> {self.name}</a></div>' elif self.kind == 'Half' and self.user.id == user: return f'<div class="Half-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Holiday' and self.user.id == user: return f'<div class="Holiday-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Annual' and self.user.id … -
how i create box like recent action admin menu django
how can I create the recent actions box in Django admin? pic -
How to pass and interpret a complex render context in Django?
I'm pretty new to Django and am not sure if I'm approaching this problem correctly. My view code generates a many to many map. So something like {'penguin' : ("bird", "black", "flightless", "arctic")}, {'axolotl' : ("reptile", "green")} {'rhino' : ("mammal", "horn", "heavy")} and so on... for a lot of different procedurally generated animals Out of this I'm trying to render page that would just have the animal's name and underneath it a few bullet points with the characteristics, like this Penguin bird black flightless and so on for every animal. The number of these animals and the descriptions are unknown and are parsed at runtime from an xml file I thought I could just pass this structure into the template and use the template language to iterate over it and render it out, but so far I feel like I'm having to jump through hoops, so I'm not sure if I'm doing something wrong or if this is just outside the scope of Django and I should be using a different framework for this kind project. The problems I'm running into: I'm having issues figuring out how to even pass this structure into the context and have it available for … -
Setting up simple Django ViewSet APIs from multiple apps
I’m still learning django and assume this may be easy for some. I’m trying to figure out the best way of simply setting up the API URLs (and so that they all display in the api root and can actually be used in the project - in my case at /api/). I’m using django rest framework, and can’t seem to set up more than one API - it works for just one, but the problem occurs when trying to set up another. So I have an app called pages and accounts (and core - the default where the main urls.py is). I’ve created another urls.py inside the pages app and another inside the accounts app. accounts/urls.py: from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r"accounts", views.AccountsViewSet, basename="accounts") urlpatterns = router.urls pages/urls.py: from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r"pages", views.PagesViewSet, basename="pages") urlpatterns = router.urls And the core urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from rest_framework.routers import DefaultRouter router = routers.DefaultRouter() urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("pages.urls")), # works but root only shows pages API # path("api/", include("pages.urls", "accounts.urls")), # fails with error: “django.core.exceptions.ImproperlyConfigured: Specifying … -
Django display form based off boolean
I am trying to use django-formtools. I have pip installed it and it's in my settings.py as well as requirements.text. Currently my /signup page works for signing up users but now I want to add another user type at the start of the form. It has this flow to it. I just want to make sure the forms display currently. 1. Displays different form based off first form's boolean. is False: display normal signup form(done) is True: display form with an added file field 2. Handles the form differently as well is False: saves the form as an abstractuser(done) is True: sends to db for an admin to add to. modals.py class PickUserType(forms.Form): is_doctor = forms.BooleanField() class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) urls.py from django.urls import path from pages.views import index, signup urlpatterns = [ … -
How to load Django template javascript when using request.get?
is my first time asking here but I'll try to explain my problem as clear as possible. I have a Django template with a few scripts on it, one of them will generate two graphs with voting results through Vue (a classmate has to do that part and isn't yet fully implemented, that is why Im using two dummy canvas elements). After generating those canvas I take them with the external script called 'get_graphs.js' and inside that script I made an AJAX POST request which stores those canvas and show them in another Django template on the same server. This works fine when I have visited the first django template using the browser at least one time but when I use another method like requests.get, urllib.request.urlopen or even Postman to visit it from outside, those scripts are not called and so the second template doesn't have the canvas. Here is the code of the first Django template: {% extends "base.html" %} {% load i18n static %} {% block extrahead %} <link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" /> <link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" /> <link type="text/css" rel="stylesheet" href="{% static "booth/style.css" %}" /> <link type="text/css" rel="stylesheet" href="{% static "/visualizer.css" %}" /> {% endblock %} {% … -
Field 'last_login' expected a number but got datetime
hello I face this probleme when trying to connect to Django Admin here is my source code i do not want to change my legacy user table last_login field in date time it is an integer field that stop date time in unix timestamp . here is my source code from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager from .helper import get_current_unix_timestamp from django.contrib.auth.signals import user_logged_in class MyUserManager(BaseUserManager): def create_user(self, username,password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not username: raise ValueError('user must have a username') user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( username, password=password, ) user.is_admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class Account(AbstractBaseUser): id = models.AutoField(primary_key=True,verbose_name='ID',) username = models.CharField(max_length=50, blank=True, null=True,unique=True) password = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) ip = models.CharField(max_length=255,null=True,blank=True) date_registered = models.IntegerField(default=get_current_unix_timestamp()) last_login = models.IntegerField(null=True,blank=True) member_group_id = models.IntegerField(blank=True, null=True) credits = models.FloatField(blank=True, null=True) notes = models.TextField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) reseller_dns = models.TextField(blank=True, null=True) owner_id = models.IntegerField(blank=True, null=True) override_packages = models.TextField(blank=True, null=True) … -
Django python3 manage.py runserver won't run via VSC terminal (Mac)
Trying to run this command: python3 manage.py runserver via VSC terminal and get this error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? But! when I run it via the Mac terminal, it works well. I have verified and: Virtual env is running (via Anaconda) Django is installed (as it is running on the Mac terminal) is it something with VCS setting I need to tweak? Thanks in advance! -
Fitlering errors in Sentry
I'm running sentry.io for my django project. I'd like to prevent some errors from being reported so as to not consume my quota. Unfortunately, I'm not able to find any code samples on how to do this. Sentry's documentation doesn't clearly outline how or where to do this. I was wondering if you'd be able to provide a simple example or point me in the right direction. I'm on the Developer plan, so I need to filter these errors server side before sending to Sentry in order to prevent my quota from being hit. Thanks! -
Displaying Panda Table from other python project in Django App
So I am looking to display a Pandas table on a Django website through a django app. I have found this thread: display django-pandas dataframe in a django template. This explains how to use bootstrap and JS to create the table and display it in Django. However where I am lost is how I import the panda table to the object in the django. Basically, I have python project that creates pandas based on information queried data from elsewhere. Now I am trying to display those pandas on my web app. So, where I am lost is how I can run that python code (from my python pandas project) to get most recent data in sync with running the website and thus assign the pandas to the product model object. Any information regarding this would be huge. Thanks in advance! I am trying to use bootstrap-tables, because it is interactive and can create many different tables, but if someone has an easier less complicated idea please let me know. -
Showing the line numbers in <pre> in Django project using Pygments
I'm using the Pygments package in my Django project. When I try to render the code snippet in my template, it renders the whole data as follows: Template: ... {% pygmentify %} <pre class="{{snippet.lang}}">{{snippet.body}}</pre> {% endpygmentify %} ... Final rendered HTML: <pre lang="python"> ... <span class="kn">import</span> <span class="nn">hello</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'hey'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">test</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'in the function'</span><span class="p">)</span> ... </pre> It actually works with no pain. The entire code block is being highlighted properly. The thing is that I want to show the line number as well. Should I style them or there is only a simple Pygments configuration needed? Thanks. -
AssertionError:'token' not found in{'non_field_errors':[ErrorDetail(string='Unable to authenticate with provided credentials.',code='authorization')]}
I've been made a django rest api app and i have this error in my test: image I'm going to leave the code here The test: def test_create_user_token(self): payload = { 'email': 'test@gmail.com', 'password': 'test123', 'name': 'Test' } create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) The serializer class: class AuthTokenSerializer(serializers.Serializer): email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password=password ) if not user: msg = _('Unable to authenticate with provided email and password.') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs From already thank you very much