Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not import 'rest_framework_simplejwt.auth.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
I am trying to make REST APIs using Django. I have installed djangorestframework & djangorestframework-simplejwt using pip pip install djangorestframework pip install djangorestframework-simplejwt Whenever I import anything from rest_framework, It gives me this error ImportError: Could not import 'rest_framework_simplejwt.auth.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'rest_framework_simplejwt.auth' Requirement.txt file: djangorestframework==3.12.4 djangorestframework-simplejwt==4.7.2 Setting.py file: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'rest_framework', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', "config", "response", "utils", "authentication", ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.auth.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=5), } -
Django can't identify the user after registering an account *AnonymousUser*
So the goal is for a new user to register an account and then get redirected to the home page and recognized. So that the user does not have to register for their account then go through the process of logging in right after. I want a standard registration, like Instagram, Twitter, and other professional applications. So far, I'm where the user can register and redirect them to the homepage, but when I try to print their name on the screen, I get AnonymousUser. The user's information is written to the database after registering, but Django doesn't know who the user is. For Django to know who is logged in after registering, they have to log out and then log in right after registering their account. If anyone could help, I would be much appreciated it. Views.py from django.shortcuts import render, redirect from .forms import RegisterForm from django.contrib import messages def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/") else: form = RegisterForm() return render(response, "register/register.html", {"form": form}) -
how to get latest second row in django?
can anyone help me I'm new to django so I don't know how to make sql queries into django code. my sql table is : select * from mangazones.mangabank_comic_banks; sql table image (below image) then for second row query : WITH added_row_number AS (SELECT comic_chapter,comic_english_name_id, row_number() OVER(PARTITION BY comic_english_name_id ORDER BY comic_chapter DESC) AS row_num FROM mangazones.mangabank_comic_banks) SELECT * FROM added_row_number WHERE row_num = 2; I get table (below image) : seond row table I want second row table query in django also. Can anyone please help me? -
Images not showing in PDF generated by WeazyPrint in a Django Project
I have a question related to generating PDF in a Django Project using Weazy Print So the first thing I have done is that I made sure that the PDF is showing correctly as per the CSS file I have included in the function below in the views.py: def admin_order_pdf(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/pdf.html', {'info': info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format( Info.id) weasyprint.HTML(string=html,base_url=request.build_absolute_uri()).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '\css\\report.css')], presentational_hints=True) return response Second I have included the {% load static %} in the report.css and I am trying to access the image file using the below: @page :first { background: url('{% static "img/report-cover.jpg" %}') no-repeat center; background-size: cover; margin: 0; } I have reviewed the following questions and their answers but they didn't help achieving my goal to show the image: PDF output using Weasyprint not showing images (Django) attach img file in pdf weasyprint My trials: I was able to get the image showing by adding @page :first in the html page between <style></style> but my issue is that there are other things that I need to link also like fonts and svgs so I wanted to know what I am doing wrong that doesn't allow the … -
Django Simple Captcha Can't change Validation Error?
I want change validation error for Captcha input after the wrong value is entered, default value error is 'Invalid CAPTCHA' how can I change it ? from django import forms from captcha.fields import CaptchaField from django.contrib.auth import get_user_model User = get_user_model() class LoginForm(forms.Form): username = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control", "id": "input-email"}) ) password = forms.CharField( widget=forms.PasswordInput(attrs={"class": "form-control", "id": "input-password"}) ) captcha = CaptchaField(required=False, label='') Error text image -
Im getting a 500 Server error when i try submitting with Django app
I deployed my django app to my cpanel and it is live, but when i go to submit a post with the form I created it gives me a 500 server error. I think it has to do with my static files and the thumbnail. enter image description here can someone tell me how are the static urls supposed to be formatted since it is live now? -
How to store a value in database using user's input in Django?
class User(models.Model): GENDER = [ ('0', 'Male'), ('1', 'Female'), ] DEGREE = [ ('0', 'High School or below'), ('1', 'Associate or Bachelor'), ('2', 'Master or PhD'), ] name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) gender = models.CharField(max_length = 1, choices = GENDER, null=True) age = model.IntegerField(null=True) degree = models.CharField(max_length = 1, choices = DEGREE, null=True) Assuming I have a formula that calculate credit scores based on this input, for example, 2.03884 * ln(age) + 12.8938 * ln(degree) + 9.9 * (ln(degree)^2). Now, I am just curious about where, how and what should I do so that whenever I look up at the User, I can obtain his/her/their score? Thank you very much for spending your time to help me since I am extremely new to Django. -
How to add, view, sort data from models or db on GMT week number basis
Please guide me im new to django i want to display and add data on week number basis For ex GMT week starts on Sunday and ends Saturday so only current week data should be shown but should be able to retrieve past weeks data as wel kind Select Week [2021-30] 30th week of year 2021 So how to write the login to display datas stored in db fetching creation date or updation date -
Django Rest Framework django_filters return empty list
I'm trying to filter my queryset on Datefield based on year and month. After searching a lot I found this answer and tried to use it. but when I use filter I got and empty list. model.py: class Sample(models.Model): name = models.CharField(max_length=50) date = models.DateField(auto_now=False, auto_now_add=False) serializer.py: class SampleSerializer(serializers.ModelSerializer): class Meta: model = Sample fields = '__all__' filter.py: import django_filters # only for showing I use django_fliter not drf defult filter from .models import Sample class SampleDateFilter(django_filters.FilterSet): month = django_filters.NumberFilter("date", lookup_expr='month') year = django_filters.NumberFilter('date',lookup_expr='year') class Meta: models=Sample fields = ['month','year'] views.py: class SampleListview(generics.ListAPIView): serializer_class = SampleSerializer queryset = Sample.objects.all() filter_backends = (DjangoFilterBackend,) filterset_class = SampleFilter I have an object in my database with this config: { "id": 1, "name": "test", "date": "2020-05-03", #date format %YYYY-%MM-%DD } without filter I got my list but I got nothing when I use queryparam: http://127.0.0.1:8000/sample/?year=2020 http://127.0.0.1:8000/sample/?month=05 or any combination of both filters. I'm using: django-filter==2.4.0 djangorestframework==3.12.4 Django==3.0.8 How can I fix this? Thanks -
Why my Model JSON/list attribute in Django sometimes misses data?
I'm building a Django project that has to do with generating math/science problems for teachers and students. The project works fine for some time but when I run it on the browser (with the views all set up) it sometimes get errors that I cant explain how they happen: Example: class Mymodel(models.Model): attribute = JSONField() #it is a list of strings ['a', 'b', 'c'] def myfunc(self): do something with (self.attribute) The problem is that every now and then, the program runs into an error mainly because when myfunc calls self.attribute it returns the list with items missing! like, in this case, it may return ['a', 'b']. I've never seen any error like this, so I don't know what to do. I obviously double checked if the attribute is really with all the variables I expeceted it to be, that's not the problem. Has anyone seen anything like this that could help? I strongly believe that it has something to do with how Django gets the data in the JSONField and parses it to a list or dict to work with that, but again I don't know what to do about it. -
Configuring Celery + AWS SQS to revoke tasks
I am running Celery+Kombu 4.4.6 on AWS SQS and want to revoke and terminate tasks. Reading through documentation and SO posts, the transport needs to allow broadcast messages. SQS does not do broadcast messages and Celery+Kombu needs to use SimpleDB for those. That option was turned off by default long way back in version 1.x. To enables it, support_fanout = True needs to be added to the transport options. But adding just that option is not working for me and I can't figure out what am I missing. Possible options are: SimpleDB - it is not clear to me how do I even enable SimpleDB. I do see documentation in AWS, but I do not see it as a separate service. Any additional config to be added? Looking briefly at the SQS code, seems like SimpleDB is the only option for this. Is that correct? Any other option to enable task revocation on SQS? In my app.celery I have: app = Celery('app', broker=''sqs://<Access key>:<secret key>@')), backend='cache+memcached://<host>:11211/')), ) And in my app.settings I have: CELERY_BROKER_URL='sqs://<access key>:<secret key>@')) CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': '<region>', 'supports_fanout': True, } CELERY_DEFAULT_QUEUE = 'app' CELERY_DEFAULT_EXCHANGE = 'app' CELERY_DEFAULT_ROUTING_KEY = 'app' -
What is the best way to do ajax rendering for a long section?
I am currently dividing the template into sections and using ths in views.py if "x" in Form2.changed_data: template_photo = render_to_string("photo.html", context) success["template_photo"] = template_photo if formset_has_changed(FormSet1): template_intro1 = render_to_string("intro1.html", context) success["template_intro"] = template_intro if formset_has_changed(FormSet2): template_intro2 = render_to_string("intro2.html", context) success["template_subject_intro"] = template_subject_intro template_section = render_to_string("section.html", context) and sending it as a JSONresponse and replacing the innerHTML with js. The reason I am using this method is to prevent the whole form from being rendered again (such as prevent unchanged photos from being rendered again). However, this will quickly become messy and repetitive as I create more sections. Is there an alternative practice to this to update the page without replacing the entire innerHTML of the form/page? -
How to sort a list from queryset using Django
I want to sort a list converted from queryset. I've tried using sorted, but I'm getting an error This is my code: views.py @api_view(['GET']) def practiceAnswer_filter(request): # GET list of filtered practiceAnswer if request.method == 'GET': practiceAnswers = PracticeAnswer.objects.all() practice_id = request.GET.get('practice_id', None) if practice_id is not None: # filter practiceAnswer based on practice_id practiceAnswer_filtered = practiceAnswers.filter(practice_id__practice_id__icontains=practice_id) # convert queryset to list practiceAnswer_list = list(practiceAnswer_filtered) # shuffle to get random practiceAnswer shuffle(practiceAnswer_list) # splice list to limit practiceAnswer practiceAnswer_shuffled = practiceAnswer_list[:3] practiceAnswer_sort = practiceAnswer_shuffled dict(sorted(practiceAnswer_sort.items(), key=lambda item: item[1])) print(practiceAnswer_sort) practiceAnswers_serializer = PracticeAnswerSerializer(practiceAnswer_sort, many=True) return JsonResponse(practiceAnswers_serializer.data, safe=False) This is the original data from queryset : <QuerySet [<PracticeAnswer: 1>, <PracticeAnswer: 2>, <PracticeAnswer: 3>]> This is the converted data from queryset to list : [<PracticeAnswer: 1>, <PracticeAnswer: 2>, <PracticeAnswer: 3>] Actually with the original data and converted data I already got the sorted data but from the original data I still process it by filtering it based on practice_id and randomizing the data to get random data after that limiting / splice to display only 3 data. Without sorted the 3 data that appear are not sequential, I want the data to be sorted by the values 1, 2, 3 If I run … -
Django ZIP multiple images for download
I'm trying to zip several images in a ZIP file. Although It's a Django app, files are not stored in the same app. I want to fetch them from a url list. I get the following error: FileNotFoundError [Errno 2] No such file or directory: 'image1.jpg' def download_image(request): fotos = ['https://storage.googleapis.com/some/image1.jpg', 'https://storage.googleapis.com/some/image2.jpg'] f = StringIO() zip = ZipFile(f, 'w') for foto in fotos: url = urlopen(foto) filename = str(foto).split('/')[-1] zip.write(filename, url.read()) zip.close() response = HttpResponse(f.getvalue(), content_type="application/zip") response['Content-Disposition'] = 'attachment; filename=image-test.zip' return response I reviewed several posts and finaly followed this one how can I export multiple images using zipfile and urllib2 - django But I can't get this working. Any clues welcome. Thanks in advance. -
How to add 4-level domain for django
there are nginx and django server and a proplem to add endpoints like moscow.test.site.com or tokio.test.site.com When i use localhost then no problem but how to add domains of 4-level for my test.site.com? -
DatabaseError at boards, No exception message supplied
I am working on a Django project with MongoDB Database, but when I am trying to open boards that contain topics(join). I have this error! -
Should I use Python or Javascript to build a text-based adventure using Django?
I hope this doesn't come off like too strange a question, but I'm relatively new to Django specifically. I currently have a website going using Heroku and Django and I would like to post a bunch of mini-projects and such I make there. One of the ones I want to do is a text-based adventure. I'm relatively proficient in Python and Javascript individually and have built similar things in both, however I'm having trouble thinking how best to translate this into the Django framework. Currently on my website I have a bunch of pages just for things like articles and written pieces. All of that is working fine and I've even added a mini CMS to the backend and that all works alright. However most of that was either building stuff entirely in backend, or entirely in frontend and then just doing a data linkage. There's no real python code going on in the backend outside of constructing the views and models etc. If I was to build this in Javascript I would likely just hardcode a lot of the writing for a text-based game, likewise with Python, however I feel with Django and a linked Postgres DB there's potential … -
Django Heroku database reset after each push?
Forgive me if this is a obvious answer, but will my database be reset after each git push heroku master ? -
Deploying django on local server
I have just finished my Django app. Now I would like to run the app at the company I work for. Problem is, this is my first time doing so, so I need a helping hand. Can anyone point me in the right direction with a good tutorial? I wish to install only necessary tools, nothing extra. I think there is no need for safety because it would be only accessible from the company level. Should I just copy files from my PC and run it on virtual machine (Windows) or is there a better approach? Is it possible for everyone to connect to my server? -
Django: How to pre-enter data in a form?
I have got a quotation that I would like to convert in a project. If a quotation has been approved, it will be converted in a new project. I`ve got two models, one for the quotation and one for the project. To achieve this, I am thinking to add a button Create Project from Quotation. This button will create a new project based on the Project Model. Now, I am trying to find a way to pre-enter some data from the quotation in the new Project model entry. What should I add to my {% url 'projects:create_project' %} to pre-enter the project name and link it to the quotation? Many Thanks, -
Trying to add report issue feature on my django project but giving me error
i am trying to add report issue on my todo beginner project but gives me error let me explain İ want it to give and error message like if its already reported in my admin.thats the main idea when i first click on the report button it shows up the id of reported item on admin / reported area but when i reclick on the report button it gives me IntegrityError at /report/17 UNIQUE constraint failed: tasks_report.id views.py def report_view(request, pk): task = Task.objects.get(id=pk) reported = Report.objects.create(id=pk) return redirect('index') models.py class Report(models.Model): is_reported = models.BooleanField(default=False) urls.py path('report/<str:pk>', report_view, name="report"), admin.py admin.site.register(Report) -
query for model instances that are indirectly related
I've got 3 models. I'd like to write a query in django to find all reviews that are related to Carts that are related to jobs that are complete. Unfortunately, I can't figure out how to do this. class Review: cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) class Job: cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) complete = models.BooleanField(default=False) class Cart: name = models.CharField(max_length=500, null=True, blank=True) amount = models.IntegerField() Any help would be appreciated! -
Django db not saving changes
Django db not always saving changes, when I canhge one of model parametrs. Code below, look veiws.py on lines highlighted by comments, I try to append new_file.ID value to parent.files (ArrayField) and user parent.save() to save changes, but realy it not always works, have this problem when loading too much files at the same time. When amount of loading files not large it's always works... I'm using postgresql views.py fragment @csrf_exempt @sync_to_async def load(request): if request.method == 'POST': if request.user.is_authenticated: import os from .utility import alternative_filename, set_file_ID file = request.FILES['file'] path = request.POST['full_path'].split('/') parent = File.objects.get(ID = request.POST['parent_id']) if allowed(parent, request.user, moderators = True): filename = alternative_filename(f'{get_file_path(parent)}/{file.name}') if len(path) > 1: path.remove(path[0]) for element in path[:-1]: if not os.path.exists(f'{get_file_path(parent)}/{element}'): os.mkdir(f'{get_file_path(parent)}/{element}') new_parent = File(name = element, folder = True, parent_ID = parent.ID) set_file_ID(new_parent, request.user.username) parent.files.append(new_parent.ID) parent.save() else: new_parent = File.objects.get(parent_ID = parent.ID, name = element, deleted = False) parent = new_parent filename = alternative_filename(f'{get_file_path(parent)}/{file.name}') path_to_file = get_file_path(parent) with default_storage.open(f'{path_to_file}/{filename}', 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) new_file = File(name = filename, folder = False, parent_ID = parent.ID) set_file_ID(new_file, request.user.username) ############################################### parent.files.append(new_file.ID) parent.save() # this save not always working!!! ############################################### return JsonResponse({'message' : 'Created', 'new_ID' : new_file.ID}, status = 201) else: … -
Using AJAX to delete model data - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. I did research online, and I came across many articles talking about using Ajax, but I can't really figure out how to implement it in my program. Can someone please help me? My JS is down bellow: swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } I have been struggling with this for a really long time, I am willing to buy whoever helps me a coffee. Thank you -
Why am I receiving a NoReverseError message when having two django paths that take string inputs? (I am working on CS50 Project 1.)
I am working on CS50 Project 1 dealing with Django. In urls.py I have two paths that take strings as input, but neither work, and I receive a NoReverseError message. urls.py code urlpatterns = [ path("", views.index, name="index"), path("edit_entry/<str:title>/", views.edit_entry, name = "edit_entry"), path("search/", views.search, name = "search"), path("wiki/<str:title>/", views.get_entry, name = "get_entry"), path("create_entry", views.create_entry, name = "create_entry") ] views.get_entry code def get_entry(request, title): exists = util.get_entry(title) if exists is None: return render(request, "encyclopedia/get_entry.html", { "entry": "Entry Does Not Exist" }) else: entry = markdown(util.get_entry(title)) return render(request, "encyclopedia/get_entry.html", { "entry": entry }) views.edit_entry code (edit_entry actually has some more work that needs to be done to it) def edit_entry(request, title): if request.method == "POST": form = NewEditEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title, content) return HttpRespnseRedirect("/wiki/" + title) else: return render(request, "encyclopedia/edit_entry.html",{ "form": NewEditEntryForm() }) The error message NoReverseMatch at /wiki/Css/ Reverse for 'edit_entry' with keyword arguments '{'title': ''}' not found. 1 pattern(s) tried: ['edit_entry/(?P<title>[^/]+)/$'] Your help would greatly be appreciated. Thank you!