Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The view system.views.Login didn't return an HttpResponse object. It returned None instead
I'm newbie to Django. I'm stuck at one thing that, valueError at /login/. I've tried my best to search and try to solve this but i didn't find my problem solution. In Following First Code Sample From Which I Got Error, def get(self, request): if request.user.is_authenticated: username = request.user stud = Stud.objects.filter(adm=username).exists() cord = Cord.objects.filter(Id=username).exists() if stud: return redirect('appStatus') elif cord: return redirect('cordIndex') else: return redirect('admin') else: form = self.form(None) return render(request, self.template, {'form': form}) Error traced from terminal: ValueError: The view system.views.Login didn't return an HttpResponse object. It returned None instead. -
django {"non_field_errors":["Unable to log in with provided credentials."]} (authtoken)
models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) # creates token when user registers def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class cUserManager(BaseUserManager): # saves the user def create_user(self, email, password, **others): email = self.normalize_email(email) user = self.model(email=email, **others) user.set_password(password) user.save() return user def create_superuser(self, email, password, **others): others.setdefault('is_staff', True) others.setdefault('is_superuser', True) return self.create_user(email, password, **others) class cUser(PermissionsMixin, AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=128, unique=True) password = models.CharField(max_length=256, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = cUserManager() urls.py from django.urls import path from . import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ # Auth Views path('login', obtain_auth_token, name='login'), ] Sample User "id": 1, "email": "user@gmail.com", "username": "User", "password": 123, "is_staff": true, "is_superuser": true, "created_at": "2021-08-10 - 16:25:19", I am trying to login the user, but whenever i do it throws this error: {"non_field_errors":["Unable to log in with provided credentials."]}, the data that gets sent to the obtain_auth_token url is the username and password, everything is good in settings.py so no need to show it here... so … -
xhtml2pdf: Output generated PDF as in-memory object (its bytes)
I'm working with Python 3, Django and the xhtml2pdf package. I want to create a PDF from an HTML string, but I don't want to write the PDF on disk, but rather just to get its bytes, as in using BytesIO or StringIO. I've read the xhtml2pdf documentation: In-memory files can be generated by using StringIO or cStringIO instead of the file open. Advanced options will be discussed later in this document. And this is one the latest thing I've tried: def html_to_pdf(html): """Writes a PDF file using WeasyPrint from a given HTML stream Parameters ---------- html : str A HTML valid string. Returns ------- bytes A bytes sequence containing the rendered PDF. """ new_output = BytesIO() pisa_status = pisa.CreatePDF(html, dest=new_output) return new_output.read() But this isn't working. Any idea how to output the generated PDF and in-memory object and thus return its bytes? -
how to pass kwargs in ajax urls in django? Reverse for '' with arguments '('',)' not found. 1 pattern tried: ['partners/analytics/(?P<id>[0-9]+)/$']
I have the following code in one of my templates: var id = "{{a.id}}"; $.ajax({ url :'{% url 'this:dashboard' id %}',, type : 'POST', data : { }, }); I get the following error? Reverse for '' with arguments '('',)' not found. 1 pattern(s) tried: ['dash/here/(?P<id>[0-9]+)/$'] my url is: path('here/<int:id>/', views.dashboard, name="dashboard"), -
How to render django model instances in particular order using django templates?
I have for div in my html with their id each like this: <div class="row"> <div class="myclass" id="id1"></div> <div class="myclass" id="id2"></div> <div class="myclass" id="id3"></div> <div class="myclass" id="id4"></div> </div> Now how can I render the instance of the model in the order specified below ? first instance in first div of the row second instance in second div of the row third instance in third div of the row fourth instance in fourth div of the row and fifth instance in first div of the row so one and so forth. Any help would be appreciate even if it is using javascript hope it would be lot more simpler there. -
Django project only works locally, not on Heroku?
When I run my django project on my local pc, it works perfectly fine and I can sign up/log in/log out on my site. When I deploy it to Heroku, it doesn't work anymore, giving me the following error: OperationalError at /login/ no such table: auth_user I know this question exists, and I've already tried all the solutions, but it still hasn't worked. I've done migrate and makemigrations on both the python and heroku side, along with the commit command at different intervals. I also don't even have the usercreateform, and OP's error for that question appeared on their local pc, not just Heroku. I also tried creating a super user, which I could on my local pc, but not on Heroku. If it helps, my procfile is: web: gunicorn django_project.wsgi --log-file - I had a hard time determining my procfile, so maybe that's the problem? The django_project part is just the name of the folder that includes settings.py and wsgi.py. Forms.py: class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] class NewMessageForms(forms.ModelForm): class Meta: model = Message fields = ['content','reciever'] -
web_1 | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
I am building an application with Djnago and MySql. I want to use docker for the deployment of my application. I have prepared a requirement.txt, docker-compose.yml and a Dockerfile docker-compose.yml version: '3' services: db: image: mariadb restart: always ports: - 3306:3306 environment: MYSQL_DATABASE: stage_emsi MYSQL_USER: root MYSQL_PASSWORD: password MYSQL_ROOT_PASSWORD: password web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/code depends_on: - db image: web:django Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /code WORKDIR /code RUN pip install mysqlclient COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ error b_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/MySQLdb/__init__.py", line … -
password dont change in views.py on django
I'm trying to change a user's password on my views.py and whenever I change the password, I lose my connection and access to my account my view.py: user = User.objects.get(id=request.user.id) user.password = make_password(request.POST.get("password")) user.save() -
How do I dynamically create methods for Django models?
I have been studying Python for several months and for the first time I got stumped. I have a sample Django code like this: class SomeOptions(models.Model): FIRST = 1 SECOND = 2 THIRD = 3 @classmethod def get_first(cls): return SomeOptions.objects.get(pk=cls.FIRST) @classmethod def get_second(cls): return SomeOptions.objects.get(pk=cls.SECOND) @classmethod def get_third(cls): return SomeOptions.objects.get(pk=cls.THIRD) It looks disgusting. But it works exactly the way I want it to. SomeOptions.get_first() >> 'Some data from db' I want to remove these methods and make them get generated dynamically. I even managed to do it this way: class Dispatcher(object): def __init__(self, model, method_name): self.model = model self.method_name = method_name def __call__(self): return self.get_required_attribute_value() def get_required_attribute_value(self): required_attribute_name = self.get_required_attribute_name() required_attribute_value = getattr(self.model, required_attribute_name) value_from_database = self.model.objects.get(pk=required_attribute_value) return value_from_database def get_required_attribute_name(self): _, required_attribute_name = self.method_name.split('_') return required_attribute_name.upper() class SomeOptions(models.Model): FIRST = 1 SECOND = 2 THIRD = 3 @classmethod def __getattr__(cls, attr): return Dispatcher(cls, attr) I got more code, but the most important thing is that the Dispatcher class is universal and can be used for any model. The problem is this: SomeOptions().get_first() >> 'Some data from db' SomeOptions.get_first() >> AttributeError: type object 'SomeOptions' has no attribute 'get_first' How can I get the code to work without creating a SomeOptions() … -
Get n number of random records using nested serializers Django REST framework
I'm trying to get random 'n' number of records from foreign key related models. Suppose I have two models named Exam and Questions. I need an API endpoint to get n number of questions for one particular subject(ex. for math, n random math questions). The endpoint is working well in retrieving all the questions for a particular subject. models.py class Exam(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Question(models.Model): exam = models.ForeignKey(Exam, on_delete=models.CASCADE) question = models.CharField(max_length=255) def __str__(self): return '{} - {}'.format(self.question) serializers.py class QuestionSerializer(serializers.ModelSerializer): questions = serializers.CharField(read_only=True) answer = serializers.CharField(read_only=True) class Meta: model = Question fields = '__all__' class ExamSerializer(serializers.ModelSerializer): name = serializers.CharField(read_only=True) questions = QuestionSerializer(many=True, read_only=True, source='question_set') class Meta: model = Exam fields = '__all__' api_views.py class ExamQuestionRetrieveAPIView(generics.RetrieveAPIView): authentication_classes = [JWTTokenUserAuthentication] serializer_class = ExamSerializer queryset = Exam.objects.all() lookup_field = 'name' After going through the doc, I tried to filter and get random records using the to_representation() method but failed. Any help is greatly appreciated. -
Django v3 NoReverseMatch at /signup/
I have a error after signup: Reverse for 'activateuser' with keyword arguments '{'uidb64': 'NzA', 'token': 'ar65ve-0c2f1aaa20521539b574c02e5a6844f5'}' not found. 1 pattern(s) tried: ['activateuser/$'] my url: ... path('signup/', accounts.views.signupuser, name='signupuser'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', ... my view: def signupuser(request): if request.user.is_authenticated: return redirect('/charts/drawchart/v1/metrics/addresses/active_count/') else: form = SignUpForm() if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('accounts/activate_account_mail.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('loginuser') else: return render(request, 'accounts/signup.html', {'form': form}) else: return render(request, 'accounts/signup.html', {'form': form}) def activateuser(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) context = {'uidb64':uidb64, 'token':token} return render(request, '/charts/drawchart/v1/metrics/addresses/active_count/', context) else: return HttpResponse('Activation link is invalid!') and finally my template: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activateuser' uidb64=uid token=token %} {% endautoescape %} -
Django admin interface missing css styling in production
The user interface is working well, and all CSS styling and static files are served correctly, but the admin interface is missing CSS styling. I looked at similar posts but in those posts people had the issue with both the user and the admin interface. My issue is only with the admin interface. Please see my static file settings below from settings.py: STATIC_URL = '/static/' #Location of static files STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') And this is my nginx configuration: server { listen 80; server_name MY_SERVER_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/MYUSERNAME/myproject; } location /media/ { root /home/MYUSERNAME/myproject; } I already executed python manage.py collectstatic on the server and got this message: 0 static files copied to '/home/MYUSERNAME/myproject/staticfiles', 255 unmodified. I restarted nginx after that and also tried emptying my browser cache, but the issue persisted. -
Django: how to create a dictionary of objects and display in templates
Hey I have had a look at similar questions but none really relate to what I am trying to do, they either explain how to order things in the admin panel or simply iterating over object dictionaries. I have created a basic photo model that contains a value gallery_order so I can edit them in Admin. I wish to populate my template with the pictures according to the gallery_order values in order from 1 upward. I guess the best way to handle it is with a dictionary but I do not know where to initialize it, if I put it in the picture model then each picture holds a dict with all the pictures order number and url in it which seems mental. My current model: class Picture(models.Model): title = models.CharField(max_length=36, blank=False, unique=True) gallery_order = models.IntegerField(default=0) image = models.ImageField(upload_to='photos/', blank=False) def __str__(self): return self.title My template code: <head> <meta charset="utf-8"> {% block content %} <div class="row"> {% if pictures %} {% for picture in pictures %} <div class="col-md-12"> <div class="card mb-0"> <img class="card-img-top" src="{{ picture.image.url }}"> </div> </div> {% endfor %} {% endif %} </div> {% endblock content %} </head> my admin code: @admin.register(Picture) class PictureAdmin(admin.ModelAdmin): list_display = ('gallery_order', 'title', … -
Need to override django auto_now_add in pytest factory
Due to auto_now_add in django models sent_at is not working in pytest factory. Need to overrive sent_at for pytest factory class ABC(models.Model): x = models.ForeignKey(X, on_delete=models.CASCADE, related_name="xx") y = models.ForeignKey(Y, on_delete=models.CASCADE, related_name="yy") sent_at = models.DateTimeField(auto_now_add=True) class ABCFactory(factory.django.DjangoModelFactory): x = factory.SubFactory(XFactory) y = factory.SubFactory(YFactory) sent_at = timezone.now() - timezone.timedelta(seconds=40) -
Allow only positive decimal numbers for decimal fields
Within my Django models I have created a decimal field. price = models.DecimalField(default=0, decimal_places=2 How can I make it so that the price is never negative. Is there a way to limit the decimal number to only positive numbers? I have tried MinValueValidator and it did not work.. -
Django crawler just scraping first page
I have a crawler that runs perfectly with simple Python but running it on Django inside an app, only grabs the links from the first page. To run the crawler I'm executing celery -A src worker -l INFO. Any idea why it starts working but suddenly stops? Could it be a Django problem? -
React App as a Django App in a Docker Container - connection refused when trying to access APIs on localhost:8000 urls
hope you might have some guidance for me on this. Right now I have a React app that is part of a Django app (for the sake of ease of passing auth login tokens), which is now containerised in a single Dockerfile. Everything works as intended when it is run as a Docker instance locally, but the Docker Image is having issues, despite the fact that the webpages are visible when the Image is deployed on server. Specifically, when the Docker image is accessed, the home page renders as expected, but then a number of fetch requests which usually go to localhost:8000/<path>/<to>/<url> return the following error: GET http://localhost:8000/<path>/<to>/<url> net::ERR_CONNECTION_REFUSED On a colleague's suggestion, I have tried changing localhost:8000 to the public IP address of the server the Docker Image is hosted on (eg 172.XX.XX.XXX:8000) but when I rebuild the React app, it defaults back to localhost. Here are my questions: Is this something I change from within the React application itself? Do I need manually assign an IP address? (This seems unlikely to me) Or is this something to do with either the Django port settings, or the Dockerfile itself? Here is the Dockerfile FROM ubuntu:18.04 # ... RUN apt-get … -
django-autocomplete-light ModelSelect2Multiple not rendering values
So this is the situation: I am using django-autocomplete-light and I got it working on a few forms, however, when tying to implement it on a M2M field it just doesn't render the values in the select field. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=11, blank=True) customer = models.ManyToManyField("customers.Customer") def __str__(self): return self.user.username class CustomerAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Customer.objects.none() qs = Customer.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class UserProfileForm(autocomplete.FutureModelForm): class Meta: model = UserProfile fields =('__all__') widgets = { 'customer': autocomplete.ModelSelect2Multiple(url='customer-autocomplete'), } in urls.py i got" url(r'^customer-autocomplete/$', CustomerAutocomplete.as_view(),name='customer-autocomplete',), when i got to the autocomplete url: customer-autocomplete/ i got: {"results": [{"id": "2", "text": "Oozz", "selected_text": "Oozz"}, {"id": "1", "text": "Voolia", "selected_text": "Voolia"}, {"id": "3", "text": "Feedspan", "selected_text": "Feedspan"}, {"id": "4", "text": "Layo", "selected_text": "Layo"}, {"id": "5", "text": "Babbleblab", "selected_text": "Babbleblab"}, {"id": "6", "text": "Digitube", "selected_text": "Digitube"}, {"id": "7", "text": "Feednation", "selected_text": "Feednation"}, {"id": "8", "text": "Dabjam", "selected_text": "Dabjam"}, {"id": "9", "text": "Zoomlounge", "selected_text": "Zoomlounge"}, {"id": "10", "text": "Zoomzone", "selected_text": "Zoomzone"}], "pagination": {"more": true}} it renders no customers: However if i remove the widget on my form.py: widgets = { 'customer': autocomplete.ModelSelect2Multiple(url='customer-autocomplete'), } It renders all customers: I guess this issue is not related to … -
I want To get all the categoy 1 level
class categories(models.Model): name = models.CharField(max_length=40) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') I want To get all the categoy 1 level categories2 = categories.objects.get(name=sub-categoy 1 ) categories2.children.all() -
how can I fixs the bug "The client noticed that the server is not a supported distribution of Elasticsearch" [closed]
when I start the django project ,the new error print in the controll ,and there is nothing I changed,what make this happened? -
How can I do to filter zero values using Django?
I am using Django and I have this query : a = User.objects.all() And I would like to remove the entries such as the field a et b are equals to 0. But the problem is that in my field I have either 0 either {"total": 0} but also {"total": 0, "2": 0} And I want that when all the values are 0 I remove that from a. Could you help me please ? Thank you very much ! -
Django web app mail using Sendgrid or Amazon SES - Not receiving emails
Thank you very much for helping people with software issues. I'm developing a simple web application using Django, and I wanted to have a contact form so users can contact me for feedback and other topics. That mail would arrive in my Gmail for simpler communication. I have followed many tutorials and update settings.py, forms.py, and views.py many times and I still have not received any email unless I send it via cmd like this: from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'validated email', ['validated email'] ) I have of course created accounts in both SendGrid and Amazon SES, validate the emails, and used the keys. for views.py I have used these two contact views, one or the other, and I have modified any part of them many times trying to get the receive the email, don't pay attention if there is any indentation issue, with Visual Studio is easily fixed, also validated email is the email I used with SES or Sendgrid from django.shortcuts import render, redirect from .forms import ContactForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if … -
Django get url variables within get_context data?
Say I have a url likes this path( 'foo/<int:foo_id>/edit/', views.FooView.as_view(), name='foo', ), and a view likes this: def get(self, request, foo_id): I find a common idiom is getting the URL variable foo_id into the context. The only thing context has access to be default is request. I tried checking request and request.GET and could not see anything. Is there a better way than: Manually adding url variables to the context_data after get_context_data() or passing it into get_context_data from a custom call from get? (ugly because class based views expect the same get_context_data signature) -
How do I add a header to a Django RequestFactory request?
I am creating an API in Django and my API has few custom views for authenticating with JWTs (getting a token, refreshing a token, etc.). To manually send a GET request to an endpoint that requires authentication, I do this with curl: curl http://example.com/endpoint -H "Authorization: Bearer [ACCESS_TOKEN]" To test the authentication views, I want to write a unit test that makes an authenticated request (using django.test.RequestFactory) with a JWT. How can I add a header to the request? For clarity, below is an example of what I'd like to be able to do, though what I have written below is not valid code because RequestFactory.get() does not have a headers parameter: from django.test import TestCase, RequestFactory class TestClassForAPI(TestCase): def test_an_api_test(self): factory = RequestFactory() token = '...' auth_header = f'Authorization: Bearer {token}' factory.get('/endpoint/', headers=auth_header) -
Capitalization not displayed in Django site after modifying Django models.py [closed]
you see, in the str method, the upper() method is applied, though no result this is the view i get, with no capitalization, even after modifying the code