Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add OneToMany relation model instances from parent model instance Django Form
I have a Person model: class Person(models.Model): name = models.CharField(max_length=100) And then a Car model: class Car(models.Model): plate = models.CharField(max_lenght=100) owner = models.ForeignKey(Person) And then a certain CarAttribute model: class CarAttribute(models.Model): whatever = models.CharField(max_lenght=100) car = models.ForeignKey(Car) Person has a relation 1 to many to Car. Car has a relation 1 to many to Car attributre. Is there a way in Django for adding the Car (and eventually its relative CarAttributes) in the Form to be used when adding a new Person? One person may have more than one car, and one car can multiple attributes. Any hints on how to approach this solution with Django? Or complementary tool? -
How to use blocks for attribute in django
I want to use jinja2 blocks for attribute in django. Basically on every page I want a different url for a header image. This is the base.html: <header id="masthead" style="background-image:url('{% block headerimage %}{% endblock %}'" . . . How do I pass in '{% static 'img/some-bg.jpeg' %} to it from index.html which {% extends "base.html" %}? I tried to use this block syntax I just showed and it does now work. How do I achieve this? I want to pass in a string for the url of an image from a template that inherits from the base template. Thank you :-). -
Django rest ModelViewSet multiple GET requests with different URLs
I have to Models: A Library can have many Books. Right now I have a URL for performing CRUD on Books in a specific Library: router.register(r'books/(?P<library_id>[0-9]+)', BookViewSet, base_name='books') and corresponding view: class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer def get_queryset(self): genre_query = self.request.query_params.get('genre', None) status_query = self.request.query_params.get('status', None) author_query = self.request.query_params.get('author', None) books = Book.objects.filter(which_library=self.kwargs.get('library_id')) if genre_query: books = books.filter(genre=genre_query) if status_query: books = books.filter(status=status_query) if author_query: books = books.filter(author=author_query) return books I originally did not use ModelViewSet instead I had functions with @api_view decorators, one of which was following (returning books added in last two weeks, I had a separate URL for this function as api/books//new_arrivals): @api_view(['GET']) def new_arrivals(request, library_id): """ List all new arrival books in a specific library """ d=timezone.now()-timedelta(days=14) if request.method == 'GET': books = Book.objects.filter(which_library=library_id) books = books.filter(when_added__gte=d) serializer = BookSerializer(books, many=True) return Response(serializer.data) While using ModelViewSets, how can I do it? Must I add another URL and then write another class for new_arrivals or write a function in existing BookViewSet? How to achieve handling those two GET methods in that case? -
Why do we need Signatures in Celery?
I've started using Celery 4.1 in my Django Python project and have come across Signatures. In the documentation it says the following: You just learned how to call a task using the tasks delay method in the calling guide, and this is often all you need, but sometimes you may want to pass the signature of a task invocation to another process or as an argument to another function. A signature() wraps the arguments, keyword arguments, and execution options of a single task invocation in a way such that it can be passed to functions or even serialized and sent across the wire. Although I see them used in some of the examples I don't really know when and why to use them, as well as which problems they solve. Can someone explain this to a layman? -
Display logo in my django-admin
I plugged Django-jet to my project and it works fine. I am trying to install a logo on the top left corner of my Django-admin, but it failed. I think the following answer is relevant here : Custom logo in django jet. (venv) ┌─╼ [~/Projects/Work_Projects/clients.voila6.com/v6] └────╼ ls .. dev_requirements.pip dploy.yml v6_project media requirements.pip dploy v6 manage.py README.md scripts (venv) ┌─╼ [~/Projects/Work_Projects/clients.voila6.com/v6] └────╼ ls admin.py clientspace core fixtures messaging __pycache__ templates urls.py apps.py configurations customers __init__.py orders settings.py tests.py views.py So templates/admin/base_site.html is in ~/Projects/Work_Projects/clients.voila6.com/v6, media/my_logo.png is in ~/Projects/Work_Projects/clients.voila6.com and MEDIA_URL is in ~/Projects/Work_Projects/clients.evoila5.com/ev5_project/conf/settings/common.py Here is my base_site.html file {# Template: your_app/templates/admin/base_site.html #} {% load static i18n %} {# Setup favicon #} {% block extrahead %}<link rel="shortcut icon" type="image/png" href="/media/e5_favicon.png"/>{% endblock %} {# Setup browser tab label #} {% block title %}{{ title }} | {% trans "Your title" %}{% endblock %} {# Setup branding #} {% block branding %} <h1 id="site-name"> <a href="{% url 'admin:index' %}"> {# Your logo here #} <img style="background-color: white" src="{{MEDIA_URL}}{% trans "e5_logo_eng-300x150" %}.png" alt="évoilà5" height="50%" width="50%"> <!--<br><br>--> <!--</span> {# trans "Your Branding" #%}--> </a> </h1> {% endblock %} I have not a lot of experience with Django and I think I forgot a step, but … -
Django Wrong save image in view func, but in admin panel save correct! how to fix?
Why does jango save the image while in the main specified directory, add one more such directory with the same name, and only create the necessary package and store it there? P.S. on local work everythin, if i save image using browser and admin pane, he save where it's need and suppose to be there, but if it makes in view, via for after gen image, save with wrong path this is my media root location theband@TheBand:~/media$ ls fake_qr_code_img media section_about did you see this *** same folder but in models set, some another special folder, without media this is model class QRCode(models.Model): user = models.ForeignKey(UserProfile, blank=True, default=None) qr_code = models.CharField(max_length=120) qr_code_img = models.ImageField(upload_to="qr_code_img/", width_field="width_field", height_field="height_field") upcoming_show = models.ForeignKey(SectionUpcomingShow) width_field = models.IntegerField(default=270) height_field = models.IntegerField(default=270) is_active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return "{0} - - {1}".format(self.user.user.username, self.is_active) def save(self, *args, **kwargs): img = Image.open(self.qr_code_img) img_name = self.qr_code_img.name new_image_io = BytesIO() if img.format == 'JPEG' : img.save(new_image_io, format='JPEG', quality=85) elif img.format == 'PNG' : img.save(new_image_io, format='PNG', quality=85) elif img.format == 'jpg' : img.save(new_image_io, format='JPG', quality=85) self.qr_code_img.delete(save=False) self.qr_code_img.save( img_name, content=ContentFile(new_image_io.getvalue()), save=False ) super(QRCode, self).save(*args, **kwargs) class Meta: ordering = ["-timestamp"] verbose_name = 'QRCode' verbose_name_plural = … -
Python Django how can't render my variables from views.py on html file
How can i render my variables from models in a html file, they was rendering a time ago before I made html link slug with class(DetailView) in my views.py HTML FILE (product.html) <h2 class="heading">{{ product.name }}</h2> <div style="clear: both;"><br></div> <div class="block"> <div class="img_preview"> <img src="{{ product.img }}"> <div class="categ"> {% for category in product.category.all %} <a href=""><span>{{ category }}</span></a> {% endfor %} {# <div style="clear: both"><br></div> #} </div> </div> <div id="links"> {% for link in links %} <div class="download_link"> <a href="{{ links.link }}"><span>DOWNLOAD MIRROR NUMBER {{ links.number }}</span></a> </div> {% endfor %} </div> <div style="clear: both"></div> <div id="games"> <div id="video_trailer"> <iframe width="560" height="317" src="{{ product.video_trailer }}" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe> <div id="description"> <span class="title">Description</span> <p>{{ product.description }}</p> </div> </div> <div style="clear: both"><br></div> <div id="system_requirements"> <span class="title">System Requirements</span><br> <p>Processor:&ensp;{{ product.processor }}<br> <br> Graphic Card:&ensp;{{ product.video }}<br> <br> Memory:&ensp;{{ product.ram }}<br> <br> Disk Space:&ensp;{{ product.disk_space }}<br> <br> OS:&ensp;{{ product.oS }} </p> </div> </div> <div id="screenshots"> {% for image in product_images %} <div class="screenshot"> <img width="1920px" height="1080px" src="{{ image.image }}" > </div> {% endfor %} </div> </div> </div> <aside> <div id="news"> <h2 class="heading">News</h2> <div style="clear: both"><br></div> {% for articles in news_articles %} <div id="articles"> <div class="article"> <a href="{{ articles.article.get_absolute_url }}"> <img src="{{ articles.image … -
Modify form data (in formset)
I have a form RegExpForm form and a formset, MovieFormSet, made up of model forms from the Movie model. Simplified: class RegexpForm(forms.Form): regexp = forms.CharField() class MovieForm(ModelForm): class Meta: model = Movie fields = [ 'title', 'year', ... ] I am scraping some raw data, that may look different from time to time. So in a View, I am using that raw data to create Movie objects. I also want the possibility of entering a named regexp that is submitted, that will then modify all of these Movie objects, before saving, to extract the raw data to the correct fields. In my view, it looks like this: MovieFormSet = formset_factory(MovieForm) if 'set_regexp' in request.POST: .... movie_formset = MovieFormSet(request.POST) for movie_form in movie_formset: # Modify movie_form according to regexp, before rendering template ... elif 'save_movies' in request.POST: ... else: .... some_initial_data = scraping_results movie_formset = MovieFormSet(some_initial_data) In the set_regexp branch, I want to take the inputted regexp (admin page, not for users) and use that to match parts in the scraped data to set the values in some field. That is, use the "raw" data to modify some fields for every movie_form in the MovieFormSet. What do I write in the … -
Django REST framework makes huge queries when rendering browsable HTML
When rendering a model Model1 that has a models.ManyToManyField field to another model Model2 that has ~50K entries in the DB, the default browsable HTML rendering takes about 3s to answer, while JSON rendering takes around 30ms. Turning on the Django Debug Toolbar, shows that the following SQL request : SELECT `app_model2`.`id`, `app_model2`.`field1` ... FROM `app_model2`; takes almost 2s by itself. That query is triggered when rendering the line 14 of https://github.com/encode/django-rest-framework/blob/522d45354633f080288f82ebe1535ef4abbf0b6e/rest_framework/templates/rest_framework/horizontal/select_multiple.html#L14 Is there a way to prevent the rendering to do such expensive SQL request? In our case, we don't expect something more than just the id from these Model2 entries to be rendered. -
Python Django!! How to insert data into mysql database from form inputs
I am a starter in python django framework and am trying to capture data from my form input and submit it to mysql database but it has failed.. My site has a page named contact.html which has a form below capturing data to be submited <form method = "post" action = "/submit"> Name: <input type="text" name="your_name" /> Email Address: <input type="text" name="your_email" /> Message: <textarea rows="8" cols="50" name="your_message">> <input type="submit" name="contact_submitted" value=" Send " /> </form> These are my challenges below What do i need to put in the form action = "" How do i capture data submitted in this form How do i view submitted data on a different page Thank you all who will take an effort to provide a solution -
Data not rendering using ajax and the rest framwork
I am using the rest frame in my django app in order to access some data. For some reason I do not manage to accees it. I have no error message but the data is not showing up. my views are . class TeamChartData(APIView): queryset = MyUser.objects.all() serializer_class = MyUserSerializer, #ProjectSerializer permission_classes = [] http_method_names = ['get',] def get_serializer_class(self): return self.serializer_class def get(self, request, format=None, *args, **kwargs): cohesiveness_score = get_team_cohesivenss_score(self) data = { "cohesiveness_score":cohesiveness_score[0], } return Response(data) my Html : {% extends 'base.html' %} {% load static %} {% block body %} <div class="container paddingtop80 marginbottom30"> <div class="row"> {% if project.has_member_responses %} <div class="col-8"> <div class="jumbotron greenback"> <h4>Welcome to the Project test "{{ project.name }}" Detail page</h4> </div> </div> <div class="col-4"> <div class="jumbotron greenback"> <div class="inner-score"> <h6>Team Score</h6> <h4>{{cohesiveness_score}}</h4> </div> </div> </div> {% else %} <div class="col"> <div class="jumbotron greenback"> <h4>Welcome to the Project "{{ project.name }}" Detail page</h4> </div> </div> {%endif%} </div> <!-- case 1 = if there is not team created or linked --> {% if project.team_id == None %} {% include "projectdetailtemp/noteamcreated.html" %}< <!-- case 2 = if there is a team created but no team members --> {% elif project.team_id and project.team_id.members.count == 0 %} {% … -
Django server slow either because of requests module or socket module
My website gives deatails about different servers. I have used requests to check which server ILO IP is not working through http and which is not. After using requests.. the page loads super slow! I'm also using socket to translate DNS name to IPS. My server checks ILO Ips of many servers and if the server is broken it shows the IP as a text and if not it shows a link(THE IP) to the ILO. Do you know how to make the server load much faster? Thanks.. P.S Timeout 0.04 helped a bit.. but not fast enough.. index.html- {% if server.checkUrlAvailable is True %} <a href="//{{ server.ServerName }}.ilo.lab.radcom.co.il"> {{ server.convertIPtoDNS }} </a> {% else %} {{ server.ILO }} {% endif %} <td width="100%"><center>{{ server.Rack }}</center></td> {% if server.checkUrlAvailable is True %} <td width="100%"><h4><span class="badge badge-success">Online</span></h4></td></center> {% else %} <td width="100%"><h4><span class="badge badge-danger">Offline</span></h4></td></center> {% endif %} <td style='white-space: nowrap'> models.py - from django.db import models # Create your models here. import requests import socket class serverlist(models.Model): ServerName = models.CharField(max_length = 30,blank=True) Owner = models.CharField(max_length = 50,blank=True) Project = models.CharField(max_length = 30,blank=True) Description = models.CharField(max_length = 255,blank=True) IP = models.CharField(max_length = 30,blank=True) ILO = models.CharField(max_length = 30,blank=True) Rack = models.CharField(max_length = … -
Angular 5 & Django REST - Issue uploading files
I developed an Angular application where the user can handle brands. When creating/updating a brand, the user can also upload a logo. All data are sent to the DB via a REST API built using the Django REST Framework. Using the Django REST Framework API website I'm able to upload files, but using Angular when I send data thu the API I get an error. I also tried to encode the File object to base64 using FileReader, but it doesn't work with Django. Can you help me understanding the issue? Models: export class Brand { id: number; name: string; description: string; is_active: boolean = true; is_customer_brand: boolean = false; logo_img: Image; } export class Image { id: number; img: string; // URL path to the image (full size) img_md: string; // medium size img_sm: string; // small img_xs: string; // extra-small/thumbnail } Service: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Brand } from './brand'; const endpoint = 'http://127.0.0.1:8000/api/brands/' @Injectable() export class BrandService { private brands: Array<Brand>; constructor(private http: Http) { } list(): Observable<Array<Brand>> { return … -
Upload an image blob from Ajax to Django
I am trying to to upload an image to Django using Ajax. Ajax code: function sendImage() { console.log(blob); var fd = new FormData(); fd.append('image', blob); var tet = $.ajax({ url: '/login/photoverify/', type: 'POST', data: fd, async: false, contentType: false, processData: false, success: function (response) { console.log(response.driverBeacon); document.getElementById('username').setAttribute('value', response.username); }, error: function (error) { console.log(error); } }).responseText; } Django Code: def imageVerify(request): if request.method == 'POST': log.info('Inside imageVerify') myform = forms.Form(request.POST) if myform.is_valid(): log.info(myform.cleaned_data) file = myform.cleaned_data['image'] But myform.cleaned_data is empty. Can someone please help? -
django-extuser Custom user model for Django Framework
I have a problem with custom user authentication. I download app from https://github.com/dunmaksim/django-extuser. Try to use it bun when i create superuser, run python manage.py runserver and login i have sign: "You don't have permission to edit anything." My github https://github.com/Loctarogar/useraccount. I tried django 1.11 and 2.0 result the same. So the problem is - I can't create admin user. -
django-oscar and multitenancy
I am researching Django Oscar for the ecommerce part of our business. One of the required features is that we need to host multiple shops on one Oscar instance, i.e. every shop owner should manage his own products, his own partners etc. And should not have access to other owner's content. Google says it had this feature as of version 0.6: https://django-oscar.readthedocs.io/en/releases-0.6/howto/multi_dealer_setup.html But the current version (1.5 as of today) does not mention this feature. How to do multitenancy in later Oscar versions? -
Running tests against existing database using pytest-django
does anybody know of a possibility to run Django Tests using pytest-django against an existing (e.g. production database)? I know that in general this is not what unit tests are supposed to do, but in my case I'm running the tests on Heroku. By default Django creates a new test database. However this is not possible on Heroku. I found a solution that would work without pytest-django (python manage.py test): https://gist.github.com/gregsadetsky/5018173 But as far as I understood, pytest-django doesn't make use of the test runner defined in the Django settings. If anybody has another approach on how to run Django tests using pytest-django on Heroku (e.g. by automating a way to create the test database) I would be happy with that solution as well. Best Lars -
Can python class variable be used as both class and instance variable?
I am very confused after working with Django Framework and the model of Djano Framework class User(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_address = models.EmailField(max_length=50, unique=True) def __str__(self): return self.first_name As we can see first_name, last_name, and email_address are created as class variables but in the dunder str() method they are used with the self as instance variables So my question is wheter in Python variables declared as class variables can be used as both "Class Variables" and "Instance Variables". Thank You in advance and thanks for reading my question. -
Django rest ModelViewSet create fails
I have two models with following relationship: class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) ... class Reader(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=30) ... # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) I have defined serializers as following (I am directly creating a User while creating a Reader for a specific Library): class ReaderSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Reader #fields = '__all__' depth = 1 fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library') def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.set_password(user_data['password']) user.save() reader = Reader.objects.create(user=user, **validated_data) return reader And I am writing a ModelViewSet as following: class ReaderViewSet(viewsets.ModelViewSet): serializer_class = ReaderSerializer def get_queryset(self): readers = Reader.objects.filter(which_library=self.kwargs.get('library_id')) return readers URL: router.register(r'readers/(?P<library_id>[0-9]+)', ReaderViewSet, base_name='readers') my GET call is successful and I get all the readers in a specific Library. I am doing a POST call with following JSON data: { "username": "three", "email": "three@gmail.com", "password": "5647", "phone": "836365", "address": "sample6 address", "which_library": "2" } and also by removing "which_library" but both give me error: IntegrityError at /api/readers/2/ (1048, "Column 'which_library_id' cannot be null") What am I doing wrong? -
How to safely count dictionary keys in python
I'm writing a django application where I will get a dictionary from the user that can be of variable size. I want to have a limit for how big the dictionary can be, i.e. how many (key, value) pairs it can hold. I want it to be no bigger than 200. I suspect that if I do: if len(user_dict)>200: raise ValidationError("dict has too many (key, value) pairs") python will have to count the whole dict. If the dict is huge, because of a malicious user, this will eat unnecessary processing power. Or does the dict keep track of how many objects it holds, meaning len(user_dict) is a simple lookup operation? What is the best way to solve this problem? I was thinking something like: i=0 for key in user_dict.keys(): i += 1 if i>200: raise ValidationError("dict has too many (key, value) pairs") -
Django - How to work with `auth_permission` Model
Django make its own permission models, like auth_permission. I want to add new permission doing this by code. How I normally add something to a table from .models import Model mdl, succeeded = Model.objects.get_or_create( field=value, field=value ) mdl.save() But to call the auth_permission Model, I have to import the model first. Only I can't find how this Model is called. So do one of you guys know what to import to call this Model? -
How to make frontend structure on Django?
How to build ordinary frontend structure using Django (Python 3)? What should I do to place, for example, gulp, Bower, SASS, React.js here? -
Django - error but no ValidationError at Imageupload, if no image is choosen
first of all, I'm new to django.I try to implement an avatar to my user model. Everything is working as expected so far, apart from one little thing: If i want to upload a new avatar to my profile, there is a "chosse File" and a "Upload" (submit) button. If I choose a file and press the Upload button, the avatar changes correctly and everything is fine. But when I don't choose a file and press "Upload", the Validation error: "Please select a file" pops up. If I don't use a default avatar in my model it works. But when I have activated the default avatar in my model , there is no "Please select a file" pop-up and following error occurs: Thank you for your help ! error Exception Type: FileNotFoundError at /account/aaa/avatar Exception Value: [Errno 2] No such file or directory: 'avatars/default_avatar.png' My default_avatar.png is located at src/media/avatars/defaultt_avatar.png The problem occurs in this line: File "/.../src/account/forms.py" in save28. im = Image.open(self.cleaned_data['image']) models.py class Profile(models.Model): def get_image_path(instance, self): return 'avatars/{}/{}'.format(instance.user, instance.user) ... image = models.ImageField( _('avatar'), storage=OverwriteStorage(), upload_to=get_image_path, default=os.path.join("avatars", 'default_avatar.png') ) views.py class ChangeAvatarView(UpdateView): model = get_user_model() template_name = 'account/change_avatar.html' form_class = ChangeAvatarForm slug_field = "username" slug_url_kwarg = 'username' … -
How can I do Server Side Rendering of reactJS app with Python/Django as backend?
I have created the reactjs app using create-react-app and have used react-route-dom for routing. I have used Python/Django Rest Framework for the backend. Now I am facing issues like I can't post every page with the different previews and titles on social media platforms. Also, I have read the CSR(Client Side Rendering) is not good for SEO. -
Django .save(using='...') correct database name
My Django settings.py contains the following: DATABASES = { 'default': { # several settings omitted 'NAME': 'myproject', 'HOST': 'localhost', }, 'other': { 'NAME': 'other', 'HOST': 'else.where', } } I now want to fetch some objects from the other DB and save it to default like so: things = Thing.objects.using('other').raw('SELECT code,created FROM other.otherapp_bigthing WHERE created>...') # 'code' is a unique string in other and PK of the Thing model for t in things: t.save(using='default') This gives me ProgrammingError: (1146, "Table 'other.myapp_thing' doesn't exist") which is a correct observation, however, by the documentation of the using parameter I expected the records to be saved to myproject.myapp_thing. Why is the database name still taken from the other configuration when I explicitly advised it to use default?