Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError at / The 'photo' attribute has no file associated with it
THE PROBLEM : I want to upload the images of my product file onto server. But when i am passing the file URL which is <{{product.photo.url}}>in my html file it is displaying value error: photo attribute has no files associated with it. My python and html file code below: product.py file: from django.db import models from django.db.models import ImageField from .category import Category class Product(models.Model): name = models.CharField(max_length=500) description = models.CharField(max_length=200, blank=True, null=True) photo = models.ImageField(upload_to='uploads/product/', blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) manufacturer = models.CharField(max_length=300, blank=True) price = models.IntegerField(default=0) @staticmethod def get_all_products(): return Product.objects.all() In the above code for Imagefield i have passed the 'photo' variable but then too the server is displaying error. urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Index.html code: <body> <div.<div class="container-fluid"> <div class="row mx-auto"> {% for product in products %} <div class="card mx-auto mb-3 mt-3" style="width: 18rem;"> <img src="{{product.photo.url}}" class="card-img-top" alt="..."> <div class="card-body"> <p class="card-title"><b>{{product.name}}</b></p> <p class="card-text"><b>{{product.price}}</b> <a href="#" class="btn btn-light border btn-md">Add To Cart</a> </div> </div> {% endfor %} </div> </div> The confusing thing is when i am passing the code {{product.image.url}} … -
Django Geos MultiPolygon contains circle
In Django, using Geos, I want to check if a circle intersects with a Multipolygon. My PointOfInterest model contains an areas MultiPolygonField, and I have tried: poi.areas.contains(Point(longitude, latitude, srid=4326)) Works fine, but we query only a point in the area poi.areas.contains(Point(longitude, latitude, srid=4326).buffer(radius)) No matching even if the circle is in the area poi.areas.buffer(radius).contains(Point(longitude, latitude, srid=4326)) Matches with all points even if with radius, they are not on the area. Do you have any idea on how to correctly find if an area (of the poi) intersects with a circle (point with radius)? -
Django Hidden cached duplicates entries, .filter() return 2 objects when .get() return one
I'm working on a quizz system , it's dev time so threre is a lot of changes on models and database imports and I have a strange problem for some time with duplicates entries. For example I've got two answers to a question for a member except of One. .get() returns one entry but .filter() returns 2 entries, I can iterate throught it, len() and count() are not equals, so it maybe a cache problem, here are some details. class Member(models.Model): name.. class MyExam(models.Model): name... class Question(models.Model): name... class Answer(models.Model): name... question = models.ForeignKey(Question,related_name="question_answers",...) class Meta: #UniqueConstraint(fields=['member_id', 'question_id', 'my_exam_id'], name='uniqu...') # get answer = Answer.objects.get(id=1) # returns one object without errors # filter answers = Answer.objects.filter(id=1) returns 2 objects answers.count() # returns 1 len(answers) # returns 2 answers.count() # returns 2 # filter distinct answers_distinct = Answer.objects.filter(id=1).distinct() # returns 2 object # filter distinct id answers_distinct_id = Answer.objects.filter(id=1).order_by('id').distinct('id') # returns 1 object It seems that count is working but len and queries are not, like if entries are duplicates in cache only, not in database. SELECT * FROM Answer WHERE id = 10; # return 1 line; SELECT * FROM Answer WHERE id IN (10); # return 1 line; I … -
Align two elements left y right in td with xhtml2pdf
How can I align two elements within a td in xhtml2pdf? I want to separate the symbol from the amount. enter image description here I tried the following but it doesn't work. Align two spans inside a td - One left and one right -
How to re-send changed data in django?
I made a POST method to send data from form, recive it with views.py . Now i want to do some changes(ex. calculate variance) on that data and then send it again to display it on my page. I tried using JsonResponse in django and $getJson in javascript but it crashes. I would really appreciate some help. views.py def valid(request): if request.is_ajax(): request_data = request.POST.getlist("invest")[0] print(request_data) return JsonResponse(request_data, safe=False) script.js function ajaxdata(){ let invest = document.getElementById('investment').value; $.ajax({ method:'POST', url:'/valid/', data: { 'invest': invest, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function (data){ alert("works"); }, error: function(data){ alert("doesn't work") } }); }; -
NoReverseMatch on Heroku Live Server
So I just launched my Django web app using Heroku. On the live server, when I try to view my cart or add a product to my cart...I get this error: Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<product_id>[0-9]+)/$'] However, I am able to successfully view and add to my cart on my local host. I will post my code below for reference. cart/templates/detail.html <form action="{% url "cart:cart_add" product.id %}" method="post" style="align-self: center"> {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.override }} <input class="btn btn-elegant btn-sm" type="submit" value="Update" style="margin-top: 20px"> {% csrf_token %} </form> cart/cart.py: class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): """ Count all items in the cart. """ … -
for this function based view i want class based view
and not able to filter with ( type=categ ), so used condition urls.py path('post/<str:categ>', category_list, name='category'), views.py def category_list(request, categ): context = {} if categ == 'first' or categ == 'First': context['category'] = Article.objects.filter(type="1") elif categ == 'second' or categ == 'Second': context['category'] = Article.objects.filter(type="2") elif categ == 'third' or categ == 'Third': context['category'] = Article.objects.filter(type="3") return render(request, 'category.html', context) Choices in model field in model type = models.CharField(choices=my_choice, max_length=10, default=False) these are choices my_choice= ("1", "first"), ("2", "second"), ("3", "three"), ("4", "four"), ("5", "five"), ("6", "six"), -
Dynamic asset database design - Postgres vs MongoDB, using Django
I'm currently designing a dynamic asset management system. Users can create their own Asset using a form builder. Currently, once the form is built I create a new table called "Asset_{name}". This works quite well but the issue I see is, over time, there will be quite a lot of tables called "Asset_...". My knowledge of database design is quite short, so the question is: should I continue on this path or will switching to a NoSQL solution (such as MongoDB) be more beneficial, and if so, why? -
How do I use Django subqueries?
How do I use this subquery in Django ORM? select id, name, price from book where price > (select avg(price) from book); I tried this and got an error. Book.objects.filter(price__gt=Subquery(Book.objects.aggregate(Avg('price')))).values('id', 'name', 'price') AttributeError: 'dict' object has no attribute 'query' -
What are some basic and advanced django webapp deployment options and costs?
I started building my first web app with the Django framework and it's going to be a simple portfolio/blog website. I went through some resources online and I am still not sure what hosting to choose. If someone who's done this before could list some good deployment options and perhaps a short description, I would really appreciate the help as it's my first time tackling this. Thanks in advance! -
Django and Angular routing without whole page refresh
In my application Backend is Django Frontend is Angular Both front and backend code is reside in same project. Home page(index.html) view rendered by using Django view method. http://appurl/home/ @ensure_csrf_cookie def home(request): return render_to_response( 'index2.html', context_instance=RequestContext(request) ) url.py urlpatterns = patterns('' url(r'^home', home), ) Once home page is loaded, user can access login page using below url http://appurl/login/ Howerver, this throw no matching url found on django side. If I add matching url like below urlpatterns = patterns('' url(r'^home', home), url(r'^login', home), ) Login page loads in browser. But this makes whole page to render. Which is against the concept of single page. Any idea how can I achieve single page concept without re-loading entire view in browser whenever new url or router changes. Thanks in adavance -
Django permission's specific to templateview
How to create multiple permission classes that would restrict user from accessing a template view ( that doesnt use any model). For example: I have 4 user categories - ( admin, management, principal, teacher). I have a Admin dashboard template view which should be restricted to user type=Admin. I would like to be able to write multiple permission classes, which I can then use in combination in any view. Following code generates 403 error: class AdministratorPermission(AccessMixin): def has_permission(self): return True class GeneralPerm1(AccessMixin): def has_permission(self): return True class DashboardView(PermissionRequiredMixin, LoginRequiredMixin, TemplateView): template_name = 'administrator/dashboard.html' permission_required = (AdministratorPermission,GeneralPerm1) Is there a way to do something like DRF permissions. Thanks -
Django SendGrid how to pass unique_args in EmailMultiAlternatives mail object
SendGrid provides the ability to pass unique_args with email so that to identify the email in the Event webhook. But the problem is I am not able to figure out how to send these unique_args with the email in Django. This is how I am currently attempting to do it: from django.core.mail import EmailMultiAlternatives header ={ "unique_args": { "customerAccountNumber": "55555", "activationAttempt": "1", "New Argument 1": "New Value 1", "New Argument 2": "New Value 2", "New Argument 3": "New Value 3", "New Argument 4": "New Value 4" } } subject, from_email, to = 'hello', 'EXAMPLE@FROM.com', 'EXAMPLE@TO.NET' text_content = 'This is an important message.' msg = EmailMultiAlternatives( subject, text_content, from_email, [to,], headers=header, ) msg.send() -
Querying many to many field in django yields an empty query set
Querying through the attachments linked to my post yields an empty queryset and i'm not totally sure why. Its probably something stupid but through the admin I can view all the attachments (files) linked to a post. Not sure how the admin is querying or whether I am querying wrong documentation on many to many fields: https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/ Models.py class Attachment(models.Model): upload = models.FileField( default='attachments/dummy.pdf', upload_to='attachments') class Post(models.Model): author = models.ForeignKey( CustomUser, on_delete=models.CASCADE) ... some other fields, ... files = models.ManyToManyField(Attachment, blank=True) Post links to Attachment through a manytomany field Views.py def UploadView(request): if request.method == 'POST': post_form = PostForm(request.POST) upload_form = UploadForm(request.POST, request.FILES) files = request.FILES.getlist('upload') if post_form.is_valid() and upload_form.is_valid(): post_form.instance.author = request.user p = post_form.save() for f in files: upload = Attachment(upload=f) #create an attachment object for each file done = upload.save() #save it p.files.add(done) #add it to the post object (saved before) return redirect('user-dashboard') ... Gets all the files from UploadForm, creates an attachment object and adds it to the post Pic of admin: pic of admin Testing it out in the shell: >>> from uploadlogic.models import Post, Attachment >>> p = Post.objects.all().last() >>> p.files >>> p.files.all() <QuerySet []> >>> f = Attachment.objects.all() >>> for i in f: … -
Python consuming API (Printful)
I am struggling to find a way to call on JSON generating from the following code. How for example, Can I call a list of "name" available on the JSON? Ps: don't worry about the Printful secret key; this is a test account. import json import requests import base64 key = 'xk7ov0my-t9vm-70z6:y491-2uyygexkkq6r' key = base64.b64encode(bytes(key, 'utf-8')) keyDecoded = key.decode('ascii') header = {'Authorization': 'Basic ' + keyDecoded} r = requests.get('https://api.printful.com/sync/products', headers=header) # packages_json = r.json() test = r.json() print(json.dumps(test, indent=4)) # print(test["name"]) -
How can I use the jquery datepicker with django admin simplelist filter
How can I use Date Picker with django-filter? does it with django-filters but I use SimpleListFilter. I don't know how to incoorporate jquery that well yet. I want to enable the user to select a date in the filterscreen to the right with a calendar widget, which is then checked whether this date is between a given time interval of start date and end date. From what I have found is that the jquery datepicker is a simple solution but you need to be able to incoorporate this. I don't know where I put this code in. I don't use any forms. Or I never used them myself. Not even called them for something. So I wasn't able to incorporate the widget neither. I wouldn't want to use form if that is possible. I know that you can put your static files in the static folder, do collectstatic and then call the .js - File with Class Media: js = ('myapp/static/js/myfile.js',) One thing I couldn't find out was how to read out/write into the date from the DateField. I guessed mydatefield.default() as the shell gave me. But I neither know how to set a custom date with the shell. Any … -
Get all elements from each Max groups in django ORM
I'm trying to group by my django query by line_nm and get the elements of the Max values from the full list in my models.py I tried this solution: dropWorst1 = dropToday.values('line_nm').annotate(worst1=Max('err_ppm')).order_by('line_nm') But it only returns the fields: line_nm, and the new value: worst1 How can I return the full fields from my database table? I'm using Mysql and I tried this other solution: dropWorst1 = dropToday.order_by('-err_ppm','line_nm').distinct('line_nm') However the occurred the follow error: DISTINCT ON fields is not supported by this database backend It because the mysql only allows .distinct() How can I get the other columns from my database? class SmdDropRateCe(models.Model): sumr_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) shift_code = models.CharField(max_length=10, blank=True, null=True) model_code = models.CharField(max_length=30, blank=True, null=True) equip_id = models.CharField(max_length=30, blank=True, null=True) mat_code = models.CharField(max_length=30, blank=True, null=True) reel_no = models.CharField(max_length=10, blank=True, null=True) err_num = models.IntegerField(blank=True, null=True) pckp_num = models.IntegerField(blank=True, null=True) plac_num = models.IntegerField(blank=True, null=True) err_ppm = models.FloatField(blank=True, null=True) Tks in advance -
Django ORM: how do I apply a function over an aggregate result?
I want to do SELECT [field1], ST_Area(ST_Union(geometry), True) FROM table [group by field1] Or, written in another words, how do I apply a function over an aggregate result? ST_Union is an aggregate. "field1" is an optional groupBy field; Also, ST_Area with 2 arguments seem not to be available on django gis helpers, so it must probably be written using Func. Also, I want to be able to also aggregate by everything (not provide a groupBy) but django seems to add a group by id if I don't provide any .values() to the queryset. This seems very confusing. I can't get my head around annotates and aggregates. Thank you! -
How to retrieve the values from a post request function django views. DRF
I have a function that makes a queryset when data from my frontend is posted. This viewset is using a serializer of combined models. On my index page on the fronted I have a treeview filter and this view loads the query to a config page. I need to access the event id's after this query is made to be passed to a separate task on the backend for polling. However I cannot access the data in this function. How would I get retrieve this query and filter on the data? right now I can't print the queryset to see its structure. class CombinedViewSet(mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = [IsMeOrReadOnly] queryset = Runner.objects.all() serializer_class = CombinedSerializer @action(detail=False, methods=['POST','GET]) def loaditem(self, request): keys = request.data['keys'] queryset = [] for xx in keys: if xx['time_key'] is None: if xx['event_key'] is None: queryset.extend(Runner.objects.filter(event__sport_id=xx['sport_key'])) else: queryset.extend(Runner.objects.filter(event__event_id=xx['event_key'])) else: date_str = xx['time_key'] datetime_obj = datetime.datetime.strptime(date_str, '%d-%m-%y') queryset.extend(Runner.objects.filter(event__start_time__date=datetime_obj, event__sport_id=xx['sport_key'])) serializer_class = CombinedSerializer(queryset, many=True) return Response(serializer_class.data) -
How to display brand name within its category? (DJANGO)
I have a model calss which has brand ...brand class also have foreignkey with category. How to diaplay brand namw according to selected category in forms class Postads(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE) ad_title = models.CharField(max_length=255) ad_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE) ad_brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) ad_model = models.CharField(max_length=255, null=True)` class Brand(models.Model): name = models.CharField(max_length =255) sub_category = models.ForeignKey(Subcategory,on_delete=models.CASCADE) slug = models.SlugField(max_length=255,null=True,blank=True) my views.py def createPostAds(request,title): global form choosecateg = get_object_or_404(Subcategory,sub_title=title) if request.method == 'POST': form = PostAdsForm(request.POST) if form.is_valid(): instance = form.save(commit=False) user = request.POST.get('owner') owner = User.objects.get(id = user) instance.ad_title = request.POST.get('ad_title') category_id = request.POST.get('ad_category') category = Subcategory.objects.get(id = category_id) instance.ad_category = category brand = Brand.objects.get_subcategory() print(brand) brand = request.POST.get('ad_brand') brand = Brand.objects.get(id = brand) I have pass category title in url. i want to display brand name within that category title name -
How to Slugify the Category Model in Django?
I'm new to django and currently writting my code in django to create my web project. I want to slugify the category url so i dont have to use the 'int:pk' again to access my post based on category. Here's my code model.py from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField from django.urls import reverse from django.utils.text import slugify class Category(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(unique=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name def get_absolute_url(self): return reverse('post_by_category', args=[self.name]) def save(self, *args, **kwargs): self.slug = slugify(self.name, allow_unicode=True) return super(Category, self).save(*args, **kwargs) class Post(models.Model): post_title = models.CharField(max_length=50) post_img = models.ImageField(upload_to='postImage/') post_content = RichTextField(blank= True, null = True) category = models.ForeignKey(Category , on_delete=models.CASCADE) post_date = models.DateTimeField(auto_now_add= False,auto_now= False, blank = True) post_author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.post_title, allow_unicode=True) return super(Post, self).save(*args, **kwargs) class Meta: ordering = ["-post_date"] def __str__(self): return f'{self.post_title}' Views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView from .models import Post, Category from django.db.models import Q class homeView(ListView): model = Post template_name = 'webpost/home.html' context_object_name = "blog_posts" class postView(DetailView): model = Post template_name = 'webpost/detailPost.html' class SearchView(ListView): model = Post template_name = … -
Django Models Unit Tests: Help for a newbie
Right, this is kind of the last place i would like to have asked due to the question being very vague, but I'm at a loss. Basically, I'm trying to learn how to code and I'm currently working with Django to help me get to grips with the back end of stuff. I keep being reminded of the importance of unit testing so I want to include them in my dummy project that I'm working on so I can begin to understand them early on in my programming journey... only... they seem easy enough on the surface, but are clearly more complicated to a beginner than i gave them credit for. I'm not entirely sure where / if I'm going wrong here, so feel free to poke me and make fun but try point me in the right direction, or to some beginner friendly resources (scoured the internet and there isn't a massive amount of info). My project is a dummy GUI related to policing (hoping to use it in my portfolio in future) Here's the model class I want help with testing. There are others but I want to do those by myself once I know more: class Warrant(models.Model): … -
Continuous Integration django applications best way
I am working on CI using gitlab and I am using something like this stages: - build - test build: stage: build script: - virtualenv env - source env/bin/activate - pip3 install -r requirements.txt - python3 manage.py check test: stage: test script: - virtualenv env - source env/bin/activate - pip3 install -r requirements.txt - python3 manage.py test Is this a good way to do ? and How It will access my env file as I dont want to commit that file . and 3rd thing should I provide DB configurations in it ? or it will make by it self ? -
django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'localhost' (10061)")
In Live server My project is running with MYSQL database but when I am working in local server by using postgreSQL database then I am getting this error. Can anybody help me to guide how to solve this issue. Thanks in Advance (venv) D:\bluehorse\goldloan-backend>python manage.py runserver Watching for file changes with StatReloader Performing system checks... .... .... .... return Database.connect(**conn_params) File "D:\bluehorse\venv\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "D:\bluehorse\venv\lib\site-packages\MySQLdb\connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'localhost' (10061)") -
I want to create a favourite view for the favouriting the album can you help me create it
So i want to favourite and unfavourite an album directly from the home page using the button please help me out models.py class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre =models.CharField(max_length=100) album_logo_link=models.CharField(max_length=1000) is_favorite_album = models.BooleanField(default=False) #is_favorite1 = models.BooleanField(default=False) def __str__ (self): return self.album_title+'-'+self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title= models.CharField(max_length=250) is_favorite = models.BooleanField(default=False) def __str__ (self): return self.song_title views.py def favSong(request, album_id): #code Also help in creating what should be there in the html file index.html {% extends "fpage/base.html" %} {% block content %} <div class="container pt-5"> <div class="row"> <ul class="d-flex w-100 justify-content-between" style="list-style-type: none"> {% for album in all_albums %} <li> <div class="col"> <img src="{{album.album_logo_link}}" height="200" width="150" /> <h2>{{ album.album_title }}</h2> <a href="{% url 'music:detail' album.id %}" class="btn btn-info" role="button">Details</a> <a href="" class="btn btn-info" role="button">Favourite</a> <a href="{%url 'fpage:album-delete' album.id %}" class="btn btn-info" role="button">Delete</a> <p></p> </div> </li> {% endfor %} </ul> </div> </div> <!-- Footer --> {% endblock %} urls.py path('fav-album/<str:album_id>/', views.favAlbum , name='fav-album')