Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make unit tests on LoginView and LogoutView in Django?
I'm trying to write proper tests for my views which are just subclassess of LoginView and LogoutView from django.contrib.auth.views. from django.contrib.auth.views import LoginView, LogoutView class UserLoginView(LoginView): template_name = 'finder/login.html' next_page = reverse_lazy('book-list') class UserLogoutView(LogoutView): template_name = 'finder/logout.html' next_page = reverse_lazy('book-list') urls.py: path('login/', views.UserLoginView.as_view(), name='login'), path('logout/', views.UserLogoutView.as_view(), name='logout'), path('book/list/', views.BookListView.as_view(), name='book-list'), What should I take in mind and how should I write proper testing cases in my test.views.py? For now I've got something like this: class UserLoginViewTest(TestCase): def setUp(self) -> None: self.factory = RequestFactory() self.user = User.objects.create_user(username='dummy', password='123secret') def test_positive_login_view(self): # request = self.factory.post(path='/login/', data={'username': 'dummy', 'password': '123secret'}) # request.user = self.user # response = views.UserLoginView.as_view()(request) response = self.client.post(path='/login/', data={'username': 'dummy', 'password': '123secret'}) self.assertRedirects(response, '/book/list/') def test_negative_login_view(self): response = self.client.post(path='/login/', data={'username': 'any', 'password': 'any'}) self.assertEqual(response.status_code, 200) But to be honest those tests are strictly suited to responses which I've got back, so e.g. I don't know why my status_code in response with improper credentials is 200 and not something else like 4xx. And what should I test in such auth views? That my user is getting an authenticated status? but how? And second question: how to use requestfactory in this case? I've tried with code which is commented, but got status_code=403 … -
Custom e-commerce or stick to an e-commerce platform?
I am sorry if this the wrong place to ask this question, but i have been asked to build a small e-commerce site, and since it's small i was wondering if i can just build it myself using something Django or PHP, or should i really just stick to ready built in platforms like WordPress or Magento and if so which one do you recommend for a small e-commerce. I am only asking because the more i search the more i find articles telling me i should stick to built in platforms i just wanted one more advice. -
ModuleNotFoundError: No module named 'index,django'
my project name = portfolio my app name = index index - url.py from django.contrib import admin from django.urls import path, include from index import views urlpatterns = [ path('', views.home, name='home'), path('home', views.home, name='home'), path('about', views.about, name='about'), path('project', views.project, name='project'), path('contact', views.contact, name='contact'), portfolio url.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')) ] and views.py from django.shortcuts import render def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def project(request): return render(request, 'project.html') def contact(request): return render(request, 'contact.html') I'm new to django. sorry. -
Elements going inside div tag when using context
My pages have a normal layout like so When trying to include the calendar on the /calendar url everything seems to just squish under the calendar tab. views.py @login_required def calendar(request): context={} results = get_events(request) #context['results'] = results d = date.today() print(d) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(results, withyear=True) context['calendar'] = mark_safe(html_cal) context['nmenu'] = 'calendar' editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm if request.method=="POST": if 'editProfileForm' in request.POST: editProfileForm = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) if editProfileForm.is_valid(): editProfileForm.save() editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm context['is_post'] = False return render(request, "home.html", context) else: context['is_post'] = True context['editProfileForm'] = editProfileForm return render(request, "home.html", context) return render(request, 'home.html', context) calendar.html {% block content %} <style> .calendar { width: 98%; margin: auto; font-size: 13px; } .calendar tr, .calendar td { border: 1px solid black; } .calendar th { padding: 10px; text-align: center; font-size: 18px; } .calendar td { width: 200px; height: 150px; padding: 20px 0px 0px 5px; } .month { font-size: 25px; } .date { font-size: 16px; } ul { height: 100%; padding: 0px 5px 0px 20px; } </style> <h1>Calendar</h1> <button>+</button> {{calendar}} {% endblock %} <!-- <ul> {% for result in results %} <li>{{result.start.date}}{% if result.end.date %}-{% endif%}{{result.end.date}}: {{result.summary}}</li> {% endfor %} </ul> … -
Is it possible to use queryset in the FROM clause
I have a model for user's points collection: class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rating') points = models.IntegerField() Each user could have multiple records in this model. I need to calculate a rank of each user by sum of collected points. For the listing it's easy: Rating.objects.values('user__username').annotate( total_points=Sum('points') ).order_by('-total_points') But how to get rank for a single user by his user_id? I added annotation with numbers of rows: Rating.objects.values('user__username').annotate( total_points=Sum('points') ).annotate( rank=Window( expression=RowNumber(), order_by=[F('total_points').desc()] ) ) it really added correct ranking numbers, but when I try to get a single user by user_id it returns a row with rank=1. It's because the filter condition goes to the WHERE clause and there is a single row with the number 1. I mean this: Rating.objects.values('user__username').annotate( total_points=Sum('points') ).annotate( rank=Window( expression=RowNumber(), order_by=[F('total_points').desc()] ) ).filter(user_id=1) I got the SQL query of this queryset (qs.query) like SELECT ... FROM rating_rating WHERE ... and inserted it into another SQL query as "rank_table" and added a condition into the outside WHERE clause: SELECT * FROM (SELECT ... FROM rating_rating WHERE ...) AS rank_table WHERE user_id = 1; and executed within the MySQL console. And this works exactly as I need. The question is: how to implement the same … -
When i try to sign up after i Deployed my django projects in Heroku this error occurs although it doesn't in my localhost
When i try to sign up in my Django prject which is deployed in Heroku this error occurs although when i try the same think on my localhost it doesn't (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 wwfTXnpKMhQYEw32JsPKVeURPTx0aN-gih7DbYiw9P7hAoVGlm9uAr6nh6wtPSf5RItfk\n5.7.14 U3yBi83J6hZNnidGpRRi0gVOlElqn-aAnjzu2O9HfpxM4jcIC6ut2sAx7C33cch0>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 f14sm18139082qko.117 - gsmtp') Request Method: POST Request URL: http://myportfoliowebsite0.herokuapp.com/signup Django Version: 4.0.2 Exception Type: SMTPAuthenticationError Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 wwfTXnpKMhQYEw32JsPKVeURPTx0aN-gih7DbYiw9P7hAoVGlm9uAr6nh6wtPSf5RItfk\n5.7.14 U3yBi83J6hZNnidGpRRi0gVOlElqn-aAnjzu2O9HfpxM4jcIC6ut2sAx7C33cch0>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 f14sm18139082qko.117 - gsmtp') Exception Location: /app/.heroku/python/lib/python3.9/smtplib.py, line 657, in auth Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Tue, 15 Feb 2022 21:48:46 +0000``` -
For some reason {{ post.message }} is not displaying the modle
I am making a simple site to experiment with manipulating user data. I have a form where the user enters in some info and once they hit submit they get redirected to a new page. On this new page, the info they entered is supposed to be displayed. I am under the impression that you use this {{ Modle_Name.Fild_name}} to inject the info into the HTML. However, it is not working. If any of y'all have a solution I would much appreciate it. sucseus.html {% extends "base.html" %} {% block content %} <h1>success</h1> <h2>{{ post.message }}</h2> {% endblock %} views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from . import forms from forums_simple.models import Post # Create your views here. class Form(generic.CreateView): model = Post template_name = 'forums_simple/form.html' fields = ['message'] success_url = reverse_lazy('forums:sucsseus') class Sucsessus_view(generic.TemplateView): template_name = 'forums_simple/sucseus.html' model = Post models.py from django.db import models # Create your models here. class Post(models.Model): message = models.TextField(blank=True, null=False) created_at = models.DateTimeField(auto_now=True) -
Connect a model to another model on save in admin panel
Sorry for my bad english, but I don't even know how to properly describe my problem. I have 3 models: class Book(models.Model): source=models.ForeignKey(Original, on_delete=models.CASCADE, related_name='book', null=True, blank=True) ... class Original(models.Model): ... class Title(models.Model): book = models.OneToOneField(Book, on_delete=models.CASCADE, related_name='item', null=True, blank=True) original = models.OneToOneField(Original, on_delete=models.CASCADE, related_name='item', null=True, blank=True) original_name = models.CharField(max_length=300, null=True, blank=True) ... In my admin page, when i creating Book instance i writing it's name to Title model as inline and i want to have an option: 1.Fill in the original_name form manually if no source given 2.If source given, leave this field empty,but when saving connect that Book instance to original field in Title model. In the end i want to have a Title model that have original_name and reference to original and book instances, if source given and from which in the future I may refer to the original_name when needed I tried to implement this using save_model function, but i have no clue how set Book instance as original field in Title model I think it must be pretty easy, but i dont know where to start and its frustrating... -
Module not found: how to install django-parsley in a Django project?
This is such a basic question, I'm sorry. I installed django-parsley with poetry (poetry add django-parsley). It's clearly installed in my pyproject.toml file. However, when I try to run python manage.py runserver, I get the following error: from parsley.decorators import parsleyfy ModuleNotFoundError: No module named 'parsley' I also tried adding 'parsley' to my INSTALLED_APPS in settings.py. That gives me this error (which is maybe due to not adding it globally with pip install?): ...some more errors... File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'parsley' What do I need to do to be able to import it in a python file in my project? -
Django support chat with site administration
How do I create a django support chat on my site? Are there ready-made solutions or some additional Python package for development? -
How to pass on django form results to a text box
I haven't been coding for more than a year now and am being a little rusty on some aspects. I have a django form designed using crispy_forms. Nothing very original : a bunch of radiobuttons, textbox... Goal: My purpose is to have a generate_report button that once being clicked on open below the button a textbox with a text generated using the values picked for the former fields. I created in models a __str__ method with the text I want. But I'm not sure that's the proper place for such a function. I can have a text box hidden that only shows once someone click on the generate_report button using javascript, but I don't know how to pass on the text with the data. Any idea? [forms.py] from .models import Foo from crispy_forms import bootstrap, helper, layout class FooForm(forms.ModelForm): class Meta: model = Foo fields = "__all__" def __init__(self, request, *args, **kwargs): self.request = request super().__init__(*args, **kwargs) actions = bootstrap.FormActions(layout.Submit("save", _("Save")), bootstrap.StrictButton("generate_report", css_class="btn-success")) self.helper = helper.FormHelper() self.helper.form_action = self.request.path self.helper.form_method = "POST" self.helper.form_class = "blueForms" self.helper.layout = layout.Layout( field1, field2, field3, actions ) self.form_tag = False self.render_required_fields = False -
Django navbar view changed and unstable
I supposed to have the navbar like the this. but when I first runserver with my appA, it always show the navbar like a list menu, like the figure 2. If I run another appB runserver and rerun myapp A, the navbar goes normal like figure1. So it looks like if I want to get the normal Navbar in appA, I should first run anther appB and then I can get the normal navbar for appA This is the navbar what I get if I run appA first after I open my computer. Thak you very much for any kind suggestions. It looks like the problem of static. -
Designing an intranet website using a safe Python framework
I want to develop a website using Python. This intranet website would only allow access to users internally within our company. After a quick search on suggested frameworks, I found Django, Flask and a few others. I have a question, and forgive me if I get the terminology wrong etc. My question: Is it safe to use a web framework like Django, for an internal website. My concern is that perhaps there are functions within the framework that make external calls to the greater internet. Thank in advance Garrett -
Django: Makemigration Error "models.E028" and "models.E340" after extending Authuser (legacy MySQL)
I connected my Django project to a legacy MySQL DB and did a first migration. I then extended the AuthUser model with a "NewUser" model (made sure that AUTH_USER_MODEL settings.py to reference 'appname.NewUser') When running makemigrations I get these error messages: models.E028 account_emailaddress: (models.E028) db_table 'account_emailaddress' is used by multiple models: seasonscan_api.AccountEmailaddress, account.EmailAddress. account_emailconfirmation: (models.E028) ...(same error) auth_group: (models.E028) ...(same error) auth_permission: (models.E028) ...(same error) django_admin_log: (models.E028) ...(same error) django_content_type: (models.E028) ...(same error) django_session: (models.E028) ...(same error) django_site: (models.E028) ...(same error) socialaccount_socialaccount: (models.E028) ...(same error) socialaccount_socialapp: (models.E028) ...(same error) socialaccount_socialtoken: (models.E028) ...(same error) fields.E340 auth.Group.permissions: (fields.E340) The field's intermediary table 'auth_group_permissions' clashes with the table name of 'seasonscan_api.AuthGroupPermissions'. socialaccount.SocialApp.sites: (fields.E340) ...(same error) I checked the docs which didnt show more than the error message without additional info. Any advice would help me a lot. Here the models as reference: from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db.models.signals import post_save class AuthGroup(models.Model): name = models.CharField(unique=True, max_length=150) class Meta: managed = True db_table = 'auth_group' class AuthGroupPermissions(models.Model): id = models.BigAutoField(primary_key=True) group = models.ForeignKey('AuthGroup', on_delete=models.CASCADE, related_name='authgroup_authgrouppermissions') permission = models.ForeignKey('AuthPermission', on_delete=models.CASCADE, related_name='authpermission_authgrouppermissions') class Meta: managed = True db_table = 'auth_group_permissions' unique_together = (('group', 'permission'),) … -
Django Send Mail keeps throwing WSGI error
So i was this application in which when a user fill the form, I get an email with their details so that i can contact them. But when ever the form is submitted, it shows me this error. I couldn't find whats bugging the code. All the credentials are in place. I am using SendingBlue smtp server for this project. Have a look at my code: views.py from django.shortcuts import render, redirect from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect # Create your views here. def home(request): return render(request, 'index.html') def register(request): if request.method == 'GET': return render(request, 'register.html') else: name = request.POST['full-name'] email = request.POST['email'] phone = request.POST['phone'] nationality = request.POST['nationality'] try: send_mail("Trial Application", name + email + phone + nationality, '*my email*', ['* same email*']) except BadHeaderError: return HttpResponse('Something Went Wrong') return redirect(request, 'index.html') return render(request, 'register.html') settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp-relay.sendinblue.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "*my email*" EMAIL_HOST_PASSWORD = "password" register.html <form action="" method="post" class="form"> {% csrf_token %} <fieldset> <legend>Please fill in the required details</legend> <input type="text" name="full-name" placeholder="Full Name" id=""> <input type="email" name="email" placeholder="Email" id=""> <input type="tel" name="phone" placeholder="Phone Number" id=""> <input type="text" name="nationality" placeholder="Nationality" id=""> <input type="submit" … -
Django - Adding up values in an object's many to many field?
I have 2 classes class Service(models.Model): service_name = models.CharField(max_length=15, blank=False) service_time = models.IntegerField(blank=False) class Appointment(models.Model): name = models.CharField(max_length=15) service_selected = models.ManytoManyField(Service, blank=True) total_time = models.IntegerField(null=True, blank=True) What Im trying to do is that after a user has selected the services and created an appointment, each of the services' service_time will be added up to equal total_time I know I have to use something along the lines of #in class Appointment def save(self, *args, **kwargs): self.total_time += self.service_selected.service_time #it needs to add up all of the service_time from each service selected but that's where Im lost super(Appointment, self).save(*args, **kwargs) But I don't know how to get the service_time value from each of the service_name that were selected, or how to query for every service_selected chosen in that appointment's object so that I can add up those values. -
Django: disable querysets from console
After python manage.py runserver and doing a request to the server, console displays logs of querysets for model instances for a given view. It's fine, helpful even, until trying python manage.py test, it's simply unnecessary and annoying while running tests. I've tried to disable those logs with logging.disable(logging.CRITICAL) or logging.disable() (critical is supposed to be the default value), but without any effect. I tried to put in in settings.py on condition i'm running the test environment, then i tried to make it work no matter the environment - I even tried to put it in setUp functions of test files or in test functions themselves. I also tried to modify the LOGGING variable in settings.py in various ways. Nothing worked. -
Django ORM and cursor which is better in the context of performance?
In our company there are large set of data and many db tables and we developed the backend by using Django REST and hosted in AWS and S3. Now the problem is , as a large size of data it takes too much time to fetch from the db while using Django ORM. So I need an alternative of this which provides an effective solution by faster access. So what to use incase of this? ORM/cursor/raw_sql/ or something else ? -
heroku django "file does not exist" when i try to download it from the server
I successfully deployed my app to heroku server but faced this problem when i try to download a file (like with <a href="{{object.file.url}}">Download</a>) django return "Page not found" with error "file 'app/.../.../{file}' does not exist" ("app" is not real app name. I don't know, where does it come from). Other static files (like with href="{% static "path/to/file" %}") work great. The same thing in the admin panel, when I go to the model instance, which stores the path to the file - the path is displayed, but nothing is downloaded from there. What should i do? -
'object has no attribute' when running TestCase
I´m following a django tests tutorial, but in my case the AttributeError appears from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient class RecipeImageUploadTests(TestCase): def setUP(self): self.client = APIClient() self.user = get_user_model().objects.create_user( 'user@kubousky.com', 'testpass' ) self.client.force_authenticate(self.user) self.recipe = sample_recipe(user=self.user) def tearDown(self): self.recipe.image.delete() def test_upload_image_to_recipe(self): """Test uploading an image to recipe""" url = image_upload_url(self.recipe.id) The error refers to "self.recipe" says: 'RecipeImageUploadTests' object has no attribute 'recipe' There is not much about setUP() in docs. Wonder why I can set self.user and not any other attribute -
How would I specify a data table that I have set up postgresql?
I am looking to set up the backend logic for a form where it shoots information to a data table that I set up in postgresql and was wondering, how I would specify the data table that I want to send the information to? -
is there any way to get Django to read react components?
i am trying to import my react project to Django. I set up webpack, babel and finally all the backend ... But when I tried to import React's 'index.js' file it reads it successfully but fails to write it into the page's DOM. I tried testing the file without React and everything works fine, however, does anyone know how to give me some advice? -
Django views with SSE and external scripts
If there is a better way to accomplish this, please let me know. I need to synchronously process data outside of a view, then only after data is processed in an external function redirect or open a new view. File is uploaded from an HTML page, which routes the file to views. Threading in views begins processing data in script outside of views. Views returns a view to display the data as it's being processed using SSE. External script sends data using send_event('test', 'message',{'text': stuff} Here's where I'm stuck: I've tried using the Javascript event listener to watch for certain text that then does a window.open('newview'), as I have a view that downloads the CSV the script creates. I'm having a problem going from one view (with an active SSE connection) to another while waiting on the thread that is processing data to finish. I've tried a second thread in views.py that returns another response when thread x is finished. I have to return render from the first view so that the live data shows to the client. Html for upload: <form action="/viewFunction/" method="POST" enctype="multipart/form-data" form target="_blank"> {% csrf_token %} <input type="file" id="fileform" name="filename"> <input type="submit" id="fileform"> views.py: def viewFunction(request): … -
Using inlineformset_factory getting incorrect id's from foreign key
I'm trying to use inlineformset_factory to generate a series of number boxes within a table to update the additional field in a through table from a self referential many-to-many relationship. views.py def edit_assembly(request, slug): root = Part.objects.get(slug=slug) forms = inlineformset_factory(Part, Relationship, fields=('qty',), fk_name="child", can_delete=False) if request.method == 'POST': formset = forms(request.POST) if formset.is_valid(): formset.save() else: formset = forms(instance=root) return render(request, "app/edit_assembly.html", { "formset": formset }) models.py class Part(models.Model): part_number = models.IntegerField() slug = models.SlugField(unique=True) name = models.CharField(max_length=40) children = models.ManyToManyField( 'self', symmetrical=False, through='Relationship', through_fields=('parent', 'child'), blank=True) class Relationship(models.Model): qty = models.IntegerField(default=1) parent = models.ForeignKey( Part, on_delete=models.CASCADE, related_name='parent', null=True) child = models.ForeignKey( Part, on_delete=models.CASCADE, related_name='child', null=True) template: <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} <br> {% endfor %} <input type="submit" value="Submit"> </form> Whatever I try I cannot seem to return a valid form. When I look at the page source with my browser the ID's that are assigned to the hidden fields in each form are not what I would expect. currently am experiencing the error: "(Hidden field child) The inline value did not match the parent instance." I suspect the hidden field child should contain the foreign key for the … -
Override create method
New to drf.I have json input data like below: { "name":"df", "email":"d@gmail.com", "age":"21", "gender":"Male", "phone":"234", "total_price":86, "advance":0, "due":86, "selected":[{"id":8,"name":"sdf","price":34},{"id":9,"name":"dg","price":52}] } Below is my views.py.I want to override create method for the json input data.But no idea how to do it. class PatientEntry(generics.CreateAPIView): queryset = Test.objects.all() serializer_class = PatientSerializer def create(self, request, *args, **kwargs): many = isinstance(request.data, list) serializer = self.get_serializer(data=request.data,many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, headers=headers)