Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST API response blocked by CORS policy - React and Django Rest Framwork
I have created a backend server in Django with Django Rest Framework, and a React frontend. My front retrieves data from the back through APIs. Each app is on a different subdomain of the same domain. I use Cloudflare to manage DNS and for SSL / security. I have had no problem with GET calls. For POST calls, I send the POST data to the server through a form, and I know it works as there is a change to the database (record created in this instance). However, I have implemented a 'retry until' function using axios and polly-js. This method waits until it receives a 201 CREATED response, otherwise retries. My problem is that when I submit the form on React, the POST is indeed received and processed by my backend server, but the response is blocked. So after 10-15 seconds, I receive an error message through the console and my 'retry until' method sends another POST request. The response of this second one is not blocked by Chrome, and I receive the 201 status. But the overall effect is that I have now 2 identical records in the database because the first call did not 'receive' the response … -
How can i create a queue following FIFO in python django?
How can i create a queue in python following FIFO, eg: I need a queue which stores recently visited 5 books in a book library management system if visted books are in order, Book1, Book2,Book3, Book4,Book5 when a Book6 comes it should rearrange like, Book6,Book1, Book2,Book3, Book4 -
How to get the current user with get_redis_instance?
I'm using asgi-redis==1.4.3. I want to get the user of the current session with this command: user = get_redis_instance().get(id) but it returns none!! -
Equivalent of Rails "Raise" in Django
I am new to Django but I have experience in Rails. In Rails, if you want to check what one of your action/function is doing, you can use the raise parameter. The execution of the action will stop, and in locahost you can see the output of that function. Example: def answer: @banana = 2 + 2 raise end If I reload localhost, a console opens and if I write @banana I get the result 4. Is there something similar in Django? -
How to render a background image in my index.html to make it dynamic using Django?
I'm trying to make a template dynamic. I added the jinja pattern wherever required and it worked except for the background images of the page. I tried this: I expected to see the bg_image on the page, but i get nothing except blank white space. I get other images in the same folder using: -
Django i cannot add button in modal for each field with ajax
I m trying to put a button in my table but i cannot succeed i receive an error "Reverse for 'editare-agenda' with keyword arguments '{'pk': '+field.id+'}' not found. 1 pattern(s) tried: ['dashboard/editare\-agenda/(?P[0-9]+)$']" if i put an number instead +field.id+ is working . if i test alert(field.id) i receive the id. is something wrong writing {% url 'dasboard:editare-agenda' pk=field.id %} but i cannot find the solution. this is my urls.py: path('editare-agenda/<"int":pk>', editare_agenda, name="editare-agenda"), $.ajax({ data: values, method:"POST", url: destinatie, contenttType: 'application/json', success: function(data){ var content =""; $.each(data.agenda, function(i, field){ content += '<tr class="text-center">'; content += '<td>'+field.denumire_unitate+'</td>'; content += '<td>'+field.sectia+'</td>'; content += '<td>'+field.telefon+'</td>'; content += '<td>'+field.pers_contact+'</td>'; content += '<td>'+field.adresa+'</td>'; content += '<td><a href="{% url "dashboard:editare-agenda" pk='+field.id+'%}"><button type="button" tclass="btn btn-sm" style="border-radius: 5px;margin: 1px;"><i class="fas fa-edit fa-lg" style="color: blue"></i></button></a></td>'; content += '</tr>'; }); $('#tabela_agenda').html(content); } }); -
How to monitor cpu usage and ram usage for each request in Django
I am running a Django Rest Framework server on Google Cloud Platform. Most of my requests are post request. I want to analyse which request is using how much memory and how much CPU on average. Is there a way to analyze it? My API code looks like as follow: class GetAudioDialogue(APIView): def post(self, request): ... -
request.user.is_authenticated working only in the home page
I am creating a website where a user can upload documents. If user is logged out he can view other's document but not download it if user is logged in he can download the document from the toolbar in pdf viewer Even when I am logged out request.user.is_authenticated is false in home page but its true in other pages. So the download button does not hide nor a login button shows up. I have tried using user.is_authenticated but it was returning true all the time urls.py re_path(r'^all_files/(?P<doc_id>[0-9]+)/$',views.doc_detail,name = 'doc_detail'), path('login/',auth_views.LoginView.as_view(template_name='homework/login.html'),name = 'login'), views.py def doc_detail(request,doc_id): template = loader.get_template('homework/doc_detail.html') doc = get_object_or_404(Document, pk = doc_id) context = { 'doc':doc } return HttpResponse(template.render(context,request)) doc_detail.html {{ doc.user.username }} {{ doc.title }} {{ doc.doc_type }} <br> {% if request.user.is_authenticated %} <iframe src="{{ doc.document.url }}#toolbar=1&navpanes=0&scrollbar=1" type="application/pdf" width = "80%" height = "600px" /> {% else %} <iframe src="{{ doc.document.url }}#toolbar=0&navpanes=0&scrollbar=0" type="application/pdf" width = "80%" height = "600px" /> <a href=" url 'homework:login'">login</a> {% endif %} -
How to override Django's default email template (smptd)
How to override Django's default email template urls.py path('change-password/', views.change_password, name='change-password'), path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), name='reset-password'), path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset-password/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'), reset_password.html <h1>Reset Password</h1> <p>Enter a registered email here!</p> <form method="post"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary" type="submit">Reset</button> </form> I was hoping to customise the django email template (smptd) using html. -
Can't validate form and refreshes page when I hit submit button django
I'm new to Django and learning some new things and I have a problem that I can't able to validate the contact form and page refreshes when I hit submit button. Can u please go through this code. I cant able to validate contact form and I can able to validate and store values of join form but the contact form and everything are fine but I don't know where is the problem. I'm using atom editor for Django Here is forms.py #forms.py from django import forms from django.core import validators from index.models import * class Contactform(forms.ModelForm): class Meta: model = Contact_Us exclude = ('date',) confirm_email = forms.EmailField() botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) def clean(self): super(Contactform, self).clean() name = self.cleaned_data['fullname'] if len(str(name)) < 4: raise forms.ValidationError("Name should contain more than $ letters") class Joinusform(forms.ModelForm): class Meta: model = Join_Us fields = '__all__' confirm_email = forms.EmailField() botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) def clean(self): super(Joinusform, self).clean() all_clean_data = self.cleaned_data email = all_clean_data['email'] cemail = all_clean_data['confirm_email'] phone = all_clean_data['phone'] registration = all_clean_data['registration'] experience = all_clean_data['experience'] hiringreason = all_clean_data['hiringreason'] role = all_clean_data['role'] year = all_clean_data['year'] if email != cemail: raise forms.ValidationError("MAKE SURE EMAIL MATCH!!!") if len(str(phone)) < 10: raise forms.ValidationError("Phone Number should be 10 … -
How do I use PHP-apis to get data into Django pages?
I have a PHP-api providing me the following data: { "ErrorCode": 0, "SubErrorCode": 0, "ErrorMessage": "", "Data": [ { "id": 2, "news_title": "Recent Update", "news_description": "last month articles", "image_id": 2, "news_date": "2018-04-01", "news_content": "the big content", "slug": "recent-update1", "company_id": 1, "user_id": 1 } ] } I want to create a view in Django that accepts data from API and displays it on a page. Views.py: from django.shortcuts import render import requests def blog_last_month(request): response=request.get("/guest/news/selector/last_month") data=response.json() return render(request,"blogHome.html",{"title":data['title']}) -
How to write multiple view function for single page
I'm trying to perform multiple operation for single web page. I'm struggling to write multiple function view for single web page. How to do that. Help me in that. def home_view(request): if 'username' in request.session: business_objs = AddBusiness.objects.all().values() username = request.session['username'] if request.method == 'GET': form = ProfileForm(request.POST) if form.is_valid: profile_info = Profile.objects.filter(username=username).values() for i in profile_info: profiledict = i return render(request, 'home/index.html', {'profile_first_name': profiledict['first_name'], 'profile_last_name': profiledict["last_name"], 'profile_phone_number': profiledict['phone_number'], 'profile_email': profiledict['email'], 'profile_address': profiledict['address'], 'profile_image': profiledict['image']}, {'business_objs': business_objs}) elif request.method == 'POST': first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') phone_number = request.POST.get('phone_number') email = request.POST.get('email') address = request.POST.get('address') image = request.FILES['images'] file_storage = FileSystemStorage() obj = Profile.objects.all().filter(username=username) if len(obj) > 0: obj.update(first_name=first_name, last_name=last_name, phone_number=phone_number, email=email, address=address, image=file_storage.save(image.name, image)) elif 'username' in request.session: if request.method == 'POST': business_objs = AddBusiness.objects.all().values() return render(request, 'home/index.html', {'business_objs': business_objs}) else: return redirect('/login/') I tried like this, it performing only first operation. Here i'm trying to perform 3 operation, GET(extract data from database and displaying in HTML form), POST(updating the form data), and Displaying all database rows and columns in HTML page. -
How to utilize the Django URL tag?
Sorry for such a beginner question but I have a TemplateSyntaxError on my URL line in my HTML and I cannot seem to debug it. <a href="{% url 'articleupdate' id:article_id %}">Update this Article</a> In the views.py, I have created an article_update_view function as seen below def article_update_view(request, article_id): obj = get_object_or_404(Article, id=article_id) form = ArticleForm(request.POST or None, instance=obj) if form.is_valid(): form.save() form = ArticleForm() context = { 'form': form } return render(request, 'article_update.html', context) and in my app.urls.py, I have written urlpatterns = [ path('<int:article_id>/update/', article_update_view, name='articleupdate'), ] -
Passing rendered data to createview
Models class Head_of_department(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=30) def __str__(self): return self.first_name class Employee(models.Model): first_name = models.CharField(max_length=200, unique=True) last_name = models.CharField(max_length=200, unique=True) head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True) email = models.EmailField(max_length=100) def __str__(self): return self.first_name + ' ' + self.last_name class Attendance(models.Model): head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True) employee = models.ForeignKey('Employee', on_delete=models.CASCADE, ) attendance = models.CharField(max_length=8, choices=attendance_choices, blank=True) Views class Attendancecreate(CreateView): model = Attendance fields = ['employee'] success_url = '/dashboard/' def get_context_data(self,** kwargs): context = super(Attendancecreate, self).get_context_data(**kwargs) email = self.request.user.email hod = Head_of_department.objects.get(email=email) context["objects"] = Employee.objects.filter(head_of_department =hod) print (context["objects"]) return context def form_valid(self, form): self.object = form.save(commit=False) self.object.head_of_department = get_object_or_404(Head_of_department, email=self.request.user.email) self.object.save() return super().form_valid(form) Template <div class="form-group"> {% for item in objects %} {{ item.employee }} {% endfor %} </div> The webapp has a login feature. The headofdepartment can mark the attendance . List of employees are rendered in the template without any issues , I want to mark attendance to the respective employees . That is when marking attendance employees will be listed in template, and to the right attendance form will be displayed for all the employees . Modelformset is needed to do it , but I am unaware about passing the rendered data … -
Django user has no logged_in_user (related_name)
I have created a LoggedInUser model, and given related_name. When I try to access, it's giving me an error as RelatedObjectDoesNotExist at / User has no logged_in_user. models.py User = settings.AUTH_USER_MODEL # Model to store the list of logged in users class LoggedInUser(models.Model): user = models.OneToOneField(User, related_name='logged_in_user',on_delete=models.CASCADE) # Session keys are 32 characters long session_key = models.CharField(max_length=32, null=True, blank=True) def __str__(self): return self.user.username In custom middleware.py stored_session_key = request.user.logged_in_user.session_key # Error in these line. Error: django.contrib.auth.models.User.logged_in_user.RelatedObjectDoesNotExist: User has no logged_in_user. Version: django == 2.1.2 python == 3.6.7 Where I'm getting wrong? -
django how get current port outside the view?
i need to get an information how to get server port number dynamically not in the views, where request is accesible, but outside views. Is it possible to get server port numbers dynamically outside the views? In .utilities , for example... Thank you -
Is it possible to check whether a user is logged in to my website while sending request from another website using cookies/browser localstorage?
I am trying to create a web application through which user can bookmark pages and can find them all collectively on my website. Whenever user want to bookmark any page he/she will just send a response to our server which will contain the url of the website. But if user is not logged in through our website, he/she will be redirected to our website login page. Now, "how would I check if any user is logged in to my website or not" or "when user is on different domain then how can we check for user's login status on our website"? I am working with django rest framework and javascript. -
Django details incorrect error location when discussing 'Error during template rendering'
I've had this problem a long time now, there was a report about it here but it half suggests it's been resolved - does anyone have this problem? When I get an error regarding a template, namely Error During Template Rendering, the location of that error is almost always incorrect. example NoReverseMatch at / Reverse for 'item_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['items/(?P<slug>[^/]+)/$'] Error during template rendering In template C:\Users\Documents\app\templates\base\base.html, error at line 42 Lines: **42 <a class="dropdown-item" href="{% url 'curate:submit_item' %}">Submit Content</a>** As you can see, it's highlighting an incorrect line, one which calls a different function entirely. The error is actually on one of my templates which extends from base, but it's hard to tell which. I've lived with this for a while, but now the project is larger it's getting much harder to figure from where this error comes. Does anyone else have this problem? I figured it might be to do with the tag at the top of the page? Base.html has that - the other templates deriving from it do not - is this possibly a cause? -
Correct way to format input and output of TimeField in Django Rest Famework?
models.py class DemoA(models.Model): my_time = models.TimeField() serializers.py class DemoASerializer(serializer.ModelSerializer): class Meta: model = DemoA fields = ('my_time', ) By default, for my_time field, it gives the format as 10:30:00, (%H:%M:%S). What is want is the serialized format as 10:30, (%H:%M). Is there any default way to specify format for such cases, like specifying extra_kwargs with serializer Meta? -
How can I get some attributes of my object?
Hello I am programming using Django and I have to face to this issue : usercomment = 'Test' usercomments = json.dumps(usercomment) data = {'date': '2019-02-06', 'usercomments': usercomments, 'totalminutes': '120', 'searched': 'functionTest' } At this line, I create the entry in the database. response = self.client.post("/urlRegistration/", data=data, follow=True) But when I want to get the uniqueid of the object created in the database I cannot because the connexion is closed myObject = Myobject.objects.filter(usercomment=usercomment) uniqueid = myObject[0].uniqueid Could you help me please ? Thank you very much ! -
How to get cookie issue solved?
I am getting a lot of issue about users not able to logged in or any such activity on my code, sooner I am guiding them to clear cache and cookie it is working. But it is not always possible to do that ! any experienced person here who can guide me how to deal with such issue. Any way to ? -
Django populate() isn't reentrant CANNOT BE RESLOVED
I keep getting this when I try to load my Django application on production . I tried all the stackoverflow answers but nothing has fixed it. Any other ideas. Here is my wsgi.py import os import time import traceback import signal import sys from django.core.wsgi import get_wsgi_application try: application = get_wsgi_application() print 'WSGI without exception' except Exception: print 'handling WSGI exception' # Error loading applications if 'mod_wsgi' in sys.modules: traceback.print_exc() os.kill(os.getpid(), signal.SIGINT) time.sleep(2.5) and What I got [Mon May 27 18:09:41.654452 2019] [wsgi:error] [pid 15704:tid 1300] handling WSGI exception\r [Mon May 27 18:09:41.655450 2019] [wsgi:error] [pid 15704:tid 1300] Traceback (most recent call last):\r [Mon May 27 18:09:41.655450 2019] [wsgi:error] [pid 15704:tid 1300] File "D:/soft_design/project_soft/project_soft/wsgi.py", line 26, in <module>\r [Mon May 27 18:09:41.655450 2019] [wsgi:error] [pid 15704:tid 1300] application = get_wsgi_application()\r [Mon May 27 18:09:41.655450 2019] [wsgi:error] [pid 15704:tid 1300] File "C:\\Users\\Scott\\Anaconda3\\envs\\py37\\lib\\site-packages\\django\\core\\wsgi.py", line 12, in get_wsgi_application\r [Mon May 27 18:09:41.655450 2019] [wsgi:error] [pid 15704:tid 1300] django.setup(set_prefix=False)\r [Mon May 27 18:09:41.655450 2019] [wsgi:error] [pid 15704:tid 1300] File "C:\\Users\\Scott\\Anaconda3\\envs\\py37\\lib\\site-packages\\django\\__init__.py", line 24, in setup\r [Mon May 27 18:09:41.655450 2019] [wsgi:error] [pid 15704:tid 1300] apps.populate(settings.INSTALLED_APPS)\r [Mon May 27 18:09:41.655450 2019] [wsgi:error] [pid 15704:tid 1300] File "C:\\Users\\Scott\\Anaconda3\\envs\\py37\\lib\\site-packages\\django\\apps\\registry.py", line 83, in populate\r [Mon May 27 18:09:41.655450 2019] … -
django.db.utils.DataError: division by zero
I am getting a error in the following line of code: context['stock_margin'] = context['top_stock'].annotate( Avg_purchase = ExpressionWrapper(F('total_puchase') / F('quantity_purchase'), output_field=FloatField()), Avg_sales = ExpressionWrapper(F('total') / F('quantity'), output_field=FloatField())) I am new to django and cant able to figure out why this is happening.. Any idea anyone how to solve this error? Thank you -
Django testing - test if logged in user is owner of userdetails
So I've made this little app where users have an account page were they can see and update their own details. Now I'm writing some tests for the DetailView and UpdateView. I would like to verify that the logged in user is indeed the owner of the user details. I've created a testdatabase with different users and added three tests. Check if the user is logged in When a user is logged in does he get the right template When a user is logged in does he see his own details only The problem is in the last test, I tried to retrieve the logged in user and compare this with the current user details but this isn't working. Any ideas? views.py class AccountDetailView(LoginRequiredMixin, DetailView): model = User template_name = 'account.html' ''' Retrieve user id from "self.request.user" instead of retrieving the user_id from the URL. This way we can illiminate the user id in the URL. ''' def get_object(self): return self.request.user def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user=self.request.user) test_views.py class LoggedInTestCase(TestCase): ''' Setup LoginInTestCase ''' def setUp(self): guest = User.objects.create_user(username='john.doe', email='john@doe.com', password='1234') guest_other = User.objects.create_user(username='david.doe', email='david@doe.com', password='5678') guest.save() guest_other.save() class AccountDetailViewTests(LoggedInTestCase): ''' Test the UserDetailView which shows the user details … -
django - call a view multiple times with different parameters
I have a django view that takes as parameter a path and returns the list of objects inside that path. I need to call this view multiple times with different paths. This is an example like my view: python views.py def filelist(request, foo): files = os.listdir(foo) context = { 'files' : files, } return render(request,'template2.html', context) The urls.py is like: python urls.py urlpatterns = [ path('', views.index, name='index'), path('filelist/<str:path>/', views.filelist, name = "filelist"), ] The template is like this one: HTML template.html <div class="collapse"> <div class="one"> {% include 'template2.html' %} </div> </div> <div class="collapse"> <div class="two"> {% include 'template2.html' %} </div> </div> <script> $(".one").load("{% url 'filelist' 'path1' %}", function() { alert( "Ok1" ); }); $(".two").load("{% url 'filelist' 'path2' %}", function() { alert( "Ok2" ); }); </script> Everything works but the variable {{ files }} is always the same. Inside template2.html there is only a for loop that shows the files' names. Any help? There is the possibility to store the variable {{ files }} in some local variables and then use it inside a {% for f in files %} loop? Thanks.