Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does DRF Built-in API documentation support file upload?
I just wrote my API and generated the built-in documentation. One of my APIs require a file to be uploaded and it works just fine but the documentation part of it where users are supposed to interact with it display the file attribute as a string not as a file type (no browse button). Did I do something wrong or does the built-in documentation not support file upload ? Thanks, -
Access ForeignKey models and fill in its fields
Please help me how to access author models and fill in the user field My models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='کاربر',blank=True, null=True) avatar = models.ImageField(upload_to='media/user_avatar/', null=True, blank=True, verbose_name='عکس کاربر') description = models.CharField(max_length=500, blank=True, null=True, verbose_name='توضیحات و رزمه') class Article(models.Model): title = models.CharField(max_length=200, blank=False, null=False, unique=True, verbose_name='عنوان') cover = models.ImageField(upload_to='media/article_cover/', null=False, blank=False, verbose_name='عکس مقاله') content = models.TextField(blank=False, null=False, verbose_name='متن مقاله') created_at = models.DateTimeField(auto_now_add=True, verbose_name='تاریخ') category = models.ManyToManyField('Category', blank=False, verbose_name='دسته بندی', related_name='article') author = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='انتشار دهنده',null=True) Article Adding Class class ArticleCreate(LoginRequiredMixin, FieldMixin, CreateView): template_name = 'registration/article_create.html' model = Article fields = ['title', 'cover', 'content', 'category', 'author', ] def form_valid(self, form): if self.request.user.is_superuser: form.save() else: obj = form.save(commit=False) obj.author.user = self.request.user obj.save() return super(ArticleCreate, self).form_valid(form) The result of these codes is this error: enter image description here -
QueryString in Django
I need one small help. I have one django application already with me and everything is working fine. Now requirement is without making change in existing functions we want to pass urls parameter as a query string path('my-app/', include('myapp.urls', namespace='myapp')), # I added this line because I want to use dcid as a querystring url(r'^my-app/(?:(?P<dcid>\w+)/)',include('myapp.urls', namespace='myapp')), and my function is already written like this def orders_b2b_open_list_pageable(request): We don't want to change in above functions but we want dcid in query string. How can we achieve that Thank You in advance -
Django int() argument must be a string, a bytes-like object or a number, not 'list' with foreignkey
I am doing batch update in my code (views.py), how do i update multiple data in django? i am having difficulties in foreignkey, productOrderList = [] productName = [] category = [] i = 0 h=0 for isa in request.POST.getlist('productname'): productName.append(isa) for isa in request.POST.getlist('category'): category.append(isa) for i in productOrderList: for product_id in request.POST.getlist("productID"): cate = ProductCategory(id=category) insert_update_groupofproduct = Product.objects.get(id=product_id) insert_update_groupofproduct.product =productName[h] insert_update_groupofproduct.category = cate insert_update_groupofproduct.save() h += 1 return redirect('adminpage') return redirect('adminpage') THis is my models.py class ProductCategory(models.Model): category = models.CharField(max_length=500) class Product(models.Model): product = models.CharField(max_length=500) category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True,erbose_name="Category") -
Django contact form which sends email
I have a question regarding creating contact form. From what I understand when someone sends it I automatically receive an email that I put in the settings. Can a reversed thing be done? I mean when someone fills the form all the information go from one email account to another. For example: user fills the title and message in the form, sends it and then that message goes from one set e-mail address (for example gmail) and then to another e-mail address (for example Outlook). I want to do that because my client doesn't want to give me the password to his e-mail. So I have to create my own e-mail on gmail and use it to send to client's e-mail. -
HyperlinkedModelSerializer not generating correct api docs using drf_yasg
I have several HyperlinkedModelSerializers in my project. When creating the swagger docs using drf_yasg, I cant seem to get the documentation of this field to work. I would like it to display this on create in the docs: "url": "http://example.com/pickup-event/{id}", But all I get in the docs is: "url": "http://example.com/", Ive tried: class PickupEventSerializer(serializers.HyperlinkedModelSerializer): def get_url(self, obj) -> str: return "Own url doc!" but it does not get picked up by the generator. -
Django - How to check if django is hitting database for certain query
I want to optimize the django app and for this I would like to know How can I check if my query is hitting database or I am getting result/return value from cached version? For example: products = Products.objects.filter(product_name__icontains="natural") if not products.exist(): return Response(...) total_products = products.count() first_product = product.first() I like to execute this in shell and want to check which line hits the database and which one just return result from cached version so I can write optimized queries in my view. I know about django-toolbar but I couldn't find if it supports things like this(does certain line hit database or result is from cached version). Regards. -
MultipleObjectsReturned at / get() returned more than one Order -- it returned 2
I am coding along with denis ivy to build an e-commerce website, now when i checkout the order get's completed as it is supposed to do but then when i return to the homepage i get this error MultipleObjectsReturned at / get() returned more than one Order -- it returned 2! and then once i delete all the orders i have in my database everything works fine until i checkout again, which means that i ave problem which is i can't have two orders in my database i really can't figure this out any help is much appreciated i'll share my views.py now from django.shortcuts import render from .models import * from django.http import JsonResponse import json import datetime def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer) items = order.orderitem_set.all() cartItems = order.get_cart_items else: items = [] order = { 'get_cart_total':0, 'get_cart_items': 0, 'shipping': False } cartItems = order['get_cart_items'] products = Product.objects.all() context= {'products': products, 'cartItems': cartItems, } return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer) items = order.orderitem_set.all() cartItems = order.get_cart_items else: items = [] order = { 'get_cart_total':0, 'get_cart_items': 0, 'shipping': False } cartItems = order['get_cart_items'] context= {'items':items, … -
Trying to link two models with a ForeignKey but get the error "IntegrityError NOT NULL"
I have a model where a user posts a job vacancy, then other users can submit applications. The submit application model is called 'CandidatesSubmission' & pulls the 'title' from a different app/model 'JobPosts'. I can add submit applications through the ADMIN page fine, but when trying to do so with a form I get "IntegrityError NOT NULL constraint failed: candidates_candidatessubmission.title_id." I believe that I'm missing something in my Views.py that essentially says "use the title of job vacancy as the title field. I have tried adding null=True, blank=False but which stops the error but the title isn't saved to the database. Any suggestions on what I'm doing wrong would be great. Thank you models.py class CandidatesSubmission(models.Model): title = models.ForeignKey('jobs.JobsPost', on_delete=models.CASCADE) Fee = models.CharField(max_length=50, null=False, blank=False) CandidateFirstName = models.CharField(max_length=50, null=True, blank=False) CandidateSecondName = models.CharField(max_length=50, null=True, blank=False) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) views.py from django.shortcuts import render, redirect, get_object_or_404 from django.db.models import Q from django.http import HttpResponseNotFound from jobs.models import JobsPost from candidates.models import CandidatesSubmission from candidates.forms import CreateCandidatePostForm from account.models import Account from operator import attrgetter # Create your views here. def submit_candidates_view(request, slug): context = {} user = request.user if not user.is_authenticated: return redirect('must_authenticate') form = CreateCandidatePostForm(request.POST or … -
Add specific date as default datetime to DateTimeField in Django
I have a model which already has multiple records. I now need to add a DateTimeField while giving a specific date as default for all the existing records of the model in my model, I'm trying to do: import datetime class some_model: **some fields here** setup_date = models.DateTimeField(default = datetime.datetime(2020,1,1)) on running makemigrations and migrate I do not get any error but the field does not get added to the database -
How can I visit a different url profile after the login in Django
My question is: How can I visit a different user url in Django after the login (ex. I'm 127.0.0.1:8000/profile/X/ and I would like to visit 127.0.01:8000/profile/Y/). Thank You in advance. -
Send Dataframe as CSV with Serializer.data in Django Rest Framework and handle it in React to download
In my django app I am creating a report in the backend using pandas in an APIView but I am not quite sure how to send this data along with serializer.data in the response Views.py class AllotmentReport(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): if request.GET['cname']: cname = request.GET['cname'] client = Client.objects.get(pk=cname).user items = Allotment.objects.filter(sales_order__owner=client).order_by('-id') else: items = Allotment.objects.all().order_by('-id') ... # pandas function on queryset df[q] = df[q].multiply(df["alloted_quantity"], axis="index") response = HttpResponse(content_type='csv') response['Content-Disposition'] = 'attachment; filename=export.csv' df.to_csv(path_or_buf=response) return Response(serializer.data, status=status.HTTP_201_CREATED) response = HttpResponse(content_type='csv') is one way that I found but it'd clash with Response, wouldn't it? Also how to handle this data in ReactJs i.e. frontend so that it can be downloaded as a CSV file -
Get a queryset from another queryset via OneToOne relation
I have two models as class modelA(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) and class modelB(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField() I have created a query as: query_set = modelB.objects.filter(age__gte=20) Now how can I get a queryset of modelA from query_set -
elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition
I have tried to create a sample django project and integrate elasticsearch with it .... I have go through the documentation : https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html#install-and-configure I have tried with this documentation Created a project and and an app After that install django-elastic-search dsl using pip install django-elasticsearch-dsl After that I have added the following lines in settings.py ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } Then I have created a model models.py class Car(models.Model): name = models.CharField(max_length=200) color = models.CharField(max_length=200) description = models.TextField() type = models.IntegerField(choices=[ (1, "Sedan"), (2, "Truck"), (4, "SUV"), ]) After that I have created a documents.py from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Car @registry.register_document class CarDocument(Document): class Index: # Name of the Elasticsearch index name = 'cars' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Car # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'name', 'color', 'description', 'type', ] # Ignore auto updating of Elasticsearch when a model is saved # or deleted: # ignore_signals = True # Don't perform an index refresh after every update (overrides global … -
Count number of filtered data is not working in my query
I want to count the filtered data and show it via Alert, but in my code count is not working. I also filter the date One day ahead the current date. How to work this? def repairList(request): def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) dl1 = Repair.objects.filter(Deadline__date = datetime.datetime.today() + timedelta(days=1)).annotate(Count("id")) print(dl1) return render(request,'repair/repair_list.html',{'Title':'Repair List', 'dl1':dl1}) print output <QuerySet [<Repair: VRR2020-000001>]> -
redis.exceptions.ResponseError: wrong number of arguments for 'set' command
I am trying to use celery with Django and followed the steps in the docs. But when I try to execute "celery -A proj worker -l info". I'm getting this error: Any idea on how to resolve this issue? -
TypeError at /post/new/Dark/ Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x0422D630>
i was trying to pass the movies name as default dynamically as pre the selected movie but get this error it should auto fill the name column by default from the urls passed name viwes.kwargs.name get to the template but can't set the field in there models.py def get_previous(): return Post.objects.filter(name=Movies.name) class Movies(models.Model): name = models.CharField(max_length=100,default=get_previous) slug = models.SlugField(max_length=100,blank=True,null=True) producer = models.CharField(max_length=100) director = models.CharField(max_length=100) date_released = models.DateTimeField(default=timezone.now) image = models.ImageField(default='default.jpg', upload_to='profile_pics') class Meta: verbose_name_plural = "Movies" def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.ForeignKey(Movies, on_delete=models.CASCADE,default=get_previous) def __str__(self): return self.title # return reverse('post-detail' , kwargs={'pk':self.pk}) def get_absolute_url(self): return reverse('blog-home') views.py class MoviesListView(ListView): model = Movies template_name = 'blog/home_movies.html' ordering = ['-date_released'] context_object_name = 'movies' paginate_by = 10 class MoviesDetailListView(ListView): model = Post template_name = 'blog/post_list.html' context_object_name = 'posts' paginate_by = 10 def get_queryset(self): user = get_object_or_404(Movies, name=self.kwargs.get('name')) return Post.objects.filter(name=user).order_by('-date_posted') class PostListView(ListView): model = Post template_name = 'blog/home_movies.html' # app/model_viewtype.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 class UserPostListView(ListView): model = Post template_name = 'blog/user_post.html' # app/model_viewtype.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class … -
Django model choice in seprate constant file
According to django docs the best way of handling choice fields in models is do like this: class Book(models.Model): AVAILABLE = 'available' BORROWED = 'borrowed' ARCHIVED = 'archived' STATUS = [ (AVAILABLE, 'Available to borrow'), (BORROWED, 'Borrowed by someone'), (ARCHIVED, 'Archived - not available anymore'), ] # […] status = models.CharField( max_length=32, choices=STATUS, default=AVAILABLE, ) However, my app grew a lot and model inter-connectivity between different app extended. In some cases I need to import the model class just to use the constant values eg: # some other file from book.models import Book def do_stuff_if_borrowed(book): if (book.status == Book.BORROWED): # do stuff pass I'd like to avoid importing models in other file as much as possible because it causes a lot of circular import issues and overall I feel it is not the cleanest way. I checked quickly and didn't find anybody presenting a solution on how to externalize these model constants like: book/constants.py AVAILABLE = 'available' BORROWED = 'borrowed' ARCHIVED = 'archived' STATUS = [ (AVAILABLE, 'Available to borrow'), (BORROWED, 'Borrowed by someone'), (ARCHIVED, 'Archived - not available anymore'), ] book/models.py from .constants import STATUS, AVAILABLE class Book(models.Model): status = models.CharField( max_length=32, choices=STATUS, default=AVAILABLE, ) and then if I … -
How to get element from json response in python
In python i am getting response like : {'destination_addresses': ['402, I Park, Plot No. 15], 'origin_addresses': [Sector 19, Haryana 122008, India'], 'rows': [{'elements': [{'distance': {'text': '1.7 km', 'value': 1672}, 'duration': {'text': '6 mins', 'value': 342}, 'duration_in_traffic': {'text': '6 mins', 'value': 334}, 'status': 'OK'}]}], 'status': 'OK'} I want to get value inside distance how can i get this value can anyone please help me related this ?? -
mutiple pagination ajax in django-el-pagination is not working
I am using multiple pagination in home template and showing list of pages but when i click on page 2 link it refreshes the page with ?page=2 and I just want to refresh the items not the whole page with ajax. #views.py class HomePage(TemplateView): model = Video template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ongoing = Video.objects.filter(status=0) context['videos'] = Video.objects.all() context['ongoing'] = ongoing context['posts'] = Post.objects.filter(status=1).order_by('-created_on') return context @page_templates({ 'video/index.html': None, 'video/index2.html': 'other_entries_page', }) def entry_index( request, template='index.html', extra_context=None): context = { 'videos': Video.objects.all(), 'ongoing': Video.objects.filter(status=0), } if extra_context is not None: context.update(extra_context) return render_to_response( template, context, context_instance=RequestContext(request)) home .html {% block js %} {{ block.super }} <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="{{ STATIC_URL }}el-pagination/js/el-pagination.js"></script> <script> $.endlessPaginate({ onClick: function() { console.log('Label:', $(this).text()); } }); </script> {% endblock %} In console I am getting error Loading failed for the <script> with source “http://127.0.0.1:8000/el-pagination/js/el-pagination.js”. Uncaught TypeError: $.endlessPaginate is not a function <anonymous> http://127.0.0.1:8000/?page=3:421 -
DJANGO: Allow white spaces on username? regex not working?
I am using django.contrib.auth.models import User to create a user (not extending user) and I want to enable whitespaces on usernames. I've tried the following: from django.contrib.auth.validators import ASCIIUsernameValidator class MyValidator(ASCIIUsernameValidator): regex = r'^[\w.@+-\s]+$' class MyUser(User): username_validator = MyValidator class Meta: proxy = True # If no new field is added. # Create your models here. class Person(models.Model): # Venue Name name = models.CharField(max_length=30, blank=False) user = models.OneToOneField(User, on_delete=models.CASCADE) ISSUE: It's not accepting white spaces. Throw form error: "Enter a valid username. This value may contain only English letters, numbers, and @/./+/-/_ characters." ideas? Django=1.11.29 -
Asset file referenced from model instances, how to restrict access to the URL
How can I serve asset files each from a cacheable URL, and also check access permission on the corresponding Django model instance before allowing a request to that URL? I have a Django application where model instances often have corresponding “asset” files, for example an image for an icon or a photo of the product. These assets should be served from a URL that is predictable and cacheable. Some of these assets are public and can be viewed without special authorisation. Others are not, and the URL should return an HTTP 401 “Unauthorized” response. The distinction is determined by the Django app view permissions for the corresponding model. It seems neither the Django “staticfiles” app nor the “ImageField” processing allows for this in a way I can see. What should I be using to connect access to an asset file URL to Django model authorisation and permissions? -
Django Detailed View: Retrieving data from another model in a detailed view - preferably with an associated foregin key
I am trying to show a list of associated "cliqueclasses" to a given "Item", but am just not able to get the template for the loop right. I'd also like to take this one step further and attach only the classes associated to the item (based on the foreign key) I haven't had any luck so far! Models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def save(self, *args, **kwargs): ... def __str__(self): return self.title ... class CliqueClass(models.Model): title = models.CharField(max_length=100) start_date = models.DateTimeField(auto_now_add=True) end_date = models.DateTimeField(auto_now_add=True) item = models.ForeignKey(Item, related_name='items', on_delete=models.CASCADE) description = models.TextField() plan = models.TextField() slug = models.SlugField() image = models.ImageField() def save(self, *args, **kwargs): ... def __str__(self): ... My Views.py class ItemDetailView(DetailView): model = Item template_name = "clique.html" # queryset = CliqueClass.objects.filter(title=Item.title) def get_context_data(self, **kwargs): """ This has been overridden to add `cliqueclass` to the template context, now you can use {{ cliqueclass }} within the template """ context = super().get_context_data(**kwargs) context['cliqueclass'] = CliqueClass.objects.all() return context My URL's.py path('clique/<slug>/', ItemDetailView.as_view(), name='clique'), My clique.html template: {% for class in object.cliqueclass_set.all %} <!--Look through all cliques classes--> … -
NGINX configuration for Django static files and Vue.js statics directory
I have an NGINX configuration for a containerized Django application that does three things: routes traffic to a container running daphne (on /api/, /admin/ and /ws/ routes) serves Django static files serves static files for a Vue.js application that uses Quasar My Vue.js application includes a few small images that should be served on /statics/ (with an s), and my Django static files are served on /static/. I can either have the /statics/ images from Vue.js working, or the /static/ files from Django working, but no both. Here's the configuration that makes Django static files work but Vue.js /statics/ files fail to load: # static files location /static { autoindex on; alias /usr/src/app/assets/static; } If I change the above to location /static/ {, then the Vue.js statics images will work but the Django static files will fail to load. Here's my full NGINX configuration file: user nginx; worker_processes 1; events { worker_connections 1024; } http { include /etc/nginx/mime.types; client_max_body_size 100m; upstream backend { server backend:9000; } server { listen 80; charset utf-8; root /dist/; index index.html; # frontend location / { try_files $uri $uri/ @rewrites; } location @rewrites { rewrite ^(.+)$ /index.html last; } # static files location /static { … -
After fetching data from DRF ListAPIView, how do I get it into a form needed to perform a map() method on it?
I am serializing all instances of my model Recipe. The Django API view looks like this (ignore the random recipes): [ { "id": 31, "title": "marsh", "cooktime": "5", "ingredients": "marshmellow\r\nonion", "directions": "make the onion\r\neat the marsh\r\nenjoy", "created_date": "08/16/2020 20:56:09", "published_date": null, "picture": null, "author": 3 }, { "id": 33, "title": "mac", "cooktime": "1", "ingredients": "mac\r\ncheese", "directions": "make cheddar\r\nadd mac and cheddar\r\nyes yes", "created_date": "08/16/2020 20:56:49", "published_date": null, "picture": null, "author": 2 }, { "id": 34, "title": "onion", "cooktime": "20", "ingredients": "onion\r\ncheddar\r\nmozz", "directions": "add onion to the cheddar and mozz\r\nadd onion some water and eat", "created_date": "08/16/2020 20:57:06", "published_date": null, "picture": null, "author": 2 }, ] In my actions for react-redux, I am getting the data with axios.get(url): export const getAllRecipes = () => async dispatch => { const res = await axios.get('http://127.0.0.1:8000/api/recipe/'); return( dispatch({ type: GET_ALL_RECIPES, payload: res.data }) ) } The payload from the function above is put into the store as 'recipes' and added to the below component's props with mapStateToProps Within one of my component classes, I am trying to create a function that will render information from each recipe by calling map() on the data from the API: class ListRecipes extends Component { componentDidMount() { this.props.getAllRecipes(); …