Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create multiple objects with one request DRF
I have the following models class Product(models.Model): name = models.CharField(null=True, blank=True, max_length=500) category = models.CharField(null=True, blank=True, max_length=120) class SpecificationName(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, related_name='specifications') name = models.CharField(max_length=125) class Attribute(models.Model): spec_name = models.ForeignKey(SpecificationName, on_delete=models.CASCADE, null=True, related_name='attributes') index = models.CharField(max_length=200, blank=True, null=True) value = models.CharField(max_length=250, blank=True, null=True) after saving objects in Django admin I have an example { "name": "Apple Smart Watch", "category": "IT", "specifications": [ { "name": "Test Data", "attributes": [ { "index": "test", "value": "test2" }, { "index": "test7", "value": "test8" }, { "index": "test9", "value": "test10" } ] }, { "name": "Test Data Continued", "attributes": [ { "index": "bla", "value": "bla1" }, { "index": "bla 2", "value": "bla 4" }, { "index": "test9", "value": "test10" } ] }, { "name": "Test Spec", "attributes": [] } ] } I need to save this kind of object with one request but I am failing to do this my serializer looks like this class ProductSerializer(serializers.ModelSerializer): specifications = SpecNameSerializer(many=True, read_only=True) class Meta: model = Product fields = ['name', 'category', 'specifications'] def create(self, validated_data): return Product.objects.create(**validated_data) I searched for many answers but I did not find or applied some of them, again it did not help me. I am using just ListCreateView in … -
Select multiple options in Django
In my web app. There is a Subscription model and it has 6 subscriptions. In a single order there is two subscription selected so I want to show the selected subscriptions which are there in a order from all subscriptions in frontend. I grab all the subscriptions and the order to frontend and trying this code to select. <div class="col-sm-8"> <select class="form-control" multiple> {% for subscription in subscriptions %} <option {% for sub in order.subscriptions.all %} {% if sub == subscription.title %} selected {% endif %} {% endfor %}>{{subscription.title}}</option> {% endfor %} </select> </div> But Its not working. It showing all the subscriptions in Subscription model. But I want to selected the sub which are there in a order. Here is the frontend. -
How do you write "SELECT ... WHERE id IN (SELECT ...)" in Django?
I have trouble following the reverse related relationship in a Django query: from django.db import models class Reporter(models.Model): name = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=500) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) "Get the reporters who wrote an article about coronavirus": SELECT * FROM myapp_reporter WHERE id IN ( SELECT reporter_id FROM myapp_article WHERE title ILIKE '%coronavirus%' ) How do I write this in Django? -
creating url shortner in django using hash
I am trying to create url shortener in django using hash (16 byte) in django. My Model : class UrlShort(models.Model): hash_url = models.CharField(max_length=100) original_url = models.CharField(max_length=100) creation_date = models.DateTimeField() expiry_date = models.DateTimeField() How will my function look if I need to store hash_url in database which is hashed from original_url with expiry_date of 30 seconds from creation_date ? -
VarsityDView is missing a QuerySet. Define VarsityDView.model, VarsityDView.queryset, or override VarsityDView.get_queryset()
My code is very simple but I'm getting error and I can't find the solution. views.py -> views.py file models.py -> models.py file -
How to import root directory file inside application in django?
My Project structure is depicted below: ├── project_name ├── app1 │ ├──views.py #I've to access root file1.py which is kept with manage.py in this file. │ ├──file1.py # But If I'm trying to import this file is being imported but I need root one │ ├──models.py ├── app2 │ ├──views.py │ ├──file1.py │ ├──models.py ├── manage.py ├── file1.py I'm using "from file1 import " in app1/views.py but the app1/file1.py is getting imported. Rather than this file I've to import project_name/file1.py file inside app1/views.py. How Can I do this? -
How to fix TypeError __str__ returned non-string
My code it still gives the error of __str__ returned non-string (type Contact) despite the fact that i cast the return statement with str() My model: class Contact(models.Model): name = models.CharField("Contact Name", max_length=50) surname = models.CharField("Contact Surname", max_length=50) company = models.ForeignKey(Customer, verbose_name='Company',on_delete=models.CASCADE) department = models.ForeignKey(Department, verbose_name='Department',on_delete=models.CASCADE) position = models.CharField("Position", max_length=50, null=True, blank=True) birthday = models.DateField("Birthday", null=True, blank=True) remarks = models.TextField("Remarks", max_length=500, null=True, blank=True) skype = models.CharField("Spype", max_length=50, null=True, blank=True) def clean(self): for field in self._meta.fields: if isinstance(field, (models.CharField, models.TextField)) and getattr(self, field.name)!=None: setattr(self, field.name, getattr(self, field.name).strip()) class Meta: verbose_name = "Contact" #####Overide save method to store names and surnames in caps def save(self, *args, **kwargs): for attr_name in ['name', 'surname', 'position']: val = getattr(self, attr_name, False) if val: setattr(self, attr_name, val.upper()) super(Contact, self).save(*args, **kwargs) def __str__(self): return self.surname + " " + self.name I also used to write the str function like this: def __str__(self): return str(self.surname + " " + self.name) but still the code returns the same error. Here is my traceback Django Version: 2.2.6 Python Version: 3.5.2 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'adminactions', 'django.contrib.admin', 'intranet', 'daterange_filter', 'gunicorn', 'notifications') Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Template error: In template /usr/local/lib/python3.5/dist-packages/django/contrib/admin/templates/admin/edit_inline/tabular.html, … -
autosuggest multiple search jquery
how to make autosuggests multiple value search? my view: def index(request): ... results = [] if request.is_ajax(): q = request.GET.get('term', '') if len(q) > 2: results = list(Tag.objects.filter(name__istartswith=q).values_list(Lower('name'), flat=True)) results = [f'{i} ' for i in results] return JsonResponse(results, safe=False) ... html: <div id="search"> <form method="get" action="{% url 'main:home' %}"> {% csrf_token %} <input type="text" name="q" placeholder="Поиск по сайту" value="{{ request.GET.q }}"> <input type="submit" value="Найти"> </form> </div> <script> ... $('#search input[name="q"]').autocomplete({ 'source': '{% url "main:home" %}', 'minLength': 2, 'appendTo': "#search" }); </script> this works correctly with one exception: I was offered https://jqueryui.com/autocomplete/#multiple, but I don’t understand what to do with it. I am not good at js, jq. please any help will be helpful -
Can not connect to smtp.gmail.com in Django
I'm trying to send email using smtp.gmail.com in Django project. This is my email settings. settings.py # Email Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'myaccount@gmail.com' EMAIL_HOST_PASSWORD = 'mygooglepassword' views.py ... send_mail( "message title", "message content", "myaccount@gmail.com", ["myaccount@hotmail.com"], fail_silently=False) Whenever I try to send email, I get this error gaierror at /contact-us/ [Errno-2] Name or service not known I tried the followings. I set my google account's less secure app access on. I unchecked avast antivirus setting 'Setting->Protection->Core Shields->Mail Shield->Scan outbound emails(SMTP)' Tried different ports in email settings. 587 and 25 Switched the ssl and tls in email settings. But it's not sending yet. When I use 'django.core.mail.backends.console.EmailBackend' instead of 'django.core.mail.backends.smtp.EmailBackend', it prints email on console. I double checked my gmail username and password on settings. Please help me. Thank you. -
how to create new user to login from different model?
i've try to create a system for student and teachers, create new user model to login from different model , not a OneToOneField from default User model , i want to make two different registration form for visitors (Student and Teacher) forms genders_selection = ( ('male','male'), ('female','female') ) class CustomUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) email = models.EmailField() objects = UserManager() def __str__(self): return self.username class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(choices=genders_selection,max_length=10) age = models.PositiveIntegerField() class Teacher(models.Model): teacher = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(choices=genders_selection,max_length=10) age = models.PositiveIntegerField() def __str__(self): return self.user.username but this architecture wont allow similar idea , and it will required first to create User then select one of them as student or teacher !? thanks for helping -
How to import model of of 1 project to another project in django?
I have 2 different django projects.I am trying to import model of project2 to project1, i am using same database for both the projects.How will i achieve that, here is my project structure all_pro_folder /project1_folder/ /src_project1 /app1(application) + projectfolder containing settings.py models.py, views.py etc /project2_folder/ /src_project2/ /app2(application) + projectfolder containing settings.py models.py, views.py etc I want to import src_project2's model in src_project1 just like from src_project2.app2.models import * -
local variable 'mobile' referenced before assignment
I want that when the user logged in, the data from the database should be displayed on the page. Here is the view: def login_view(request): if request.method == 'POST': mobile= mobile.objects.all() form= AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) return render(request,'pages/store.html',{'mobile':mobile}) else: form= AuthenticationForm() return render(request, 'pages/login.html', {'form':form}) The HTML page: {% load static %} <html> <head><title>store</title></head> <body> Hi {{user}} <table> <thead> <tr> <th>Model</th> <th>Price</th> </tr> </thead> <tbody> {% for item in mobile %} <tr> <td>{{ item.Model }}</td> <td>{{ item.Price }}</td> </tr> {% endfor %} </tbody> </table> </body> </html> My model consists of mobile and Price as attribute. I have tried creating a view to display the database: def display_view(request): if request.method == 'GET': mobile= mobile.objects.all() return render(request,'pages/store.html', {'mobile':mobile}) But the error showing is the same: local variable 'mobile' referenced before assignment Can anyone help me out in displaying the data to the page? I don't think the error is because I have created the signup and login forms using django built-in form. -
How to send email from my G-Suite account using Django and OAuth 2?
How to send email from my G-Suite account using Django and OAuth 2 ? I am using Django to send email but its asking me to make my account enable for less secure app. I don't want to do that, I want to use OAuth 2 in my app and send email from my G Suite account. -
Vue vs React vs Angular with Django?
I'm a Django developer planning to learn a front end framework so I could easily scale my applications.The thing that is bothering me is Which is the most simpler and easier to use framework in Vue,react and Angular that I can get started within a day,build some projects and doesn't come up with a lot of confusing things to learn about and most important is easy to integrate with Django to build large scale applications.Which one is the most appropriate in this case? -
How to access Django Docker app in a Virtual Machine?
Currently, I'm trying to access a simple Django application, which I created in an Azure Virtual Machine. As the application is still simple, I only want to access the "The install worked successfully! Congratulations!" page from my local machine by accessing http://VM_IP:PORT/. I was able to do just that, but when I tried to Dockerized the project and then trying to access it again from my local machine, it didn't work. I've already made some setup in my Azure portal so that the Virtual Machine is able to listen to specific port; in this case is 8080 (so http://VM_IP:8080/). I'm quite new in Docker so, I'm assuming there was something missing in the Dockerfile I've created for the project. Dockerfile RUN mkdir /app WORKDIR /app # Add current directory code to working directory ADD . /app/ # set default environment variables ENV PYTHONUNBUFFERED 1 ENV LANG C.UTF-8 ENV DEBIAN_FRONTEND=noninteractive # set project environment variables # grab these via Python's os.environ# these are 100% optional here ENV PORT=8080 # Install system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ tzdata \ python3-setuptools \ python3-pip \ python3-dev \ python3-venv \ git \ && \ apt-get clean && \ rm -rf … -
Django reading data from 2 models with foreignkey and make single list
I'm new to django. I've been coding with sql but django orm is hard for me to convert my knowledge of sql to orm models. I've client model class client(models.Model): c_id = models.AutoField(primary_key=True) name= models.TextField() age=models.IntegerField() and address model class address(models.Model): c_id = models.ForeignKey(client, on_delete=models.CASCADE) addr = models.CharField(max_lenght=20) city= models.CharField(max_lenght=20) This is my table --------------------------- | c_id|Name | age | --------------------------- | 1 | John | 23 | ---------------------------- | 2 | Rose | 20 | ---------------------------- ------------------------------ | c_id|addr | city | ------------------------------ | 1 | buspark | florida| ------------------------------ | 2 | homesquare| florida| ------------------------------ how to get allclient with address in list -
Django - database query optimisation - over 100 queries per request
models.py class Category: name = ... class SubCategory: name = ... category = models.ForeignKey(Category) class Item: name = ... category = models.ForeignKey(Category) subcategory = models.ForeignKey(SubCategory) class ItemImage: item = models.ForeignKey(Item) image = ... views.py def show_all(request): categories = Category.objects.all() return render(request, 'template.html), {'categories':categories}) template.html {% for cat in categories %} <!-- cat.name --> {% for subcat in cat %} <!-- subcat.name --> {% for item in subcat.item_set.all %} <!-- item.name --> <img src="{{item.itemimage_set.first.image.url}}"> Problem: The last iteration in html for itemimage_set causes extra query for each item rendered. I've got 300 items to render on the page, then over 300 queries for each request. Not sure where to add prefetch... or this is unavoidable? Please help! -
How to Setting Up Django Static Files?
So for settings up my django static files I added these code in settings.py STATIC_URL = '/static/' STATIC_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') So I created A static folder In Base Directory and then I created a folder named css inside of it and I added a file named nav.css into it. <link rel="stylesheet" href="{% static 'css/nav.css' %}"> But it's not working at all. It gives me error : Failed to load resource: the server responded with a status of 404 (Not Found) What I did wrong? -
Django summernotes model customize
I am currently working on django summernotes but facing trouble in form submission. I think it is due to the model models class htmlpage(models.Model): id= models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = models.CharField(max_length=2000) thumbnail = models.ImageField(upload_to='images/blog') tags = models.CharField(max_length=50) ... def __str__(self): return self.title The content Field in the model is implemented with summernotes. forms.py class FormName(forms.Form): title = forms.CharField(required=True) thumbnail = forms.ImageField(required=True) content = forms.CharField(widget=SummernoteWidget(), required=True) tags = forms.CharField(required=True) How to save data in Django in-order to separate the media files inside the summernotes. Currently all the image files are getting stored as text in Charfield. This way works fine for retrieving and displaying but having trouble in validating the form created. is_valid() is becoming false for every form submit. You can submit the form without is_valid() but image is not uploaded in database. form = forms.FormName() if request.method == "POST": form_name = FormName(data = request.POST) title = form_name["title"].data thumbnail = form_name["thumbnail"].data content = form_name["content"].data tags = form_name["tags"].data instance = htmlpage(title=title, thumbnail=thumbnail, content= content, tags=tags, by=request.user) instance.save() -
Django RestFramework Elastic Search: Timeline API
I'm using django restframework along with elastic search to develop a backend application for a mobile app. I need to develop a timeline API that will load a timeline of posts from other users the user is following. Along with other related poststhat the people they're following may comment. What is the best implementation method for this problem? -
duplicate key value violates unique constraint "booking_reservation_student_id_key" DETAIL: Key (student_id)=(1) already exists
I am new to Django and currently working a hostel booking system. I however experincing some errors. Firstly,I want the is_reserved field in the room model to be True upon reservation,I have tried manay ways but it doesnt work for me. Secondly,I get an error when a user tries to book twice,Is there any way I cane solve this error: Here is my code and errors displayed: def RoomBookingView(request,pk): if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) student_id = request.user reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() room_id.is_reserved = True return redirect('confirm') return render(request,'room-detail.html',{}) class Reservation(models.Model): student = models.OneToOneField(User,on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete = models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Reservation' verbose_name_plural = 'Reservations' def RoomBookingView(request,pk): if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) student_id = request.user reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() room_id.is_reserved = True return redirect('confirm') return render(request,'room-detail.html',{}) class Room(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200,null=True,blank=True,unique=True) price = models.IntegerField() hostel = models.ForeignKey(Hostel,on_delete=models.CASCADE,null=True) number_of_beds = models.IntegerField() room_thumbnail = models.ImageField(null=True) resized_thumbnail = ImageSpecField( processors=[ResizeToFill(620, 430)], format='JPEG', options={'quality': 60}) room_type = models.ForeignKey(Category,on_delete=models.CASCADE) room_number = models.IntegerField() is_reserved = models.BooleanField(default=False) description = models.TextField() def get_absolute_url(self): return … -
How to create templates folder inside of an app in Django?
So Basically I like to create templates folder in main project directory and than I just create HTML file inside of it. But now I want to create this templates folder inside of an app. How can I do it? Thanks Good people in Advance. -
Is there a method to create a persistent variable in my Django view function?
I'm currently grabbing a variable 'type' via GET when my view function is called, as shown. I need to query by this variable in my POST method. def article_delete_view(request, pk): type = request.GET.get('type') #GET THE VARIABLE from referring data-url obj = Listing.objects.get(type=type) # I could query here if I wanted (illustration only) article = get_object_or_404(Article, pk=pk) data = dict() if request.method == 'POST': article.delete() data['form_is_valid'] = True articles = Article.objects.all() obj = Listing.objects.get(type=type) #THIS DOES NOT WORK, since 'type' is not passed on submit. context = {'articles':articles, 'obj':obj} data['article_table'] = render_to_string('article_table.html', context) else: context = {'article':article} data['html_form'] = render_to_string('article_delete.html', context, request=request) return JsonResponse(data) Is there a best-practice way to make that variable persist when POST is called on a submit? I know declaring a global is a bad idea. Thought about writing it to memory (attached to article) but that feels like a hack. I could get my <input> method to pass 'type' but to do so I'd have to refactor a lot of other things. Are django session variables the answer here? Any perspective is helpful. Thanks in advance. -
When are Django model objects initialized?
I'm facing an interesting problem in Python with Django. I think just by putting my code you will get what I'm trying to do. views.py: def ingredients(request): objects = Ingredient.objects.all()[:50] return render(request, 'template.html', {'objects': objects} models.py: class Ingredient(models.Model): stock_by = models.IntegerField(null=False) unit = "" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) unit_type = { 1: 'Units', 2: 'Kilograms', 3: 'Litters' } self.unit = unit_type[IntegerField.to_python(self.cost_by)] Error: TypeError at /Ingredient/ to_python() missing 1 required positional argument: 'value' (Value is None). I think it's clear what I'm trying to achieve. Just a String attribute which will take the name of the unit value (represented by integers in db). -
Trying to understand why Selenium cannot see Binary at '/app/.apt/usr/bin/google-chrome' error despite solutions tried - using Heroku
I am trying to use Selenium and Heroku I've run into a common error: selenium.common.exceptions.WebDriverException: Message: unknown error: no chrome binary at '/app/.apt/usr/bin/google-chrome' I've come across this article as to why this may be happening: WebDriverException: Message: unknown error: no chrome binary at C:/.../Chrome/Application/chrome.exe with ChromeDriver Selenium and Python I am using Selenium 3.141.0 It suggests that Chromedriver is unable to locate the binary chrome.exe. It also suggests to ensure that I am not using the deprecated option: ChromeOptions() and don't believe I need to use the keyword argument executable_path as I am launching it from Heroku where I would use '/app/.apt/usr/bin/google-chrome' path. Other solutions I've come across suggests various different configurations and I feel like I have everything configured correctly but maybe not. What else could be the reason that I am unable to get this to work? Buildpacks https://github.com/heroku/heroku-buildpack-google-chrome https://github.com/heroku/heroku-buildpack-chromedriver Heroku Config Variables GOOGLE_CHROME_BINARY = "/app/.apt/usr/bin/google-chrome" CHROMEDRIVER_PATH = "/app/.chromedriver/bin/chromedriver" Options class WebDriver: def __init__(self): self.GOOGLE_CHROME_BINARY = config('GOOGLE_CHROME_BINARY') self.CHROMEDRIVER_PATH = config('CHROMEDRIVER_PATH') self.chrome_options = Options() self.chrome_options.add_argument("--disable-dev-shm-usage") self.chrome_options.add_argument('--no-sandbox') self.chrome_options.binary_location = self.GOOGLE_CHROME_BINARY self.chrome_options.add_argument("headless") self.driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, options=self.chrome_options) Any help even in just helping me understand what's going on better would be much appreciated