Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Custom user login form doesn't work
I'm a beginner at Django and I created custom user model (Person) using AbstractBaseUser and custom forms for registration (RegForm) and login (LogForm). With RegForm everything is okay and it works right but when I try to login I always have error messages that's my username or password incorrect, even when it's correct. I have tried to read documentation but I didn't find solution. And I have no idea what is wrong. views.py : from django.shortcuts import render,redirect from django.contrib import messages #from .models import Tutorial from django.http import HttpResponse from django.contrib.auth import logout, authenticate, login, get_user_model # для входа, выхода from .forms import RegForm , LogForm from .models import Person, Service, Category from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import AuthenticationForm @login_required def homepage(request): return render(request = request, template_name='barter/home.html', context = {"category":Category.objects.all}) def register(request): #вход аккаунта next = request.GET.get('next') # if request.method == 'POST': form = RegForm(request.POST or None) if form.is_valid(): user = form.save(commit = False) Username = form.cleaned_data.get('Username') password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(Username=user.Username, password=password) login(request, new_user) if next: return redirect(next) return redirect('/') context = { 'form' : form, } return render(request,"register.html",context) def login_request(request): #вход next = request.GET.get('next') form = LogForm(request.POST or None) if form.is_valid(): Username = … -
Python reportlab - Last page
I'm trying to create an invoice with the python reportlab library. (to return in a Django view) What I am already able to do is the following: I can create the first page with the header and add a table with all products, which can go over multiple pages. But now my problem: How can I write something at the bottom of the last page? (I already added a Spacer to be sure that there's enough space for the important part of the invoice. I need to get a canvas on which I can draw the invoice. (That function which draws the invoice is all set up) I hope you can help me! PS: I'm sorry for my english, I'm from switzerland. -
Summary values on a Django Model with tens of millions of records
I have a Django model developed on PostgreSQL with more than 20 Millions of records. The large volume of data makes it impossible to get even a simple count of all rows. from myapp.models import LargeModel len(LargeModel.objects.all()) Is there any workaround for this? -
Why is Django Channels websocket connect call failing?
I am working on a web app that consists of a Django channels 2 app running on AWS Elastic Beanstalk, where AWS Elasticache serves as my redis instance. Everything works completely fine in development, but once I deploy it to AWS I start having websocket issues. Initially it works just fine, sending data over the websocket, for about two minutes, but at some point the connection always fails. Django throws the exception [Errno 110] Connect call failed. In my past experience this has always been related to it not being able to connect to the redis instance, however, in those cases it failed immediately. I have no idea why it's suddenly failing after some amount of time. Any suggestions for causes of this error? -
Hi there. I would like to register the models in admin.py but it doesn't work
Here is admin.py code and I registered app in INSTALLED_APPS and I created three app beside this app . from django.contrib import admin admin.autodiscover() from .models import ( Teacher,Student,Group, Subject,Table,Dairy, NotParticipating,Task,StudentTask, ) @admin.register(Teacher) class TeacherAdmin(admin.ModelAdmin): list_display = ('created_at', ) admin.site.register(Student) admin.site.register(Group) admin.site.register(Subject) admin.site.register(Table) admin.site.register(Dairy) admin.site.register(NotParticipating) admin.site.register(Task) admin.site.register(StudentTask) -
How to deploy changes made to my django project, which is hosted on pythonanywhere?
I am new to git and Pythonanywhere. So, I have a live Django website which is hosted with the help of Pythonanywhere. I have made some improvements to it. I have committed and pushed that changes to my Github repository. But, now I don't know that how to further push that changes to my Pythonanywhere website. I am so confused. Please help!!! Forgive me, I am new to it. -
Reducing backlog and celery mem consumption
I have a Django app that simply checks an API and then stores the response from the API to my DB if the status is completed, I use celery for this, the celery task looks like this @task(bind=True, priority=5) def process_domain_scan(self, scan_url): response = self.get_status(scan_url) if response and (response.get('status') != "FAILED"): while response and response.get('status') == "PENDING": print "processing :: {}".format(response) time.sleep(5) response = self.get_status(scan_url) if response and response.get('status') == "COMPLETED": #store to database the problem here is that sometimes the job I am running on the external API might be pending for hours and hence my celery task will be in a loop for hours while waiting for the status to return Completed is there a better way of using celery to do this without waiting for the API to return Completed -
Deployment failed on heroku
I am relatively new to Django and I am finishing my first project. I've been following the heroku django tutorial at http://devcenter.heroku.com/articles/django and https://www.youtube.com/watch?v=kBwhtEIXGII&list=PL-51WBLyFTg2vW-_6XBoUpE7vpmoR3ztO&index=24&t=576s but I keep running into the following problem. heloku logs --tail 2020-04-27T17:49:06.576169+00:00 app[web.1]: ModuleNotFoundError: No module named 'crm-live' 2020-04-27T17:49:06.576364+00:00 app[web.1]: [2020-04-27 17:49:06 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-04-27T17:49:06.614676+00:00 app[web.1]: [2020-04-27 17:49:06 +0000] [4] [INFO] Shutting down: Master 2020-04-27T17:49:06.614802+00:00 app[web.1]: [2020-04-27 17:49:06 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-04-27T17:49:08.033207+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=codrut-crm.herokuapp.com request_id=2d4b0b83-fb4b-4658-b465-d96b3cd3c4fd fwd="188.26.24.149" dyno= connect= service= status=503 bytes= protocol=https 2020-04-27T17:53:52.000000+00:00 app[api]: Build started by user ursache.codrut71@gmail.com 2020-04-27T17:54:58.618150+00:00 app[api]: Deploy 11a7c2b5 by user ursache.codrut71@gmail.com 2020-04-27T17:54:58.618150+00:00 app[api]: Release v9 created by user ursache.codrut71@gmail.com 2020-04-27T17:54:58.947798+00:00 heroku[web.1]: State changed from crashed to down 2020-04-27T17:55:10.000000+00:00 app[api]: Build succeeded 2020-04-27T17:55:37.135414+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=codrut-crm.herokuapp.com request_id=dad84a35-0089-44a8-9d8c-4c06e673f59d fwd="188.26.24.149" dyno= connect= service= status=503 bytes= protocol=https 2020-04-27T17:56:52.119540+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/admin" host=codrut-crm.herokuapp.com request_id=485798b3-6d1b-48c7-beb2-5d9a0ba52dcf fwd="188.26.24.149" dyno= connect= service= status=503 bytes= protocol=https 2020-04-27T18:08:48.000000+00:00 app[api]: Build started by user ursache.codrut71@gmail.com 2020-04-27T18:09:49.587556+00:00 app[api]: Deploy 11a7c2b5 by user ursache.codrut71@gmail.com 2020-04-27T18:09:49.587556+00:00 app[api]: Release v10 created by user ursache.codrut71@gmail.com 2020-04-27T18:10:01.000000+00:00 app[api]: Build succeeded 2020-04-27T18:10:05.771483+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" … -
Django urls NoReverseMatch - missing argument
I've a more or less working comment and edit comment system. However, when I configured everything so that the proper userreview_id is pulled to the url in my UpdateView, it broke the link going from index page to details (it is in details thatare displayed comments, access to comment form and to updateview form). Here is my code with Broken URL urlpatterns = [ # ex: /restaurants/ path('', views.index, name='index'), # ex: /restaurants/15 path('<int:restaurant_id>/', views.details, name='details'), path('/edit/review/<int:userreview_id>', views.EditReview.as_view(), name='edit-review'), ] Details view def details(request, restaurant_id): # calling restaurant ID and displaying it's data restaurant = get_object_or_404(Restaurant, pk=restaurant_id) # calling a review and displaying it's data user_review_list = UserReview.objects.filter(pk=restaurant_id) user_reviews = [] for user_review in user_review_list: if user_review.posted_by == request.user: user_reviews.append({"user_review_grade": user_review.user_review_grade, "user_review_comment": user_review.user_review_comment, "posted_by": user_review.posted_by, "edit": user_review.get_edit_url}) else: user_reviews.append({"user_review_grade": user_review.user_review_grade, "user_review_comment": user_review.user_review_comment, "posted_by": user_review.posted_by}) return render(request, 'restaurants/details.html', {'restaurant': restaurant, 'user_review_list': user_reviews,}) index template {% extends "base_generic.html" %} {% block content %} <h1>Restauracje Poznan</h1> <p> Search by name or city <form action="{% url 'restaurants:search_results' %}" method="get" class="form-inline"> <div class="form-group mx-sm-3 mb-2"> <input name="q" type="text" placeholder="Search..."> </div> <div> <input type="submit" class="btn btn-primary mb-2" value="Search"> </div> </form> </p> <h2>Restaurants and other gastronomy places:</h2> {% if restaurants_list %} <ul class="list-group"> {% for restaurant in … -
How to check if a url is valid that youtube-dl supports
I am developing a project, where user submits a URL. I need to check if that URL is valid url , to download data from youtube-dl supported sites. Please help. -
Why is pytest throwing an "AttributeError: 'NoneType' object has no attribute '_meta'" error when testing model creation?
I'm using Django 2 and trying to write some unit tests for my models. I have these models ... class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] class CoopType(models.Model): name = models.CharField(max_length=200, null=False, unique=True) objects = CoopTypeManager() class CoopManager(models.Manager): # Look up by coop type def get_by_type(self, type): qset = Coop.objects.filter(type__name=type, enabled=True) return qset class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I have created the following factory for auto-generating these models ... import factory from .models import CoopType, Coop class CoopTypeFactory(factory.DjangoModelFactory): """ Define Coop Type Factory """ class Meta: model = CoopType class CoopFactory(factory.DjangoModelFactory): """ Define Coop Factory """ class Meta: model = Coop coop_type = factory.SubFactory(CoopTypeFactory) Then I created this simple test ... import pytest from django.test import TestCase from .tests.factories import CoopTypeFactory, CoopFactory class ModelTests(TestCase): @classmethod def setUpTestData(cls): print("setUpTestData: Run once to set up non-modified data for all class methods.") pass def setUp(self): print("setUp: Run once for every test method to setup clean data.") pass @pytest.mark.django_db def test_coop_type_model(): """ Test coop type model """ # create coop type model instance coop_type = CoopTypeFactory(name="Test Coop Type Name") assert coop_type.name … -
Can I refer to single value of foreign key in Django's template?
I have model: `class product(models.Model): product = models.CharField(primary_key=True, unique=True, max_length=7, editable=False) desc = models.CharField(max_length=50) class pricelist(models.Model): product = models.ForeignKey(product, on_delete=models.CASCADE) price_group = models.ForeignKey(pricegroup, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2, null=True)` Basically I have 4 different price groups(one product may have up to 4 different prices- one for each price_group) and I'd like to display product's price of specified(filtered) price group on my product's template(DetailView). Let's say I have following price groups: "PG1", "PG2","PG3","PG4" I'm able to loop through the list of them: {% for pricelist in product.pricelist.all %} {{ pricelist.price }} {% endfor %} but I can't display prices for only two specified price groups. I need to display prices on my webpage in the following way: PG1 = 124 PG3 = 367 Sometimes only prices for two or three groups are available -
got this error while runing the django web service
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name ' six' from 'django.utils' -
Modular python admin pages
I'm building a personal website that I need to apply modularity to it for purpose of learning. What it means is that there is a model that contains x number of classes with variations, as an example a button is a module that you can modify as much depending on provided attributes. I also have a pages model that need to select any of created modules and render it. I can't find any documentation of how to access multiple classes from one field to reference to. Model structure is as below: Modules, contains module A and module B Pages should be able to select any of module A and order its structure. Please let me know if not clear, this is the simplest form I could describe. Am I confusing this with meta classes? How one to achieve what I'm trying to achieve? -
AppRegistryNotReady: Apps aren't loaded yet
I am trying to query data from database using Python shell. settings.py includes: import django django.setup() ... INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products.apps.ProductsConfig', 'users.apps.UsersConfig', 'crispy_forms', ] When i open Python shell i do: > from django.conf import settings > settings.configure() Then I try to import models: > from products.models import Product However, Python returns: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I tried adding django.setup() call in settings and also moving this statement after INSTALLED_APPS. -
why the super(ContactView, self) ? . isnt super use to call a function of parent class and why is that argument necessary
also this line in the below code why is the return necessary: return super(ContactView, self).form_valid(form). class ContactView(FormView): form_class = ContactForm template_name = 'contact-us.html' success_url = reverse_lazy('<app-name>:contact-us') def form_valid(self, form): self.send_mail(form.cleaned_data) return super(ContactView, self).form_valid(form) def send_mail(self, valid_data): # Send mail logic print(valid_data) pass -
Django Ajax post data is not clean on insert
I am posting the data via Ajax using $("#add").click(function () { var data = { 'content': $("#content-input").val(), 'csrfmiddlewaretoken': '{{ csrf_token }}' }; var request = $.ajax({ url: "/ajax/list", method: "POST", data: data, dataType: "json" }); }); I'm trying to save the data in my view using if request.is_ajax() and request.method == 'POST': form = listModel() tmpForm = form.save(commit=False) tmpForm.content = request.POST['content'], tmpForm.user_id = request.user tmpForm.save() return HttpResponse(json.dumps({"message":"saved"}),content_type="application/json") else: return Http404 The data is being saved as ('Test input',), What am I doing wrong? I want the text to be saved normally without the parentheses. Thanks -
how do I pass context variables which use request in Class-based views in django?
In my other views, I am passing in the following context variable. tab: 'documents' authenticated: request.user.is_authenticated Exec: ('Exec' in groups) ElectionOfficer: ('ElectionOfficer' in groups) Staff: request.user.is_staff Username: request.user.username URL_ROOT: settings.URL_ROOT How can I pass in those exact same variables when accessing the page that renders with the /multiple url? in my urls.py url(r'^multiple$', views.SubmissionUploadPage.as_view(), name='multiple_example') in my forms.py class MultipleFileExampleForm(BaseForm): input_file = MultipleUploadedFileField() def save(self): example = UserSubmission.objects.create( title=self.cleaned_data['title'] ) for f in self.cleaned_data['input_file']: UploadedFile.objects.create( example=example, input_file=f ) self.delete_temporary_files() in my views.py class BaseFormView(generic.FormView): template_name = 'file_uploads/example_form.html' def get_success_url(self): return reverse('success') def form_valid(self, form): form.save() return super(BaseFormView, self).form_valid(form) class SubmissionUploadPage(BaseFormView): form_class = forms.MultipleFileExampleForm -
I want to display pptx from my local to webpage using Django
<iframe class="default_position" src="{% static 'images/aa.pps' %}" ></iframe> When i am using this, and after refreshing it, its showing ad download. i want to display on web page, not download. -
Field validation with JavaScript (Django for backend)
I'm working with my checkout form and I'm trying to style the validation form with red when the field is not valid. This is what I have so far, and it works almost perfectly: (function() { const elementsList = document.querySelectorAll("#id_street_adress, #id_zip_code, #id_country, #id_email"); const elementsArray = [...elementsList]; var form = document.getElementById('form'); var elem = document.createElement('div'); elem.id = 'notify'; elem.style.display = 'none'; form.appendChild(elem); elementsArray.forEach(element => { element.addEventListener('invalid', function(event){ event.preventDefault(); if ( ! event.target.validity.valid ) { elem.textContent = 'Please complete the fields below.'; elem.className = 'error'; element.className = 'input textinput textInput form-control invalid'; elem.style.display = 'block'; } else{ element.className = 'input textinput textInput form-control'; } }); element.addEventListener('input', function(event){ if ( 'block' === elem.style.display ) { elem.className = ''; elem.style.display = 'none'; } }); }); })(); The issue with this is that it'll add the css class invalid if the field is -obviously- invalid but it won't remove it if the user changes it to somethinh that in fact is valid. That's what I'm trying to achieve with that else statement, but it won't do the trick. I appreciate any kind of help! Let me know if you need any other code, since I tried to make it as simple as possible. -
Preventing Django view from running context_data on load
My Django site returns data when loading the view, regardless if required parameters have values. I'm using Django-Filters to provide the filter form. My end goal is for the user to have to input the filters prior to the get_context_data method from running. Views.py class BillingListView(LoginRequiredMixin, UserPassesTestMixin, ListView): login_url = '/login/' redirect_field_name = 'redirect_to' raise_exception = True model = Trip queryset = Trip.objects.select_related('pu_Location', 'do_Location', 'driver', 'vehicle') template_name = "main/billing.html" ordering = ("serviceDate", "pu_Time", "tripID") def test_func(self): return self.request.user.is_staff def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = BillingFilter(self.request.GET, queryset=self.get_queryset()) return context Filters.py class BillingFilter(django_filters.FilterSet): trip_choices = ( ('ERRORS', 'ERRORS'), ('PROCESSED', 'PROCESSED'), ) errors_only = django_filters.ChoiceFilter(choices=trip_choices, label='Billing Status', method='get_errors') serviceDate = django_filters.DateFromToRangeFilter(field_name='serviceDate', required=True, label='Date Range', widget=RangeWidget(attrs={'placeholder': 'MM/DD/YYYY'})) def get_errors(self, queryset, field_name, value): if value == 'ERRORS': return queryset.filter(Q(miles__lte=0) | Q(pu_Actual__isnull=True) | Q(pu_Clear__isnull=True) | Q(driver__isnull=True) | Q(vehicle__isnull=True)) if value == 'PROCESSED': return queryset.filter(miles__gte=0, pu_Actual__isnull=False, pu_Clear__isnull=False, driver__isnull=False, vehicle__isnull=False) class Meta: model = Trip fields = ['errors_only', 'serviceDate', ] I've tried to edit the request using a RequestFactory but it didn't seem like the best option. What are best practices to filter the data if required parameters are missing? -
Problems with request object in template
I have a project with videos and i want to make if loop that will add icon to the video if you are on this video right now. How to implement that? template <h1>{{ video.title }}</h1> <video width="960" height="620" id="plyr-video" poster="/path/to/video-poster.png" controls> <source src="{{ video.video.url }}" type="video/mp4"> <source src="/path/to/video.webm" type="video/webm"> <!-- Captions are optional --> <track kind="captions" label="English captions" src="/path/to/video-caption.vtt" srclang="en" default> </video> <h1>{{ course.title }}</h1> <div class="ui styled accordion"> {% for section in sections %} <div class="title {% if section == video.section %}active{% endif %}"> <i class="dropdown icon"></i> {{ section.title }} </div> <div class="content {% if video.section == section %}active{% endif %}"> <div class="ui divided list"> {% for video in videos %} {% if video.section == section %} <div class="item"> <i class="map video icon"></i> <div class="content"> <a class="header" href="{% url 'courses:video_detail' course.slug video.pk %}">{{ video.title }}{% if %}<i class="small play red icon"></i>{% endif %}</a> <div class="description">An excellent polish restaurant, quick delivery and hearty, filling meals.</div> </div> </div> {% endif %} {% endfor %} </div> </div> {% endfor %} -
Django cannot load static images, but can load image through web url
In my Django app, i cannot load images from DB or from local files. But i can load images through image web link. HPGRM\ hpgrm\ setting.py and other files mahasabha\ app.py and other files static\ images\ image1.JPG templates\ base.html manage.py db.sqlite3 {% load static %} <img src="{% static /orange.jpg' %}" /> or <img src="{% static images/orange.jpg' %}" /> #This is working perfectly :- <img src="http://www.clipartbest.com/cliparts/Kcj/p5B/Kcjp5Bb6i.png" class="img_size" alt="NewALT" /> I tried every possible method available on the internet moved static directory to every other directory available in project Changed path in settings.py Used different images Loaded images from Db and more but still cannot find any answers. I can, on other hand copy image link from google and use it as src='image.link.from.google' and can successfully load image [enter image description here][1] #here is error file PS E:\Abhi\HPGRM\hpgrm> py manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 27, 2020 - 21:39:23 Django version 3.0.5, using settings 'hpgrm.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [27/Apr/2020 21:39:28] "GET /home/ HTTP/1.1" 200 3189 Not Found: /home/{% static 'mahasabha/images/img.png' } Not Found: /home/{% static 'mahasabha/images/orange.jpg' } [27/Apr/2020 21:39:28] "GET /home/%7B%%20static%20'mahasabha/images/img.png'%20%7D HTTP/1.1" … -
django.db.utils.ProgrammingError: cannot cast type uuid to integer
I tried to upload my web to Heroku server and stuck at this ploblem my error when I try to migrate my database The above exception was the direct cause of the following exception: return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: cannot cast type uuid to integer LINE 1: ...ict_word" ALTER COLUMN "id" TYPE integer USING "id"::integer ^ models.py class Word(models.Model): id = models.UUIDField(primary_key=True, unique=True) esearch = models.TextField() eentry = models.TextField() tentry = models.TextField() ecat = models.TextField() ethai = models.TextField(null=True) esyn = models.TextField(null=True) eant = models.TextField(null=True) def __str__(self): return self.eentry def get_absolute_url(self): return reverse('word-detail', args=[str(self.id)]) does anybody know how to fix it -
Django: substitute password field with another field for obtaining JWT with Simple JWT
I am using Simple JWT for issuing tokens. I am generating random code upon user registration and assigning it to user. Is it possible to substitute password field which is required to obtain token with this field?