Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django forms - what is difference between form.fields and class var?
I wanted to make a dropdown-list that removes data with submit button. <form method="post"> <label for="id_title">Select:</label> <select name="title" id="id_title"> <option value="Return of the Jedi">Return of the Jedi</option> <option value="The Force Awakens">The Force Awakens</option> </select> <input type="submit" value="remove"> </form> and my views.py: def remove(request): if request.method == 'POST': form = forms.TitleDropDownForm(request.POST) if form.is_valid(): (col_name, val), = form.cleaned_data.items() psy.delete_movie_from_table( table='ex04_movies', col_name=col_name, val=val ) return redirect(request.META.get('HTTP_REFERER')) else: form = forms.TitleDropDownForm() form.reload() return render(request, 'ex04/remove.html', context={'form' : form}) forms.py: class TitleDropDownForm(forms.Form): def get_title(): try: conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret') try: cur = conn.cursor() cur.execute(""" SELECT title FROM %s; """ % ('ex04_movies', ) ) res = cur.fetchall() except Exception as e: return [] else: conn.commit() conn.close() cur.close() ret = [] for tup in res: ret.append((tup[0], tup[0])) return ret except Exception as e: return ret title = forms.ChoiceField(label='Select', choices=get_title()) def reload(self): # TitleDropDownForm.title = forms.ChoiceField(label='Select', choices=TitleDropDownForm.get_title()) self.fields['title'] = forms.ChoiceField(label='Select', choices=TitleDropDownForm.get_title()) When I tried reloading form with class var like comment, the page did not display changed DB properly. But It works after modifying Form.title to self.fields['title']. What is difference between two methods, and how does it work? -
How to queryset filter with two lists?
I have two list and I want to filter the values from table. I was using this query but this is giving me unions of two list i.e OR. I want something with AND i.e filter values this way retail_item_list = [100,120] and city_id_list = [1,2] the output should be on the basis of these combination (100,1) (120,2) val = list(KVIItem.objects.filter(Q(retail_item_id__in=retail_item_list, cms_city_id__in=city_id_list)).values("retail_item_id","cms_city_id","active","id").order_by('-id')) -
How to manage long running tasks via website
I have a django website, where I can register some event listeners and monitoring tasks on certain websites, see an info about these tasks, edit, delete, etc. These tasks are long running, so I launch them as tasks in a asyncio event loop. I want them to be independent on the django website, so I run these tasks in event loop alongside Sanic webserver, and control it with api calls from the django server. I dont know why, but I still feel that this solution is pretty scuffed, so is there a better way to do it? I was thinking about using kubernetes, but these tasks arent resource heavy and are simple, so I dont think it's worth launching new pod for each. Thanks for help. -
Import Error when i try to set AUTHENTICATION_BACKENDS
i created a module in my project directory like this: -Project Directory -Project Name -modules -emailauth.py settings.py -app name and when i add this code to Settings.py: AUTHENTICATION_BACKENDS = ('.modules.emailauth.EmailBackend') i get the error: ValueError at /login/ Empty module name and when i try: AUTHENTICATION_BACKENDS = ('modules.emailauth.EmailBackend') i get the error: ImportError at /login/ m doesn't look like a module path like it's spliting it by characters instead of '.' when i try: AUTHENTICATION_BACKENDS = ['modules.emailauth.EmailBackend'] which i think should be correct, i get an entirely new kind of error: TypeError at /login/ the 'package' argument is required to perform a relative import for '.modules.emailauth' -
`create()` must be implemented
My code: serializers.py: class AuthenticationSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) def validate(self, data): email = data.get('email') password = data.get('password') user = User.objects.get(email=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password was not found.'+ ' ' + email + ' ' + password ) return { 'email': user.email, 'username': user.username, } views.py: class Authentication(CreateAPIView): serializer_class = AuthenticationSerializer def authentication(request): user = request.data.get('user', {}) serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) return user, Response(serializer.data, status=status.HTTP_200_OK) i need to create authentication and after give user JWTToken but i can't to do authentication. I am work with this libs 2days. May be it is because i am using CreateAPIView? But what can I replace CreateAPIView? -
how to use default address for saving in django
i have model name address which allow user to create multple address and also have functionality to set the default address but i unable to fetch it for saving in models any suggestion will be a big help thank you here is my address model choice are removed class Address(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='address') reciever_name = models.CharField(max_length=200, blank=False) phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=False) alt_phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=True) state = models.CharField(max_length=50, choices=state_choice, blank=False) pincode = models.CharField(validators = [pincodeRegex], max_length = 6, blank=False) eighteen = models.CharField(blank=False, choices=eighteen_choice, default='Yes', max_length=4 ) city = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=500, blank=False) locality = models.CharField(max_length=300, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) default = models.BooleanField(("Default"), default=False) def __str__(self): return self.user.username my views.py for seting a address to deafult @login_required def set_default_address(request, id): Address.objects.filter(user=request.user, default=True).update(default=False) Address.objects.filter(pk=id, user=request.user).update(default=True) return redirect('accounts:home') my model in which i want to save that default address class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) item = models.ForeignKey(Item, on_delete=models.CASCADE ) address = models.ForeignKey(Address, default= True, on_delete=models.CASCADE ) status = models.IntegerField(choices = status_choices, default=1) method = models.CharField(max_length=50, blank=False,) size = models.CharField(max_length=20, blank=False) price = models.FloatField(blank=False) created_at = models.DateField(auto_now=True, editable=False) payment_status = models.IntegerField(choices = payment_status_choices, default=3) order_id = … -
Django preventing multiple user logins
I wanted to limit users to one login per account. I read numerous posts, and I've been following this post in particular: How to prevent multiple login in Django. In myapp/models.py, I have this: from django.conf import settings from django.db import models from django.contrib.sessions.models import Session ... class UserSession(models.Model): user_acc = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session_manager = models.OneToOneField(Session, on_delete=models.CASCADE) In myaurth/views.py, I import from myapp/models.py and have this: from django.contrib.auth import user_logged_in from django.dispatch.dispatcher import receiver ... @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions Session.objects.filter(usersession__user_acc=user).delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user_acc=user, session_manager=Session.objects.get(pk=request.session.session_key) ) I am not using a custom user model. When I run this code, it works properly when the user logs in the first time and creates an entry in the usersession table. After that I have problems: If I login a second user, it logs them in, but it replaces the first user's session info with the second user's in the usersession table. I never see more than one entry in the usersession table, which is the last user to successfully login. Worse, if I attempt to login the first user … -
How to set Heroku profile so it accepts "yes" in any terminal question for Heroku Deployment
Hello I am tryting to run a command while deploying my Django code to Heroku. I want to accept any question it might get in terminal I tried to add following to the procfile, but it didnt work release: python manage.py collectstatic --yes release: python manage.py collectstatic -y What is the correct way to do this? Thanks in advance -
Facing troubles on bringing the Django admin user tools like welcome, view site, log out on the custom template
I have to override the blocks like branding,site_title, and index title to a custom template. But the user tools are not displaying. How I get. How I want. -
DateField in Django Forms shows like simple text input
My Form : date = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control'})) My HTML : <label class="form-label">Date</label> {{ form.date }} <div class="invalid-feedback"> Enter Date </div> Also I don't want to add type "date" in my forms. Issue picture : enter image description here -
How to configure a django url correctly in javascript
I have seen lots of questions and answers on this topic, but the solution seems to evade me. common/urls.py path('use-selected/<str:app_base>/<str:board_number>/', views.UseSelectedItem.as_view(), name='use-selected'), If I enter the the following code in my template, it works correctly <a id="use-selected" href="{% url 'use-selected' app_base='solo' board_number='4' %}"><button type="submit">Use selected</button></a> if, on the other hand, I assign the href in javascript use_selected = document.getElementById('use-selected'); use_selected.href="{% url 'use-selected' app_base='solo' board_number='4' %}" the link fails. The request url is http://127.0.0.1:8000/common/history/solo/%7B%25%20url%20'use-selected'%20app_base%3D'solo'%20board_number%3D'4'%20%25%7D I do not uderstand where the common/history/solo elements arise. common and solo are apps within my project; common/history was the url to get to this page -
Django Paginator. How to set number of pages or elements of list
I need to create a Paginator object for function based view. When I send a request to googleapi I receive json with totalItems and items keys. GoogleApi paginates request to 10 items. Let's say the totalItems is 800 so I need to somehow tell Django Paginator there are more items than I receive in the request. My first idea was to just create a list with empty items and items received from API at indexes accordingly to page number but I believe there is some good clean trick for that" VIEW def get_books(request): page = request.GET.get('page', 1) start_index = (page - 1) * 10 params = {'q': RoweryMogąUratowaćŚwiat, startIndex: start_index} result = requests.get('https://www.googleapis.com/books/v1/volumes?,params=params) total = result['totalItems'] items = result['items'] my_list = [] for i in range(total) if start_index < i < start_index + 10 my_list.append(items[i - start_index]) else: my_list.append('') paginator = Paginator(my_list, 10) -
Creating an Django API end point for data with foreign key value
first time asking question will try and make it clear what I'm trying to do. I have 2 models called Configuration and Results. class Configuration(models.Model): title = models.CharField(max_length=50, default="") houseType = models.CharField(max_length=50) numberOfHouses = models.CharField(max_length=50) maxAmpere = models.CharField(max_length=50) date = models.DateField(default=now()) status = models.BooleanField(default=False) class Results(models.Model): time = models.CharField(max_length=100) averageCurrent = models.CharField(max_length=100) config_id = models.ForeignKey(Configuration, related_name='results', on_delete=models.CASCADE) What I am struggling to do is: Create a Results object linked to the correct configuration Create an api endpoint in the views to fetch the results for a specific configuration Any help or advice would be greatly appreciated! Thanks in advance In case it helps this is the code for my serializers: class ResultsSerializer(serializers.ModelSerializer): class Meta: model = Results fields = ['time', 'averageCurrent', 'config_id'] class ConfigurationSerializer(serializers.ModelSerializer): results = serializers.StringRelatedField(many=True) class Meta: model = Configuration fields = ['results', 'title', 'houseType', 'numberOfHouses','maxAmpere', 'date', 'status'] -
Create a timer in the Django admin model
I want to create a timer in such a way that when the time is set in the admin model, the timer will be activated. Thank you if anyone knows. enter image description here -
DJango admin base_site template extension not working
I am trying to override the basic structure of a Django admin page using the below code: {% extends "admin/base_site.html" %} But the problem is, using this I only get the branding of the site, everything else like the navbar or the logout buttons are all missing. I have also tried adding the below segment but it is not working: {% block nav-global %}{% endblock %} Please suggest some measures. -
Connecting to AWS RDS Postgres Instance from my Django Project (Settings.py)
settings.py import os import dj_database_url ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USERNAME'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': 5432 } DATABASES['default'] = dj_database_url.config(os.environ.get('DATABASE_URL'),conn_max_age=600) I have a environment variable in my machine postgres://<user>:<password>@<host>:5432/cust_manage this is to connect to my aws rds postgresql then when I start the server it returns this error django.db.utils.OperationalError: FATAL: password authentication failed for user "dieth" FATAL: password authentication failed for user "dieth" QUESTION: How to connect my app to my aws rds that uses environment variable? so that I don't have to pass my real host and password to my settings.py. Thanks guys. -
Hide algorithm, iterations, salt in django password field
In django user table password are encrypted automatically with a secure algorithm (pbkdf2_sha256) with salt and iterations. But what I don't understand is why the django password field shows the algorithm, iterations and salt in this format: <algorithm>$<iterations>$<salt>$<hash> I thought those information are secret and I want to show only the hash. -
Login form not initializing not authenticating
When I was adding a template from the internet to my login.html code I encountered a problem. When I try to login it did not work. Even after I added CSRF tokens and login form control code. It has a clickable button that does not thing. I hope someone can help me. If any pictures or other codes needed please feel free to ask. login.html: {% extends 'base.html' %} {% load static %} {% block content %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <!-- Style --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <div class="content"> <div class="container"> <div class="row"> <div class="col-md-6 order-md-2"> <img src="{% static 'images/undraw_file_sync_ot38.svg' %}" alt="Image" class="img-fluid"> </div> <div class="col-md-6 contents"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="mb-4"> <h3>Sign In to <strong>C</strong></h3> <p class="mb-4">Lorem.</p> </div> <form method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" id="username" placeholder="Username"> </div> <div class="form-group"> <input type="password" class="form-control" id="password" for="password" placeholder="Password"> </div> </form> <input type="submit" value="Log In" class="btn text-white btn-block btn-primary"> </form> </div> </div> </div> </div> … -
Django | Queryset ManyToMany Relation through Instance
I would like to display the different dates for each course. A course can also have several dates. Unfortunately I can't find a solution. Models: class Course(models.Model): course_number = models.CharField(max_length=24, blank=True) course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE) course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates") def __str__(self): return self.course_number class Course_Course_dates(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE) def __str__(self): return self.id class Course_dates(models.Model): date = models.DateField() start = models.TimeField() end = models.TimeField() trainer = models.ManyToManyField('Trainer', through="Course_dates_trainer") def __str__(self): return self.date.strftime("%d.%m.%Y") View: def course_list(request): courses = Course.objects.all() course_list = [] for course in courses: course_location = course.course_location.description dates = course.course_dates.all() course_list.append({'course': course, 'course_location': course_location, 'dates': dates,}) context = { 'course_list': course_list, } return render(request, 'kursverwaltung_tenant/course.html', context) Thanks for help!!! -
Request data empty with formData - Django Rest Framework
I am trying to save strings, floats and an image via a POST request made to a Django Rest Framework backend: # My view: class CreatePost(APIView): # tried with and without parser: # parser_classes = [FormParser, MultiPartParser] def post(self, request): serializer = PostSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user_id=request.user.pk) return Response(serializer.data, status=201) return Response(serializer.errors, status=400) # My serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ("x", "y") And my JS frontend: const postBody = new FormData(); postBody.append('x', 'someValue'); postBody.append('y', 'someValue'); fetch('/api/v1/post', { method: 'post', body: postBody, credentials: 'same-origin', headers: { 'X-CSRFToken': getCookie('csrftoken'), 'Content-Type': 'multipart/form-data' } } However, sending as 'Content-Type': 'multipart/form-data' does not show any values in request.data in my backend. Sending as application/json works, but does not when one of the fields is an image. How can I process both text and image using form-data? I tried using parsers (FormParser and MultiPartParser) without success. -
Django, all views require login except `@login_not_required` decoratored views
Django is centered towards allow access to all the majority of the time, and restricting acces on the exception. I am making a site whereby I would like access restricted the most of the time, and the rare case is open to all. Ensuring that one has added a @login_required decorate to all views is error prone. I acheived this by creating a custom middleware like this. To keep track of open URLs, I defined a list, and then whenever I wished to open up a URL, I added it to the list, and the middleware checked the request path against this list, and allowed exceptions accordingly. This method above works, but I often mess it up with changing urls, and other issues to do with code reuse on different sites. Ideally I would like to create my own @login_not_requied decorator. How to get the class based view or function the request is going to call within the middleware, so I can check whether the view does not require login? -
Using Django's GenericForeignKey with Async Graphene Subscription
I've implemented graphql_ws to subscribe to updates from a Notification model that uses multiple GenericForeignKeys. My setup works well, except when I try to query information from those foreign objects. I then get the following error: graphql.error.located_error.GraphQLLocatedError: You cannot call this from an async context - use a thread or sync_to_async. From what I seem to understand, that's because some database query operations are being done outside the async context of get_notifications (that is, in the resolve_actor function). But I'm really not clear on how I can pull the operations of resolve_actor into the async context. I've unsuccessfully tried using prefetch_related (plus I'm not sure it'll work with multiple content types per Django's docs). Here's the code models.py class Notification(TimeStampedModel): # ... actor_content_type = models.ForeignKey(ContentType, related_name='notify_actor', on_delete=models.CASCADE) actor_object_id = models.CharField(max_length=255) actor = GenericForeignKey('actor_content_type', 'actor_object_id') # ... schema.py class ActorTypeUnion(graphene.Union): """ All possible types for Actors (The object that performed the activity.) """ class Meta: types = (UserType,) # here's there's only one type, but other fields have multiple class NotificationType(DjangoObjectType): actor = graphene.Field(ActorTypeUnion) def resolve_actor(self, args): if self.actor is not None: model_name = self.actor._meta.model_name app_label = self.actor._meta.app_label model = ContentType.objects.get(app_label=app_label, model=model_name) return model.get_object_for_this_type(pk=self.actor_object_id) return None # ... class Meta: model … -
"Incorrect type. Expected pk value, received User."
I have this two models: order and route. Route has a oneToMany relation with Order as you can see: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField(default=datetime.date.today) date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) description = models.CharField(max_length=500, null=True) route = models.ForeignKey(Route, related_name='orders', null=True, on_delete=models.CASCADE) class Route(models.Model): day = models.DateField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) start_time = models.TimeField() When a route is created I want to associate orders with that route, so I've done the following serializer: class routeSerializer(serializers.ModelSerializer): orders = OrderSerializer(many=True) class Meta: model = Route fields = ['day', 'warehouse', 'start_time', 'orders'] def create(self, validated_data): orders_data = validated_data.pop('orders') route = Route.objects.create(**validated_data) for order_data in orders_data: order_serializer = OrderSerializer(data=order_data) order_serializer.is_valid(raise_exception=True) orders = order_serializer.save() orders.route = route orders.save() return route I am sending a request like this: { "day" : "2021-12-12", "warehouse": "1", "start_time": "7:00", "orders": [ { "id": 15, "customer": 1, "retailer": 2, "date_available": "2020-12-12", "weight": "1.20", "description": null, "ordertimelocation": [ { "longitude": "12.1223000000000000", "latitude": "12.1223000000000000", "time_interval": [ { "start": "2021-07-21T10:10:00Z", "end": "2021-07-21T10:10:00Z" } ] } ] } ] } But the server returns a bad request: { "customer": [ "Incorrect type. Expected pk value, received User." ], "retailer": [ "Incorrect type. Expected pk value, … -
Django Ajax Post - works sometimes
I have a Django application where I am using AJAX to do a post when submitting a form. My issue is what do I set the URL to in my JavaScript? JavaScript snippet: $.ajax({ url: "search/do_post/", // the endpoint type: "POST", // http method data : { relevancy: relevancy, report_id: report_id, query: query_text, //csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, urls.py snippet: path("search/do_post/", do_post_view, name="do_post"), My issue is that sometimes the above works and sometimes it does not. When it doesn't I get: POST http://localhost:1227/search/search/do_post/ 404 (Not Found) When I see that I then remove the search part from the url in my JavaScript. Sometimes that works and sometimes not. Any suggestions? -
How to upload a saved file in django
in my case, the user gives a word in the front-end and in the back-end, i will call some function that i wrote and at the end i will build a .PDF file in the /media/reports directory. how i can make this files user-specefic and save them in the database? before that, i implemented my code without models and forms and just save file in the /media/reports/ directory. and user just could download that file at the moment after redirected to the download page. but now, i want to save these files to the database that each user will be access new files in his profile. how i can do that ? here is my code: views.py: @login_required(login_url='/login/') def dothat(request): if request.method == 'GET': return render(request, 'app/dothat.html') else: try: global word, user_name, function_name function_name = dothat.__name__ word = request.POST.get("word") user_name = request.user full_name = request.user.get_full_name() myscript.script_one(word, user_name,full_name, function_name) # And in the called myscript, after doing some things, # the PDF file will be saved in /media/reports/ directory except ValueError: return render(request, 'app/dashboard.html', {'error':'Bad data passed in. Try again.'}) # And then, the user will be redirect to the download page to download that single file return render(request, 'app/download.html') and …