Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add a method to a model field declared in Meta class
Is it possible to add a method to a field declared in the FilterSet Meta class, that processes the value given before filtering? In the following class MoldelAFilter(filters.FilterSet): class Meta: model = ModelA fields = { 'name': ['exact', 'contain'], 'ts': ['exact', 'gt', 'lt'] } I want to process the value passed to 'ts' (p.e: '2020-11-02') before filtering -
Choose where put business logic in Service Layer Architecture
I have two models, User and Post. An user have many Post. If i want to get all posts of an user, that logic belongs to an UserService or a PostService? Actually i have this class User: -
Instantly update fields of forms - Django
I am still on the way to learning Django. I am going to create an app. That would essentially be an instant financial ratios calculator. Which would comprise of various forms (say like Loan calculations, Mortgage calculations, interest calculations, etc, etc. one field from one form(Loan calculator) would also be part of other single or multiple forms. The target (field on another form) will need to be instantly updated as the user is updating the inputs on the form Using the typical approach of forms and views (that will essentially bind to HTTP [get/post]). I am looking for a way to have the field (derived from one field) updated instantly as soon as an input is received from the user. The basic example is here https://html.form.guide/calculation-forms/simple-html-calculation-form/ I am keen to use Django, what do you guys suggest would be the best approach to undertaking the above-mentioned tasks and at the same time satisfying the instant field update criterion as in the link above? Looking for some guidance. -
django authenticate Nonetype, admin wrong password
I'm currently building a django application but when I create a superuser using python manage.py createsuperuserand try to login to the admin I keep receiving the Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. warning. Aditionally, trying to run: >>> from django.contrib.auth import authenticate >>> u = authenticate(username="user", password="pass") >>> type(u) <type 'NoneType'> This is my user model: class users_user(AbstractUser): pk_iduser = models.AutoField(db_column='PK_IdUsers', primary_key=True) # Field name made lowercase. name = models.CharField(max_length=132, verbose_name='password') surname = models.CharField(max_length=132, verbose_name='password') email = models.CharField(max_length=132, verbose_name='password') password = models.CharField(max_length=132, verbose_name='password') is_active = models.BooleanField(db_column='is_active',default=False) is_reset_password = models.BooleanField(db_column='is_resset_password',default=False) date_reset_password = models.DateTimeField(db_column='date_resset_password',blank=True, null=True) phone = models.CharField(max_length=50,db_column='phone',blank=True, null=True) country = models.IntegerField(db_column='Country',blank=True, null=True) city = models.CharField(max_length=100,db_column='city',blank=True, null=True) address = models.CharField(max_length=255,db_column='address',blank=True, null=True) is_active = models.BooleanField(db_column='is_active',default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) class Meta: db_table = 'users_user' verbose_name_plural = "users" def __str__(self): return '{}'.format(self.pk_iduser) In my UserManager class tried both ways suspecting password was in text format: user.set_password(password) and user.set_password("password") None worked. The class: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) … -
Why I cannot access to this page with urls.py?
I have a very simple question but I don't achieve to solve this problem : my url is the following : http://localhost:8000/myApp/activate/eyJ1c2VybmFtZSI6InJvbWFyaWM5MSIsImFjdGlvbiI6ImFjdGl2YXRpb24ifQ:1lDysD:ZdbBiSLf0zjSWM-fpvUn_oeEG-5h6GuW4MhSkipPa38 And in my urls.py I define that : urlpatterns = [ re_path(r'activate/(?P<hashtag>)/', views.index), ] But I got that : Page not found (404) I need to catch the variable hashtag but I don't know why it does not work... Could you help me please ? Thank you very much ! -
Django AuthenticationForm required fields
I need to add required class to a div element to render the fields of AuthenticationForm. But for a reason I can't understand, inside the template, form.password.required does not evaluate to True: <div class="field {% if form.password.required %}required{% endif %}"> {{ form.password.label_tag }} {{ form.password }} </div> Problem is, when I instantiate a form manually >>> from django.contrib.auth.forms import AuthenticationForm >>> f = AuthenticationForm(None, {"password": "foo", "username":"bar"}) >>> f.is_valid() >>> f.fields["password"].required # is true Why isn't it true in the template ? -
Using pytest-django and setup takes 7 or 8 minutes?
I am setting up pytest testing for our Django site and it is taking seven or eight (7 or 8) minutes to finish running a single test in which less than a hundred objects are created. This feels like its going to be a massive impediment to developing tests if I can only try five things an hour (given that I will be sure to waste several of those tries on stupid mistakes like typos in filepaths.) platform win32 -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 Django 3.1.5 Our site uses django-simple-history (which creates a history counterpart of every table) and django-taggit, and has maybe 25 different apps, of which a couple provide widely reused models (if that matters). Could be 100 or more models all up. My laptop has 8Gb RAM, and an older i7 CPU. I have set the reusedb option in pytest.ini, but there is no perceptible change. Is this a fixable problem? -
Is it possible to call a graphQL mutation into an url?
I would like to know if it is possible to execute a graphQL mutation in a url ? I precise I am using Django with graphene. because I have this graphQL query which allow to confirm or not the email : mutation { verifyAccount(token: "eyJ1c2VybmFtZSI6InJ") { success errors } } And actually I receive an email with the following link : http://localhost:8000/activate/eyJ1c2VybmFtZSI6InJ This link is useful to confirm my email but I didn't define this in my urls.py so I get a 404 error which is normal. I precise when I use graphiQL to test the query, I got a success so it is okay for this part. -
django website workflow for aws ubuntu server
hello everyone i have weird question well its really random in internet and it dend whos what need what type of databses eg i have seen how api is made in heroku or docker but cannt find what is after that i am creating django on ubuntu for server host i have nginx and for usgi gunicorn also database postgresql all in aws webservice so its kanda hard when its problem where to find tutorial by this configuration or which version is out of date so i will make this all in docker which will be my server and i will use development settings to run in localhost also all this configured by ylm file so when it comes database i still be able to connect my aws database by my computer right? when my website will be ready , how can i take this all file to my server its all created in ubuntu? to take yml file and setups this files with settings righ bcs i use git and it changes users and groups also i really make big mess and now dont know where gone my problem also tryng to find project which is basic autorisation when … -
Get name of the element on template shown from database
I'm using for loop to show some data on template from models. With every loop I'm rendering a button with the elements. How can I get that particular looped element's id when the button which was rendered with it was clicked. For example if I click on approve button in the second row, I need to get id, username, etc. from that row. Image for above problem template.html {% for applications in applications %} <div class="applicationList"> <table style="width:100%"> <tr> <th>Request ID</th> <th>Employee</th> <th>Reason for Leave</th> <th>From Date</th> <th>To Date</th> <th>Approve/Deny</th> </tr> <tr> <td>{{ applications.id }}</td> <td>{{ applications.user }}</td> <td>{{ applications.reason }}</td> <td>{{ applications.from_date }}</td> <td>{{ applications.to_date }}</td> <td> <form method="POST"> {% csrf_token %} <input class="appproveButton appproveButtonYes" type="submit" name="approve" value="Approve"> <input type="submit" class="appproveButton appproveButtonNo"name="deny" value="Deny"> </form> </td> </tr> </table> </div {% endfor %} views.py @login_required(login_url='login/') def applications_view(request): if request.user.is_superuser: applications = LeaveApplication.objects.all() if request.method == "POST": pass context = { 'applications': applications } return render(request, 'home/applications.html', context) -
How can i write the urlpattern in a template calling a view function
Url.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path("", views.index, name= 'homepage'), url(r'^(?P<single_link>[0-9]+)/$', views.single_link, name='detail'), path("reserve_link/<str:print_link>", views.reserve_link, name='reserve_link') ] Views.py def single_link(request, single_link): try: movie_details = MovieSection.objects.get(pk=single_link) movi = MovieDetails.objects.get(movie_section__pk= single_link) except MovieSection.DoesNotExist: raise Http404("Movie does not exist") return render(request, "reviewmovie.html", {"part_ones": movie_details, "movi": movi}) def reserve_link(request, print_link): reserve = get_object_or_404(Ticket, movie_details__pk=print_link) context = {'reserve': reserve} return render(request, "reserve.html", context) Models.py class Ticket(models.Model): movie_details = models.ForeignKey(MovieDetails, on_delete= models.CASCADE) movie_section = models.ForeignKey(MovieSection, on_delete= models.CASCADE) price = models.CharField(max_length=20) movie_time = models.DateTimeField("Ticket time") ticket_link = models.CharField(max_length=20) HTML template <a href="{% url 'reserve_link' %}">Seat Reservation</a> My question is how How will i write a correct urlpattern that will call the reserve_link view function The single_link function generate a details page in the generated page, there should be a page gotten from the details to display some information. How will i write a view function to call that page. How will i write the ink in html template. -
How to hide items before filtering in django templates?
i have a simple website and i want to test the filters but i have a problem ! i don't want user to see all results i want him to see only the filtered one before start filtering or searching and here is my CODE -
Django queryset seach function isn't working. Returns unfiltered results
I' trying to implement a search function but when I enter a query into the search bar it doesn't filter anything and returns everything as is, unfiltered. forum\views.py def forum(request): context = {} # passing the query to the search bar query = "" if request.GET: query = request.GET['q'] context['query'] = str(query) posts = sorted(get_forum_queryset(query), key=attrgetter('created_at'), reverse=True) return render(request, 'forum/discussion-forum.html') def get_forum_queryset(query=None): queryset = [] queries = query.split(" ") for q in queries: posts = Post.objects.filter( Q(title__icontains=q) | Q(contents__icontains=q) | Q(tag__icontains=q) ).distinct() for post in posts: queryset.append(post) return list(set(queryset)) core\templates\core\base.html <div class="search-bar"> <form class="form-inline" method="GET"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class='bx bx-search' ></i></span> </div> <input type="text" class="form-control" name="q" placeholder="Search" id="id_q"> </div> </form> </div> In order to set the value to {{query}} to the input attribute, I set the value using javascript because it wasn't working when I did so in the html <script type="text/javascript"> document.getElementById("id_q").value = "{{query}}" </script> forum\templates\forum\discussion-forum.html {% extends 'core/base.html' %} {% block content %} {% if posts %} {% for post in posts %} # post the posts {% endfor %} {%else%} <div class="container content-section"> <div class="row"> <div class="card m-auto"> <div class="card-body mt-2 mb-2"> <h2 class="card-title"> No results found </h2> <p class="card-body"> Thre were no results … -
Django List Related Objects
how can I list related objects qs = response.context_data['cl'].queryset metrics = { 'totalAnswers' : models.Count('QuestionAnswer', distinct=True), 'totalUsersAnswer' : models.Count('QuestionAnswer__UsersAnswer'), } response.context_data['summary'] = list( qs .values('Question') .annotate(**metrics) .order_by('-totalUsersAnswer') ) Question : How I Can List all Objects in QuestionAnswer ? -
expected bytes-like object, not InMemoryUploadedFile Sending Email
I am trying to create a view that will send the contents of a form through email. I am struggling with sending the file uploaded by the user. I get the following error. expected bytes-like object, not InMemoryUploadedFile I've done a bit of research on this and I think its because I am trying to send the file object which is not the expected format for EmailMessage def jobSeeker(request): """Example View""" context = {} if request.method != 'POST': form = EmployeeForm() else: form = EmployeeForm(request.POST, request.FILES) if form.is_valid(): first_name = request.POST['first_name'] last_name = request.POST['last_name'] phone = request.POST['phone'] email = request.POST['email'] resume = request.FILES['resume'] message = 'Example message here' # send an email ct = datetime.datetime.now() email_message = EmailMessage( first_name + ' is looking for a new oppportunity!', message, email, ['XXXX.@XXXcom'] ) filename = last_name email_message.attach(filename, resume) email_message.send() print("Message sent!") context['first_name'] = first_name messages.add_message(request, messages.SUCCESS, 'Message was sent! We will be in touch shortly.') return HttpResponseRedirect(reverse('emails:jobSeeker')) context['form'] = form return render(request, 'job-seeker.html', context) -
Django admin Filter Horizontal Widget limitation on number of objects
I have a Many-to-many relationship in my Django model. On my admin page, I used filter_horizontal = ["destination_name"] to display this relationship. As my data grows up if the relationship includes more than 1000 rows for an object, the "filter_horizonal" widget shows only the first 1000 objects in the relationship. Can anyone help me to resolve this problem on the admin page? -
Ignore Django Model fields in migrations
I want to create a Django model that contains a FileField to store image and video files, but I want to validate the files before saving the instance. I've thought about adding three fields: file: A FileField field. This will only be used to have a file column in the database, but serializers won't use it (instead they will use the two next fields). file_image: An ImageField to perform image file validation. Before the model instance is saved, the file will be assigned to the file field. I don't want this field to have a dabatase representation. file_video: A VideoField (custom field) to perform video file validation. Before the model instance is saved, the file will be assigned to the file field. I don't want this field to have a dabatase representation. Of course, file_image and file_video won't be set at the same time. The problem is preventing makemigrations from including file_image and file_video in the migrations. I could edit the migration file by hand, but I wonder if there is any way to automatically ignore these fields. class MyModel(models.Model): file = models.ImageField() file_image = models.ImageField() # Not an actual column file_video = models.ImageField() # Not an actual column def … -
PyTest-fixtures: Let data persist (Django)
I like pytest-django fixtures and use them in my django application. But from time to time I would like to have data to play around. Up to now the pytest fixtures are only in the temporary database. My goal: I would like to have a button in my django-web GUI. If I press the button a list of my pytest fixtures should get called inside the normal database. If I try to call the fixtures directly in a django view, I get this message: Failed: Fixture "waiting_for_activation_user" called directly. Fixtures are not meant to be called directly, but are created automatically when test functions request them as parameters. See https://docs.pytest.org/en/stable/fixture.html for more information about fixtures, and https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code. Of course I could ignore that the test fixtures exist, and implement the "create test-data" button with the help of the Django ORM method update_or_create(). But that's not nice, since I need to implement the creation of test data twice Has anybody a solution, so that I need write the code to create test-data only once, and I can use it twice (once for the pytext fixture, once for the button)? -
How to set cookie without response in Django or DRF?
I tried this response = Response() method but it is not set in the browser cookie Because my function return user and token instead of response.Any possibility to set cookie in browser without response or httpResponse?.. views.py(It does not work): def authenticate(self, request): ...... new_access_token = result.get('access') response = Response() response.set_signed_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE_ACCESS'], value = new_access_token, salt = settings.SIMPLE_JWT['AUTH_COOKIE_SALT'], expires = 214748364, secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) return self.get_user(validated_token),validated_token Please help me I am very confuse for this. -
Strange behaviour with e-mails between Django and Google
I have configured my Django settings to send an e-mail using gmail (for password reset) However, I'm facing a strange behaviour from Google: Locally, it works fine, when I use my Django app and I get the report that an email has been sent; Deployed on DigitalOcean, using the shell, it works fine: >>> from django.core.mail import send_mail >>> send_mail("Objet3", "Message body", "from.eg@gmail.com",['to.eg@gmail.com'], fail_silently=False) 1 However, when using the deployed app, I always get a Server Error 500, which is reported as such by Sentry: SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError f6sm10267338edk.13 - gsmtp', 'webmaster@localhost') It's really puzzling, as at Gmail: I have decreased the level of security, I have created an App pass and implemented it... Does anyone have an idea, where it may come from ? -
Trouble in Emperor modo - Django Production
I deployed django on Digital Ocean. I followed the documentation for configuring Emperor mode. Everything works fine until the command cd / home / tiago / base_email && uwsgi --ini uwsgi.ini. ''' This is the uwsgi.ini configuration: [uwsgi] chdir = / home / tiago / base_email module = logmail.wsgi home = / home / tiago / venv master = true processes = 10 chmod-socket = 666 socket = /home/tiago/base_email/mysite.sock vacuum = true I made the following commands: sudo mkdir -p / etc / uwsgi / vassals sudo ln -s /home/tiago/base_email/uwsgi.ini / etc / uwsgi / vassals and to execute the emperor: / home / tiago / venv / bin / uwsgi --emperor / etc / uwsgi / vassals --uid www-data --gid www-data error message is: *** Starting uWSGI 2.0.19.1 (64bit) on [Sun Feb 21 20:07:12 2021] *** compiled with version: 9.3.0 on 21 February 2021 15:18:54 os: Linux-5.4.0-65-generic # 73-Ubuntu SMP Mon Jan 18 17:25:17 UTC 2021 nodename: ubuntu-s-1vcpu-1gb-nyc3-01 machine: x86_64 clock source: unix pcre jit disabled detected number of CPU colors: 1 current working directory: / root detected binary path: / home / tiago / venv / bin / uwsgi setgid () to 33 setuid () to 33 *** … -
how to solve django user log in wont work at all
I havent built a django app from scratch in a little while but something is definitely going wrong below. I m using Django 3.0 and created in settings.py AUTH_USER_MODEL = 'users.CustomUser' MODELS.py class CustomUser(AbstractUser): GENDER_CHOICES = ( ("Male", "Male"), ("Woman", "Woman"), ) bio = models.CharField(max_length=200) gender = models.CharField(max_length=30, choices=GENDER_CHOICES) to add fields in the models to the User now when i try to implement the login, it doesnt work at all FORMS.py class UserLoginForm(forms.Form): """Validate Login form username and password.""" username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') print("form username", username) print("form password", password) URLS.py app_name = 'core' urlpatterns = [ path('', views.home, name='home'), path('login/', views.login_view, name='login'), ] VIEWS.py def login_view(request): form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) print("username", username) # HERE print("password", password) # HERE print("user", user) if user is not None: form = login(request, user) print("HERE form", form) # HERE return redirect('core:home') else: print("Error") form = UserLoginForm(request.POST or None) context = {'form': form} return render(request, 'core/login.html', context) here the result below of using print TERMINAL output form username james001 form password somepassword username james001 password somepassword user None < === … -
django.db.utils.ProgrammingError: relation "database_class" does not exist
I have been recently working on a project that just parses data from csv file to the django models stored in a PostgreSQL database. Running "makemigrations" and "migrate" are fine as long as I comment out the parse function but when I do runserver with the function now uncommented the error "django.db.utils.ProgrammingError: relation "database_class" does not exist". Code: import csv import os import time import json from django.db import models from django.core import serializers from django.contrib.postgres.fields import ArrayField BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Individual class model class Class(models.Model): prefix = models.CharField(max_length=10) ID = models.IntegerField(null=False, blank=False) name = models.TextField(null=False, blank=False) description = models.TextField(null=False, blank=False) HI = models.IntegerField(null=False, blank=False, default=0) CI = models.IntegerField(null=False, blank=False, default=0) DI = models.IntegerField(null=False, blank=False, default=0) fall = models.IntegerField(null=False, blank=False, default=0) spring = models.IntegerField(null=False, blank=False, default=0) summer = models.IntegerField(null=False, blank=False, default=0) pathways = ArrayField(models.CharField(max_length=150, blank=True), default=list, size=10, null=True, blank=True) def __str__(self): return self.name #Parse through CSV file def parse(): # Get the absolute csv file csvFile = os.getcwd() + "/" + "HassPathways.csv" # Open the file with open(csvFile, 'r') as file: # Read it and note the delimeter file_r = csv.reader(file, delimiter=',') # Loop through teh columns for col in file_r: # Skip the empty empty data (work on … -
Django - model have date in string 'MM/DD/YYYY' how can I order_by(date) in this situation?
I have models with date information in string in 'MM/DD/YYYY' format. I would like to make a query of this models and order them by this date. But in order to do it I will need to convert this date to format readable by django. I know that I could add additional field to my model and make a script that would fill this field with datetime format but I would like to do it (if possible) while making query, since this won't be used much. Once I solved similar problem by using this kind of code: sorted(information, key=lambda k: pendulum.from_format(k['date'], 'MMMM DD, YYYY')) pendulum.from_format in sorted() let me do this 'on the fly' in one line. I am wondering If I could somehow incorporate in django order_by() this pendulum.from_format? -
How do I define name of the column in Model.objects.values_list(named=True) if I use for this column Cast('column_name', CharField())
A want to retrieve query set of specific model's fields as a list of named tuples (precisely speaking django <Row> objects). I constructed further query: ModelName.values_list('id', Cast('date', CharField()), 'title', named=True) Amid other columns I want to retrieve date which is DateTimeField() as a string (and do it right away, without any further processing). But there is a problem: this "casted" datetime string in result have name "cast1". <QuerySet [Row(id=1, cast1='2021-02-21 16:26:03.85+00', title='some title')] Can i somehow define it's name in Row object direct in .value_list() method and not dealing with .annotate() method?