Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling Django function with Angular button
I am trying to add Django to Angular. I have set up Angular web page already, and it has been running for quite awhile without any problems. I just have to add a button in Angular that is going to call python function. I searched for a way to do that, and it seems python Django is a popular way to do it. So, I have been reading and following with github open sources. I can start a new django project and starting from there, I can integrate Angular and Django just fine. But, when I tried to integrate Django into existing Angular project, that is where I have some problems. From what I saw in open sources, I think the below structure is correct. But, what I do not get is how to call a python function in views.py in django from all the way in page.html that is located in src folder (Angular side). project-ui server src app core page page.html ui_python - templates - ui - urls.py - views.py - ui_python - urls.py - manage.py in ui_python/ui/urls.py, I have urlpatterns = [path('helloworld/', views.HelloWorld, name='test')] in ui_python/ui/views.py, I have def HelloWorld(self, request): data = 'Hello World' print(data) return … -
how to allow user to update his/her own record in django
I have managed to develop a django application where a user can sign up and login using django authentication. Now i want to create a form for the user update his/her record after login based on the user model. Please help me how i will create the UpdateProfile form, loading the form in the profile.html view and updating the record when the user clicks update record button. My sign up form from django import forms from django.contrib .auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name=forms.CharField(max_length=30, required=True, help_text='Enter your first name.') last_name=forms.CharField(max_length=30, required=True, help_text='Enter your last name.') email=forms.EmailField(max_length=254, help_text='Enter a valid Email') class Meta: model=User fields=('first_name','last_name','email','username','password1','password2') widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.TextInput(attrs={'class': 'form-control'}), 'username': forms.TextInput(attrs={'class': 'form-control'}), 'password1': forms.TextInput(attrs={'class': 'form-control'}), 'password2': forms.TextInput(attrs={'class': 'form-control'}), } My profile function def profile(request): if request.method == 'POST': form = UpdateProfile(request.POST) if form.is_valid(): form.save() return redirect('profile') form = UpdateProfile() return render(request, 'profile.html', {'form': form}) else: form = UpdateProfile() return render(request, 'profile.html', {'form': form}) -
Django define which urls loaded and which temolate show
i have many html files (all of them are same) i useing base.html , but i want to define which html show, for examole when something.com/love loaded show love content, if something.com/game loaded show game content. how define this? and where define? in views.py or in html? {% for lov in lovess %} {% if forloop.last %} love Content text{{lov.body_text}} {% endif %} {% endfor %} if game urls loaded shows game body text. i do not want to copy paste and create many html files (DRY) , i want to used one basic which are extends in html files. -
django-channels. Is it possible to combine sending/receiving messages to one method?
I have some complex logic that I need to handle after my code receive some message from channel layer: send a request to client through websocket, wait for response, send another request, wait again, then send response back through a channel. Right now the only way I found is to split all logic to a bunch of smaller methods and to use lock to sync all. It's working but looks ugly. Is it possible to write something like that? async def complex_logic(self, data): with self.lock.acquire(): await self.send_ws_request1(data) resp1 = await self.get_ws_response1() data2 = self.do_something_with_resp(resp1) await self.send_ws_request2(data) resp2 = await self.get_ws_response2() await self.send_resp_to_channels(resp2) -
How to convert boostrap template to pdf in django
I have invoices bootstrap template in which data come with ajax response after invoice filled with response data then i want to convert that exact template with its css into pdf, so i can send it through email using django server. Is there is anyway to convert template with its data and css into pdf. I tried so many things but can't get desire result. I want exact pdf of this invoice with css. Thanks in adnvance. -
Suspicious file operation : Cannot configure media root and base dir in my django Project folder
I am trying to save the project files to media then grap to show in url, so far i have followed some easy techniques to avoid the file operation and stored them in media my setting.py file-> STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' my models.py files model fields-> picture = models.ImageField(null=True, blank=True, upload_to = "photos") resume = models.FileField(null=True, blank=True, upload_to = "resume") It stores then correctly and shows as media url. my urls.py file-> from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/cand/',include("core.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) main problem happens when i query a resume pdf file. It can't find the BASE_DIR from django.conf import BASE_DIR url = serializer.data["resume"] file_name = url.split("/")[-1] data=ResumeParser(os.path.join(BASE_DIR,"/media/resume/",file_name)).get_extracted_data() return Response({**serializer.data, "data": data}, status = status.HTTP_200_OK) Although it works when i use absolute path-> url = serializer.data["resume"] file_name = url.split("/")[-1] data=ResumeParser("/home/riyad/Desktop/kalkedev/services/candidate","media/resume/",file_name).get_extracted_data() return Response({**serializer.data, "data": data}, status = status.HTTP_200 _OK) is this is a django issue because i have been dealing with this issur previously and taking the easy way(default base_dir) to store file. Need to find the answer quick. -
Django Forms posting not working - Django simply renders the page again
Basically I have set up a form to create organizations. When I hit the Save button, it simply renders the page again - the POST is not working. See my code below: models.py from django.db import models from accounts.models import User from datetime import datetime, date #// ------------ FUNCTIONS -------------// # Generate Organisation IDs for each organisation def org_id_generate(): last_org = Organization.objects.all().order_by('org_id').last() if not last_org: return 'ORG_001' else: last_org_id = last_org.org_id number_in_id = int(last_org_id[4:7]) new_number_in_id = number_in_id + 1 new_org_id = 'ORG_' + str(new_number_in_id).zfill(3) return new_org_id #// ------------ MODELS -------------// class Organization(models.Model): org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False) organization_code = models.CharField(max_length=20) company_name = models.CharField(verbose_name="Company Name", max_length=60) legal_name = models.CharField(verbose_name="Legal Name", max_length=100) industry_distribution = models.BooleanField(verbose_name="Distribution", default=False) industry_education = models.BooleanField(verbose_name="Education", default=False) industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False) industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False) industry_retail = models.BooleanField(verbose_name="Retail", default=False) industry_services = models.BooleanField(verbose_name="Services", default=False) business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True) vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True) created_date = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created By") effective_start_date = models.DateField(auto_now_add=False) effective_end_date = models.DateField(auto_now_add=False, blank=True, null=True) update_date = models.DateTimeField(default=datetime.now) last_updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Last_Updated_By", verbose_name="Last Updated By") def __str__(self): return self.company_name forms.py from django import forms from organizations.models import Organization class OrganizationAddForm(forms.ModelForm): class Meta: model = Organization exclude = … -
input type="submit" doesn't show full text
and I have a list of element {{FieldName}}. when I use this list inside an input it shows just the first Word not all text? my code {% for con2 in FieldName %} <table style="border-width: 2px; border: #333;"><tr> <input type="submit" value= {{con2.FidlAbr}} name="FieldName" style="width:200px;"></tr></table> {% endfor %}</form> </div></div></div> the output should be like: BEQ , HMZ , TFT DEVO 100 , TIM SNAGUENE , TFNW , TRNW but it gave me an output like!! BEQ , HMZ , TFT, TIM, TFNW , TRNW what is the problem with it? -
How to get highest rated comment for another model through Django ORM?
This is a pretty straight forward issue but I don't know why prefetch related isn't working for me. My relevant models: class Aritcle: pass class Comment: num_likes = models.IntegerField(default=0) pub_date = models.DateTimeField('date published') word = models.ForeignKey(Article, on_delete=models.CASCADE) I want to return a list of Articles, and for each article the highest rated comment on that article (max num_likes). I have a QuerySet[Article] called search_results. I keep trying: search_results.prefetch_related( Prefetch('comment_set', queryset=Definition.objects.order_by('-num_likes').first(), to_attr="top_comment") ) But it doesn't seem to work. I've tried to use the attr and it gives me an attribute error: for article in search_results: print(article.top_comment) generates: AttributeError: 'Article' object has no attribute 'top_comment' I've tried with arbitrary query sets, doing Comments.objects.filter('pub_date') but nothing seems to work -
When typing: print(Topic.objects.all()) , I get the error message: django.db.utils.OperationalError: no such table:
hello after running this code in a models.py file: from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, ) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey( 'Webpage', on_delete=models.CASCADE, ) date = models.DateField() def __str__(self): return str(self.date) As a note, I was having trouble with migrations as I kept getting error messages related to the .ForeignKey so I got the following code from some other forum, and it finally ran the migrations but I'm not sure if this code is the problem... topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, ) After successful migrations, I ran python manage.py migrate; everything seemed to migrate fine. Then I ran python manage.py shell then I ran: >>> from first_app.models import Topic >>> print(Topics.objects.all()) but got the following error: OperationalError: no such table: first_app_topic here's the full read out: Traceback (most recent call last): File "/Users/homepage/opt/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/db/backends/utils .py", line 86, in _execute return self.cursor.execute(sql, params) File "/Users/homepage/opt/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/db/backends/sqlit e3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: first_app_topic The above exception was the direct cause of the following exception: Traceback (most recent … -
Uncaught ReferenceError: jQuery is not defined in Django
I have a simple Django project. I want to add material design bootstrap in it. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> {% load static %} <title>Material Design for Bootstrap</title> <!-- MDB icon --> <link rel="icon" href="{% static 'assets/images/mdb-favicon.ico' %}" type="image/x-icon" /> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" /> <!-- Google Fonts Roboto --> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" /> <!-- MDB --> <link rel="stylesheet" href="{% static 'assets/css/mdb.min.css' %}" /> <!-- Custom styles --> <style></style> </head> <body> <!-- Start your project here--> <header> <!-- Navbar --> <nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top"> <div class="container" style="height: 100px; "> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarExample01" aria-controls="navbarExample01" aria-expanded="false" aria-label="Toggle navigation" > <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarExample01"> <ul class="navbar-nav mr-auto mb-2 mb-lg-0"> <li class="nav-item active"> <a class="nav-link" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </ul> </div> </div> </nav> <!-- Navbar --> <!-- Jumbotron --> <div class="p-5 text-center bg-light" style="margin-top: 100px;"> <h1 class="my-1 h4">The title of our atricle</h1> </div> <!-- Jumbotron --> </header> <!-- End your project here--> <!-- Main layout --> <main class="my-4"> <div class="container"> <div class="row"> <div … -
Send email after returning response to user in django
I want to send verification email to new users. But because of slow connection it takes a long time to send an email and user will see a CONNECTION TIMED OUT error. I want to return the response to user and after that send the email. I already tried StreamingHttpResponse and using yield. But it returned a creepy response instead of the response I wanted. I prefer to do it using function view but there is no problem if I HAVE to use class view. What should I do? from django.shortcuts import render from django.http import HttpRequest def sign_up (request: HttpResponse): method = request.method if method == 'GET': # checking cookies return render(request, "template name", context) if method == 'POST': # validating data if unvalid_data: return render(request, "template name", context) # saving data return render(request, "template name", context) # sending email -
How to specify form with specific user type in DetailView Django?
In my DetailView I want to specify form for specific user type like if user is a teacher then use AttendanceForm and if user is a student then use StudentleaveForm. I have tried get method but it failed. How can I do that? here is what I have tried: class Class_detailView(LoginRequiredMixin, FormMixin, DetailView): login_url = '/' model = Class template_name = "attendance/content/teacher/class_detail.html" def get(self, request, *args, **kwargs): if request.user.is_teacher: form_class = AttendanceForm elif request.user.is_student: form_class = StudentLeaveForm return super(Class_detailView, self).get(request, *args, **kwargs) here is the error I got 'NoneType' object is not callable -
"[Site]" in email subject line when django-allauth sends email
I'm using django-allauth for user authentication in my Django project. Right now account emails are being sent through MailGun. When a password reset or confirm account email comes through, [Site] is printed in the subject line of the email as such: [Site] Password Reset E-mail How can I remove this? Thanks. -
Get user authentication or session or cookie data from php to django server
I have a php server running and using a django-dash app server as an iframe. My issue is that I want to the user to have access of the django server only if he is authorized by the credentials had given in the php server. So the django server will not have the ability to run standalone if he hasn't receive the user authentication. I tried to filter the session data that are created by the php and written in the database but my problem is how to filter the exact parameters in the django server. Do you consider any other solution to pass the authenticated data or session or cookies from php to django in order to examine the django server if the user is authenticated and then will be depict its content?? -
Wagtail modeltranslation doesn't work with DEBUG = False
I have a problem with absent redirection to the default language for the multilanguage wagtail site. If I set DEBUG = False on production, I got Internal server error, because redirection to url with language postfix is absent. If DEBUG = True everything works fine. I'm using wagtail_modeltranslation https://progtribe.com/ - doesn't work https://progtribe.com/ua - works # urls.py from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( url(r'', include(wagtail_urls)), path('dj_admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), ) -
Create function and validated_data in Django rest
This is my class and create function in serializers.py. I dont understand this create function and validated_data on serializers.py . I mean whats is purpose and what it is doing here? It is necessary or optional. Please explain in lay man terms. User = get_user_model() class UserCreateSerailizer(ModelSerializer): class Meta: model = User fields = [ 'username', 'password', 'email', ] # fields ="__all__" extra_kwargs = { "password":{"write_only":True} } This is my create function with validated data. But I have no idea of its purpose. def create(self, validated_data): username = validated_data ['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User( username = username, email = email ) user_obj.set_password(password) user_obj.save() return validated_data -
show data according to login user in admin template if login user is not admin but it's staff?
I am create two user in django admin this and this two user is able to login in admin panel. and both are user is create a blog so on display list i want to set only login user is can seen list of blog that is add by him and admin can seen all data. let's i give you a situation. suppose you create a blog site befour 1 year is this site only a one user that is super user and it's create a blog but after some time you feel that you don't have time to operate that. and you don't want to create other user panel. so at this point you dissed that i create two new staff user and give the permission that he can create blog and edit blog but thy can not delete that blog. but there are no any permission for view list of blog. so they can view all blog but user A have a permission for edit so he can edit the blog that is created by user B so that why we want to set view permission according to login user so thy can only see blogs that is … -
How can I get a particular value from sqlite using ajax in django
I want to fetch database object values. When I enter a title value to the field (newvalue) and display the corresponding descreption value to the template field (appendlabel). I know one possible solution could be Ajax, I trying for last few days but I can't get it. Below is the code, please help with the implementation. Here is my AJAX code <script> $("#getvalue").click(function () { $.ajax({ type: "GET", url: '{% url "getvalue" %}', data: { title: $('#newvalue').val(), }, dataType: 'json', success: function (response) { $('#appendlabel').append(response.alldata.description) } }); }); </script> Template part <button id="getvalue" type="button" class="btn btn-primary"> Get</button> <input id="newvalue" name="newlabel"> <label id="appendlabel"></label> Views.py def getvalue(request): descreption = request.GET.get('title', None) ob=Post.objects.get('select description from newapp_post where title=%s',[descreption]) return JsonResponse({'alldata': ob}, status=200) urls.py path('getvalue', views.getvalue, name='getvalue'), models.py class Post (models.Model): title = models.CharField(max_length=50) description = models.TextField() -
How to process a CSV file from DB in Django
I am a newbie to Django. While working on a project I have stuck on CSV operations and radio forms. I have a file in my DB and it wants to read it in my views.py. Below is the model using which I m uploading the file in the DB. class Exam_Upload(models.Model): Id=models.IntegerField(primary_key=True) Question_file=models.FileField(upload_to='Documents/') where the CSV has the following columns: Question Option1 Option2 Option3 Option4 I want all these fields to be displayed as- The question should be the ordered list in the HTML staring from 1 and the options should be in the radio button. Where I can save the selected option in the DB. Your help will be really appreciated. -
How to create set object for a Django model with a many to many field?
I'am trying add many objects(Products) for my Database by ORM. In this script i want add some products def add_new_products(self): for i in range(100): Product.objects.create(name='kk',seller_id=5,description='kkkk',category_set=set([1,2]), image='/media/product_images/burger.jpg',manufacturer_id=2) return 'ff' without adding field category_set work fine with this instructions I tried to do but it didn't help on my case How to create an object for a Django model with a many to many field? shop/models.py Product model class Product(models.Model): name = models.CharField(max_length=200) seller = models.ForeignKey(to=Shop, related_name='products', on_delete=models.CASCADE) category_set = models.ManyToManyField(to=ProductCategory) description = models.TextField(blank=True) image = models.ImageField(upload_to='product_images/', null=True) manufacturer = models.ForeignKey(to=Manufacturer, related_name='products_manufactured_by', on_delete=models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name ProductCategory model class ProductCategory(models.Model): name = models.CharField(max_length=100, unique=True) # supercategory parent_category = models.ManyToManyField('self', related_name='subcategories', blank=True, symmetrical=False) image = models.ImageField(upload_to='product_category_images/', null=True) class Meta: verbose_name_plural = "product categories" def __str__(self): return self.name -
Instance of 'Flight' has no 'id' member
enter image description here Instance of 'Flight' has no 'id' member It seems like I have no id non the above class but it was working on the video I had watched -
Using Djongo with Django is failing to install database through migration scripts with in AWS DocumentDB
I have an existing project which I have developed Django rest-framework, Djongo (ORM) and MongoDB (4.0.2). Now, I have to move it to AWS DocumentDB. I have followed the instruction of index limit provided by AWS documentdb docs. https://docs.aws.amazon.com/documentdb/latest/developerguide/limits.html But still I am receiving following error messages djongo.sql2mongo.SQLDecodeError: FAILED SQL: ALTER TABLE "django_content_type" ADD CONSTRAINT "django_content_type_app_label_model_76bd3d3b_uniq" UNIQUE ("app_label", "model") Params: () Pymongo error: {'ok': 0.0, 'errmsg': 'namespace name generated from index name is too long', 'code': 67} Version: 1.2.33 Why are we getting this issue? Can someone help me ? -
Do i have to use WSGI, nginx for small applications
i have created a simple blog like application using django and want to host it on AWS. After going through some blogs i found that django in-built server is not good for production and i have to use nginx and a WSGI for hosting. Do i need to use nginx and WSGI even for simple applications ? -
Django: add `__str__` function in models.py doesn't work
I'm following the tutorial linked below to build a Django app. Here is the content in my models.py from django.db import models class Word(models.Model): word = models.CharField(max_length=100) def __str__(self): return self.word in interactive shell, Word.objects.all()[0].word can get the actual content, e.g >>> Word.objects.all()[0].word 'the meaning of the word get' Since I've already add the __str__ function, the code Word.objects.all() is supposed to output something like <QuerySet [<Word: the meaning of the word get>]> However, I just got the same one before I add __str__ function. <QuerySet [<Word: Word object (1)>]> I've already restart everything but didn't get what is expected to be. Could someone help me with this? video: https://youtu.be/eio1wDUHFJE?list=PL4cUxeGkcC9ib4HsrXEYpQnTOTZE1x0uc&t=428