Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
which I should prefer user.address.id or user.address_id in django?
I have two models User and Address, User has a foreign key relationship with Address model, I want to get the Address id from the user object, which query I should prefer, or is there any other efficient way? user = User.objects.last() we have two queries which one is efficient: user.address.id or user.address_id Thanks -
Some objects of django forms are not saved in database?
I created a custom register form and previously it only asked for username and password.Then I added some sections such as name , lastname and email to the user registration section. After adding these, it now doesn't happen when registering the username in the database during user registration. And also name and email information is not registered. models.py from django.db import models class Register(models.Model): first_name = models.CharField(max_length=50,verbose_name="First Name") last_name = models.CharField(max_length=50,verbose_name="Last Name") username = models.CharField(max_length=50,verbose_name="Username") email = models.EmailField(verbose_name="Email") password = models.CharField(max_length=50,verbose_name="Password") confirm = models.CharField(max_length=50,verbose_name="Confirm Password") def __str__(self): return self.title forms.py from django import forms from.models import Register class LoginForm(forms.Form): username = forms.CharField(label="Username") password = forms.CharField(label="Password",widget=forms.PasswordInput) class RegisterForm(forms.ModelForm): class Meta: model = Register widgets = { 'password': forms.PasswordInput(), 'confirm': forms.PasswordInput(), } fields = ["first_name","last_name","username","email","password","confirm"] views.py from django.contrib.auth.backends import UserModel from django.shortcuts import render,redirect from .forms import LoginForm, RegisterForm from django.contrib.auth.models import User from django.contrib.auth import login,authenticate,logout from django.contrib import messages from django.contrib.auth.decorators import login_required # Create your views here. def register(request): form = RegisterForm(request.POST or None) if form.is_valid(): password = form.cleaned_data.get('password') username = form.cleaned_data.get('username') last_name = form.cleaned_data.get('last_name') email = form.cleaned_data.get('email') first_name = form.cleaned_data.get('first_name') newUser = User(username = username) newUser = User(first_name = first_name) newUser = User(email = email) newUser = User(last_name … -
Change django language code from URL pattern
I have this languages code setup on my Django application. LANGUAGES = [ ('en', _('English (US)')), ('de', _('Deutsch')), ('fr',_('Français')), ('ja',_('日本語')),# -> JP ('ko',_('한국어')),# -> KR ] And on the url patterns i have the following setup: urlpatterns = i18n_patterns( path('', include('main.urls')), prefix_default_language=False ) So my application has the languages folder prefixed on the URLs. But i need the languages ja and ko to work from other prefixes, jp and kr, respectively. I tried using a middleware to override the request.path_info and the site responds on the required urls but it builds the internal links on the bad urls. -
Django using MySQL deployment - Window server apache mod_wsgi
I don't know how to deploy Django web application using MySQL on Window Server. I did some searches on google but i can't find anything relating to the topic. There are some videos on google about deploying Django on Window Server, but most of them use SQLite. I need some guidance for this setup or any good articles would be appreciated. Thanks in advance. -
Adding an Array to an a href link using Javascript/Jquery
I'm currently writing a functionality, whereby the users will click on a particular email and this will be added to a list in the local storage, thereafter, the user will click a button, essentially that button should popular a href tag, so that all the mail addresses are copied to user's default email settings (in my case outlook). My question is how do you convert this into an email format?, I have tried loading it into the tag and it works, but then Django interprets this as a URL, not a mailing list? So far I have the following: <td class="virtualTd" onclick="putThis(this)">{{ client.email }}</td> <script> const emails_list = [] function putThis(control) { var email = control.innerText; emails_list.push(email); } </script> This populates an array with all the addresses, Thereafter, the user can click this button to load the data in to local storage, with the ultimate intention to load the outlook email <a href="#" id="sendEmail" class="btn btn-primary" onclick="popEmail()"> Email Client </a> <script> function popEmail() { const jsonArr = JSON.stringify(emails_list); localStorage.setItem("array", jsonArr); const str = localStorage.getItem("array"); const parsedArr = JSON.parse(str); console.log(parsedArr); var a = document.getElementById('sendEmail'); a.href = parsedArr; } </script> -
Django uploading images via admin panel error
Hello when I want to test uploading images via admin panel I keep getting an error. No such file or directory: '/todoapp/media/cola.png'. I have no idea what did I wrong and unluckily I have to paste ton of code. model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) image = models.ImageField(upload_to='media/', default='ww1.jpg') urls.py urlpatterns =+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) tree: ├── docker-compose.yml ├── Dockerfile ├── home │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── signals.py │ ├── static │ │ └── home │ │ ├── etc. etc. │ ├── templates │ │ └── home │ │ ├── etc. etc. │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── media │ ├── dress.png │ └── pictures │ └── ww1.jpg ├── requirements.txt ├── todoapp │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── settings.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── wsgi.cpython-39.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── travis_script.sh -
HTML form not passing data in Django views.py, passing null string
I have been trying to build a multi step form and when submitted the form, the default from select tag and empty string from input tag is passed. And thus the conversion to integer in views.py is showing a value error. I have added name attribute in the html forms yet the values aren't being passed. Could anyone help me what I am missing? HTML <section> <div class="container"> <form method="POST" action="{% url 'cost' %}"> {% csrf_token %} {{form}} <div class="step step-1 active"> <div class="form-group"> <div class="custom-select type" style="width:200px;"> <p class="details">Product Type</p> <div class="buff"></div> <select id="type" name="type"> <option value="0">Select type:</option> <option value="1">Shopping Bag</option> <option value="2">Card</option> <option value="3">Box</option> </select> </div> </div> <div class="buff"></div> <div class="buff"></div> <div class="buff"></div> <div class="buff"></div> <div class="buff"></div> <div class="form-group"> <div class="custom-select purpose" style="width:200px;"> <p class="details">Product Purpose</p> <div class="buff"></div> <select id="purpose" name="purpose"> <option value="0">Select Purpose:</option> <option value="1">Corporate Gifts</option> <option value="2">HR</option> <option value="3">Packaging</option> </select> </div> </div> <button type="button" class="next-btn position">Next</button> </div> <div class="step step-2"> <div class="form-group"> <div class="buff"></div> <div class="buff"></div> <div class="buff"></div> <div class="buff"></div> <p class="details">Quantity of Product:</p> <div class="buff"></div> <input type="text" placeholder="How many pieces..." name="quantity"> <div class="buffer"></div> </div> <button type="button" class="previous-btn position">Prev</button> <button type="button" class="next-btn position">Next</button> </div> <div class="step step-3"> <div class="form-group"> <div class="buff"></div> <div class="buff"></div> <div class="buff"></div> <p … -
Fetched objects from django are displayed as numbers/ids
I'm using React frontend and Django backend. I've managed to make it so users can add rats to their account, however when I wanna fetch details about the rats the details are displayed as numbers, I'm assuming the id of the detail? Here's an example. This is what you get if you view one of the rats, frontend-wise: User: 12, Rat Name: newrat Rat Body colour: 3, Eye colour: 3 So as you can see, you get the id (?) of each detail except the rat name. It belongs to the user with the id of 12, and the 3rd body colour created, etc. Here's my models: class EyeColour(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class BodyColour(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class rat(models.Model): name = models.CharField(max_length=132, null =True) body_colour = models.ManyToManyField(BodyColour, related_name='bodycolour') eye_colour = models.ManyToManyField(EyeColour, related_name='eyecolour') user = models.ForeignKey(User, on_delete=models.CASCADE, null = True) def __str__(self): return self.name Serializers: class EyeColourSerializer(FlexFieldsModelSerializer): class Meta: model = EyeColour fields = '__all__' class BodyColourSerializer(FlexFieldsModelSerializer): class Meta: model = BodyColour fields = '__all__' class RatSerializer(FlexFieldsModelSerializer): class Meta: model = rat # fields = '__all__' exclude = ['bio'] # read_only_fields = ['eye_colour', 'body_cdolour'] expandable_fields = { 'EyeColour': ('accounts.EyeColourSerializer', {'many': False}), 'Image': ('accounts.ImageSerializer', … -
how can i get mail from from_mail in django?
I am sending mail from my django site. Everything is fine and mail is also sent and received successfully, but not from_email(that put on email field in contact form). Email sent from EMAIL_HOST_USER = 'example@gmail.com' that I put on setting.py. def contact(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] phone = request.POST['phone'] message = request.POST['message'] try: send_mail(subject,message,email,['to@gmail.com',],fail_silently=False) messages.success(request, 'We get your message and reply shortly...') except: messages.error(request, "failed") return render(request, 'pages/contact.html') I want mail will be sent from email(that user put on the email field) -
XMLParser and Json parser
i wrote an xml parser request and i need this : if the request was sent xml return the response in xml, without enforcing to send Accept header return Response(data, status=status.HTTP_200_OK, headers=headers,content_type= request.content_type) the content type t+is not working what can i do? -
Connect admins name and email to a group in Django settings.py
I added ADMINS in my settings.py and I put my name and email there. Is there any way to put a group name that I created in my Django admin page instead of using hardcoded names and emails? Let's say that I have created group named moderators and I want to assign this group to ADMINS in my settings.py -
Whenever I click a link, It downloads an empty html file instead of opening another page
I am developing a Todo app with Django. I am trying to have some links in every task container to forward it into a detailed page of the task. So whenever I run the server in localhost and try to click on those links. it downloads empty Html files (with the name 'download.html'). I trided to figure if the problem is in the path of the URL but It turns out to be fine. <div class="col-md-4"> <a class="btn btn-info btn-sm" href="edit-task/">Edit</a> <a href="" class="btn btn-danger btn-sm">Delete</a> </div> I cleared the browser data like google chrome community suggestion, but nothing changed, Please Help me. Do not worry! everything in urls.py and views.py is set correctly -
Merge two records to one record based on an item in bootstrap table
I have a Django web app for managing books, using Django rest framework and bootstrap table. In the frontend, the user want to merge two records (part time and full time) to one record (ALL) in frontend. That is, merging the below two records to one one row with course type "ALL" in the frontend. enter image description here enter image description here HTML: <table contenteditable='true' class="table table-bordered table-xl" width="100%" cellspacing="0" style="font-size: 1.0rem;" id="bk-table" data-toggle="table" data-toolbar="#toolbar" data-cookie="true" data-cookie-id-table="materialId" data-show-columns="true" data-show-export="true" data-export-types="['excel','pdf']" data-height="1650" data-click-to-select="true" data-id-field="id" data-show-footer="true" data-url="/api/materials/" data-query-params="queryParams" data-remember-order="true" data-pagination="true" data-side-pagination="client" data-total-field="count" data-data-field="results"> <thead class="thead-dark" > <tr contenteditable='true'> <th class ='courseCode' data-field="courseCode" data-formatter="renderCourse">Course Code</th> <th data-field="type" data-formatter="renderCourse">Course Type</th> <th class ='title' data-field="book.title" data-formatter="renderCourse">Course Material Title </th> </thead> </table> RESTful API(using DRF): class BookSerializer(serializers.HyperlinkedModelSerializer): publisher = serializers.ReadOnlyField(source='publisher.name') class Meta: model = Title fields = ['id', 'url', 'title'] class CourseSerializer(serializers.ModelSerializer): # semester = SemesterSerializer(many=False) courseCode = serializers.ReadOnlyField(source='courseInfo.code') courseTitle = serializers.ReadOnlyField(source='courseInfo.title') courseType = serializers.ReadOnlyField(source='courseInfo.type') year = serializers.ReadOnlyField(source='semester.year') month = serializers.ReadOnlyField(source='semester.month') term = serializers.ReadOnlyField(source='semester.term') school = serializers.ReadOnlyField(source='courseInfo.school.code') class Meta: model = Course fields = ['id', 'courseInfo', 'semester', 'courseCode', 'courseTitle', 'courseType'] class MaterialSerializer(serializers.ModelSerializer): book = BookSerializer(many=False) course = CourseSerializer(many=False) school = serializers.ReadOnlyField(source='course.courseInfo.school.name', allow_null=True) courseId = serializers.ReadOnlyField(source='course.courseInfo.id') year = serializers.ReadOnlyField(source='course.semester.year') month = serializers.ReadOnlyField(source='course.semester.month') term = serializers.ReadOnlyField(source='course.semester.term') quota … -
is there any other way i can use django @login_required parameter?
this little stuffs has been frustrating me since yesterday, i was trying to add @login_required parameter to my create function in django, the code works really well without adding the @login_required parameter, but bring page not found when i add @login_required. this is my code. urls.py app_name = 'accounts' urlpatterns = [ path('signup', views.signup_view, name='signupp') , path('login', views.login_view, name='loginn'), path('logout', views.logout_view, name='logoutt') ] views from django.contrib.auth.decorators import login_required @login_required(login_url='accounts/loginn/') def jayapp_create(request): return render(request, 'jayapp/jayapp_create.html' ) when i go to http://127.0.0.1:8000/jayapp/create/ it shows Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/jayapp/accounts/loginn/?next=/jayapp/create Using the URLconf defined in JayDjango.urls, Django tried these URL patterns, in this order: admin/ accounts/ jayapp/ [name='list-in'] jayapp/ log jayapp/ create [name='create'] jayapp/ / [name='detail'] backen/ ^media/(?P.*)$ The current path, jayapp/accounts/loginn/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
DRF : Getting nestted serializer fields for custom checks
Here is my master and detail serializers. class MasterSerializer(serializers.ModelSerializer): class Meta: model = Master fields = ['id','date_signed','info1','info2'] class DetailSerializer(serializers.ModelSerializer): master = MasterSerializer(read_only=True) class Meta: model = Detail fields = ['id','master','date_start','date_end','info3','info4'...] def validate(self, attrs): # 1. check if date sign is always grater than date start # 2. check date start is greater than date end What i am trying to do is to check if the date_signed in master serializer is always a date before the date_start one. For that i need the date_signed in the detail serializer. So how can i get it. May be is a simpler question, but i am finding it difficult as i just started learning drf. I searched a lot, but couldnt get the solution i needed. Hope to get some help to point me in the right direction. Thanks in advance -
How to create a django reset framework api serializer for models that is `ManyToMany` field with `through` attribute?
How can I create a serializer for Model that has ManyToMany field with through attribute using django reset framework. I need to embed this serializer with the parent serializer to be represented at the same API route. -
My search form is not reflecting the details of my page DJANGO
I'm currently trying to create a search page that shows the content of a page but it is not working. Kindly guide me on what I am doing wrong. I don't have a model to reference this to as the content of the pages were created in a folder called utils.py with files that contain what I am trying to display. I've tried two different search view functions and brainstormed my head out so I would really appreciate help on this URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("search", views.search, name="search"), ] LAYOUT.HTML <form action="{% url 'encyclopedia:search' %}" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> ENTRYPAGE.HTML {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} {{ content|safe }} {% endblock %} INDEX.HTML <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href="{% url 'encyclopedia:entrypage' entry.title %}">{{ entry|safe }}</a></li> {% endfor %} </ul> VIEWS.PY def entry_page(request, title): title = util.get_entry(title) if title: content = markdown2.markdown(title) context = { "title": title, "content": content, } return render(request, "encyclopedia/entrypage.html", context) else: return render(request, "encyclopedia/errorpage.html") # def search(request): # if request.method == 'GET': # query = request.GET.get('q') # … -
The field was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed
its my installed apps : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'leadgenerator', 'leadgenerator.apps.ui', 'leadgenerator.apps.accounts', 'leadgenerator.apps.instagram', 'leadgenerator.apps.BorseBots', 'leadgenerator.apps.TelegramBorse', 'leadgenerator.apps.Utils', 'leadgenerator.apps.Blog', 'leadgenerator.apps.Crypto', 'channels', 'multiselectfield', 'django_redis', 'django_filters', 'extra_views', 'django_select2', 'compressor', 'django_celery_beat', 'crispy_forms', 'django_tables2', 'ckeditor', 'ckeditor_uploader', # 'leadgenerator.ckeditor5', 'leadgenerator.rolepermissions', 'rolepermissions', # login and login_as 'loginas', 'allauth', 'allauth.account', 'allauth.socialaccount', 'phonenumber_field', # blog 'modelcluster', 'taggit', # end blog 'imagekit', 'pwa' ] and i used user in models : from django.contrib.auth.models import User as djangoUser class BlogPost(models.Model): author = models.ForeignKey(djangoUser, on_delete=models.CASCADE, related_name='blog_posts', verbose_name=_('Author')) migration now is 0013 when i use backward migrate like this : migrate Blog 0011 error happend : ValueError: The field Blog.BlogPost.author was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed. also i do not have AUTH_USER_MODEL in settings.py also i can not remove data base because have so many data on it. what is problem?? using django2.2 python3.7 postgresql -
How to use render_to_string() to validate template
I'm trying to validate the template being entered by the user class TemplatesForm(forms.ModelForm): class Meta: model = Templates def validate_temp(self): name = self.cleaned_data.get('name') html = self.cleaned_data.get('html') html_form = render_to_string(html) try: HttpResponse(html_form) except TemplateSyntaxError as e: logger.error(f"email template of name={name}suffers syntax error ") raise e class TemplateAdmin(TabbedDjangoJqueryTranslationAdmin): form = EmailTemplateForm list_display = ('name', 'code', 'subject_en', 'subject_ar') actions = None search_fields = ['name', 'code', 'text_en', 'text_ar', 'html_en', 'html_ar', 'subject_en', 'subject_ar'] admin.site.register(EmailTemplate, EmailTemplateAdmin) is this trial correct or something is better -
I need help in django
I want to print First semester's Subjects in First Semester & Second semester's Subjects in Second Semester and so on. See this pic cick in image here Maybe there is some logic in views.py that Im not having on my mind rn.Can someone help me in this logic and how to render it in semester.html page My code is here. models.py from django.db import models from django.db.models.base import ModelState # Create your models here. class Course(models.Model): faculty = models.CharField(max_length=100) class Semester(models.Model): sem = models.CharField(max_length=100) faculty = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return F"Semester {self.sem} at Faculty {self.faculty}" class Subject(models.Model): faculty = models.ForeignKey(Course, on_delete=models.CASCADE) sem = models.ForeignKey(Semester, on_delete=models.CASCADE) subject_name = models.CharField(max_length=100) def __str__(self): return str(self.id) views.py from django.shortcuts import render from django.views import View from django.contrib import messages from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django import forms from django.utils.translation import gettext, gettext_lazy as _ from .forms import CustomerRegistrationForm from .models import Course, Semester, Subject # Create your views here. def home(request): return render(request, 'app/home.html') def faculty(request): course = Course.objects.all() return render(request, 'app/faculty.html', {'course':course}) class SemesterView(View): def get(self, request,id): obj = Course.objects.get(id=id) print(obj) semobj = Semester.objects.filter(faculty=obj) print(semobj) subobj = Subject.objects.filter(faculty=obj) print(subobj) return render(request, 'app/semester.html', {'obj':obj, 'semobj':semobj, 'subobj':subobj}) semester.html {% extends 'app/base.html' %} … -
WebSocket connection failed no error message
WebsocketConnectionFailed When I access the web directly, I can establish a websocket connection.When I set up websocket in acapp, it will fail on my pc. When I use other people's computers, everything works fine. When the connection fails, the console cannot even give an error message. -
How to delete an entry from queryset in django html template without refresing page?
On my HTML template, I am printing a list of my QuerySet that I passed from views.py in Django. I want users to delete an entry from the list without refreshing the page. How do I do that? -
How do I host a function in a web server, which returns a value back to the client?
I made an ML model that classifies images, and I want to implement it to my application. But the problem is that the file is too heavy and requires an unreasonable amount of disk space for an android application. So I was wondering if I could host the Model function in a server, which would return the prediction back to the client, when I can call from my python script. I couldn't find any specific tutorials on hosting functions, with would return output back the the client. So How do I go about doing this? Here is the function I wish to host- from keras.models import load_model from PIL import Image, ImageOps import numpy as np labels= ["Banana", "Fan", "Clock","Coin","Leaf","Paper_airplane","Pen","Phone","Spoon","Tomato"] model = load_model('keras_model.h5') data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) #Here I wish to pass the image, from my python program, and recieve the prediction def RunPrediction(img): image = img size = (224, 224) image = ImageOps.fit(image, size, Image.ANTIALIAS) image_array = np.asarray(image) normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1 data[0] = normalized_image_array #And I want to recieve this output in my code prediction = model.predict(data) return prediction -
Parsing data from django backend into react component
Hi I am trying to parse JSON data from Django view into the frontend. Basically in my view, I defined the data which I want to parse and it looks like this : user_information = {'username':request.user.username, 'email':request.user.email, 'first_name':request.user.username} Then in the html, I can parse it into the javascript using json_script which looks like this: {{ user_information|json_script:'user_information' }} Then I want to call the user_information variable in React component using this script: class Form extends React.Component { constructor(props){ super(props); this.state = { user_information: null }; } componentDidMount() { this.setState({ user_information: JSON.parse(document.getElementById('user_information').textContent) }); console.log(this.state.user_information); } render () { return( <h1>{this.state.user_information}</h1> ); } } To test tis out I tried to print it in the console to see whether it is successfully parsed to the component state. But it turns out that in the console I got null. Can you guys help me what are my mistakes and how do I solve it ? -
Django Celery ORM None field
In celery task i getted my object (Order). Object contains ManyToManyField and then i call it i recived None. However when i call the same code in django shell i recived back correct list of objects. What wrong with celery task and what i can do with that? @app.task() def send_admin_email_task(): yesterday = datetime.now() - timedelta(days=1) orders = Order.objects.filter(timestamp__gte=yesterday, status=Order.StatusChoice.NEW) print(orders.first().orderItems) class OrderItem(models.Model): product = models.ForeignKey('products.Product', null=True, on_delete=models.SET_NULL) count = models.PositiveIntegerField() price = models.FloatField(default=-1) сlass Order(models.Model): orderItems = models.ManyToManyField(OrderItem) price = models.DecimalField(decimal_places=2, max_digits=10, default=0) full_name = models.CharField(max_length=200, blank=True) email = models.EmailField(blank=True) phone = models.CharField(max_length=12, blank=True)