Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to filter and display posts from categories on a page
I'm new to Django and have build a simple application that includes posts. I want to display posts that are associated with certain categories on one page. I did quite a bit of research online but can't seem to make it work. I think the problem is in my views.py I guess there's something wrong with the get_queryset function in CategoryListView. ''' models.py ''' from django.db import models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey( 'Category', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=150, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('post-category', kwargs={'pk': self.pk}) ''' views.py ''' from django.views.generic import ListView from .models import Post, Category class CategoryListView(ListView): model = Post template_name = 'posts/post_category.html' def get_queryset(self): category = get_object_or_404(Category, id=self.kwargs.get('category__name')) return Posts.objects.filter(category_name=categorie) ''' urls.py ''' from .views import CategoryListView urlpatterns = [ CategoryListView.as_view(), name='post-category') ] The code gives me a 404 and the message that no Category matches my query. -
Lazy querysets in django
This is more of an efficiency question. My django web page is working fine, in the sense that I don't get any errors, but it is very slow. That being said, I don't know where else I would ask this, other than here, so here goes: I am developing a sales dashboard. In doing so, I am accessing the same data over and over and I would like to speed things up. For example, one of my metrics is number of opportunities won. This accesses my Opportunities model, sorts out the opportunities won within the last X days and reports it. Another metric is neglected opportunities. That is, opportunities that are still reported as being worked on, but that there has been no activity on them for Y days. This metric also accesses my Opportunities model. I read here that querysets are lazy, which, if I understand this concept correctly, would mean that my actual database is accessed only at the very end. Normally this would be an ideal situation, as all of the filters are in place and the queryset only accesses a minimal amount of information. Currently, I have a separate function for each metric. So, for the … -
Query Optimization and Scaling Django GraphQL API with Graphene
I have been using Django Rest Framework and it is awesome for filtering, permissions, de/serialization, security, query optimization, scaling, micro-services etc. Then I came to know about the GraphQL with django-graphene and started to learn about this wonderful technology. All was looking good and I had decided to use that in my new projects. Then suddenly I got to know that the GraphQL is not good enough for query optimization with django-orm and scaling. I would like to know if is that true with GraphQl especially with django-graphene A short note to those who always keep blocks the questions on the the name of duplicate question or any other reason. Please don't do that. I have tried to found but got no answer on my typical question. If someone thinks this is duplicate I would say he is only doing this to increase his score on this site. Thanks if someone answers. -
How to get the name of categories insted of their Id from a ManyToMany Field?
I have two models Influencer and Categories: Class Influencer(models.Model): full_name = models.CharField('Full Name',max_length=255) username = models.CharField('Username',max_length=255,unique=True) photo = models.URLField(blank=True,max_length = 500) email_id = models.EmailField('Email Id',blank=True,max_length=500) categories = models.ManyToManyField(Category,blank=True,max_length=400) and class Category(models.Model): name = models.CharField(max_length=400) def __str__(self): return self.name Influencer has a many to many field categories. My views function is as follows which returns a JSON response: def index(request): influencers = Influencer.objects.all().order_by('followers') paginator = Paginator(influencers,16) page = request.GET.get('page') paged_listings = paginator.get_page(page) user_list = UserList.objects.all().filter(user_id = request.user.id) queryset = list(chain(paged_listings,user_list)) ser_query = serializers.serialize('json', queryset) return HttpResponse(ser_query,content_type='application/json') The response I get from the views functions is as follows: model "influencer_listings.influencer" pk 5779 fields full_name "SHIVANGI | PUNE FOODIE" username "homely_flavours" photo "https://instagram.fdel8-1.fna.fbcdn.net/vp/be30112676c82fe49c238fa53a8c1e49/5DAA860D/t51.2885-19/s150x150/36480131_205075237009354_3083993965448396800_n.jpg?_nc_ht=instagram.fdel8-1.fna.fbcdn.net" email_id "" categories 0 5 1 9 The categories in the JSON format are given as category id and not as category names. How can I return category names instead of category id? -
django no patterns in file
I am reading this book "Django for Beginners" by William S. Vincent. In chapter 2, the sample codes to produce a "Hello World!" page are as following: #pages/views.py from django.http import HttpResponse def homePageView(request): return HttpResponse('Hello, World!') #pages/urls.py from django.urls import path from .views import homePageView urlpatterns=[ path('',homePageView,name='home') ] #helloworld_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns=[ path('admin/',admin.site.urls), path('',include('pages.urls')), ] When I run python manage.py runserver, there is a message pages\\urls.py does not appear to have any patterns in it. If you see a valid pattern in the file then the issue is probably caused by a circular import. The book, however, says that I should see a webpage with "Hello, World!" text at http://127.0.0.1:8000 If someone could explain what is going on here, that would be very much appreciated. -
How can I add post favorite marking system in my app with django generic class based view?
I'm trying to let my users to mark favorite post that they can read it later. I've seen some solution using FBV, but I want to make favorite marker with CBV. How can I do it using django class based view (DetailView) ? model class Article(models.Model): ... favorite = models.ManyToManyField(get_user_model(), related_name='favorite', blank=True) def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) views class ArticleDetailView(ObjectViewMixin, DetailView): model = Article context_object_name = 'article' ... def get_context_data(self, **kwargs): ... return context def favorite_post(request, id): post = get_object_or_404(Article, id=id) if post.favorite.filter(id=request.user.id).exists(): post.favorite.remove(request.user) else: post.favorite.add(request.user) return redirect('article_detail', pk=article.pk) urls urlpatterns = [ path('<int:pk>/edit/', ArticleUpdateView.as_view(), name='article_update'), path('<int:pk>/favorite_post/', favorite_post, name='favorite_post'), ] -
Django @permission_required Decorator not Working in function-based view
I was trying to give permission a user that he can do everything except delete. He has view permission here is my function @login_required(login_url='loginPage') @permission_required('excel_data.view_exceldata', raise_exception=True) def viewExcel(request): excelInfo = ExcelData.objects.filter(deleted=0).order_by('-pk') return render(request, 'excelData.html', {'excelInfo': excelInfo}) here is my auth_permission database table view here is my auth_user_user_permissions table view the user is not an is_superuser when I try to view that page I got 403 Forbidden what is I'm doing wrong -
Perform Django model operation after a response has been sent with Rest framework
I have created a very simple setup with articles and comments, in which users can post comments to articles through an api created with the Django Rest framework. So far so good. The problem is I have several expensive operations that need to be performed when a comment is created (such as sending email notifications), but I would like for them to be performed AFTER the response has returned, so the user won't have to wait. class Comment(CommentBase): article = models.ForeignKey(Article, on_delete=models.CASCADE) def save(self, *args, **kwargs): #Expensive operations here, which should run after a response has been returned. super(Comment, self).save(*args, **kwargs) As far as I know, the rest framework won't send a response until after a model-save has been performed. How do I best run operations after the response has been returned? Can I use post-signal, or is this something I need to do with Celery? -
Gow i can delete record from db with several conditions
I have data models like: from django.db import models class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() def __str__(self): return self.first_name + ' ' + self.last_name class Course(models.Model): name = models.CharField(max_length=255) description = models.TextField() start_date = models.DateField(null=True) end_date = models.DateField(null=True) def __str__(self): return self.name class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='courses', on_delete=None) student = models.ForeignKey(Student, related_name='students', on_delete=None) completed = models.BooleanField(null=True, default=False) def __str__(self): return self.course I have some serializer like: class AssignStudentToCourseSerializer(serializers.ModelSerializer): class Meta: model = CourseParticipant fields = ('id', 'student', 'course') class UnassignedStudentFromCourseSerializer(serializers.ModelSerializer): class Meta: model = CourseParticipant fields = ('student_id', 'course_id') I have vies for it class AssignStudentToCourse(generics.CreateAPIView): serializer_class = AssignStudentToCourseSerializer class UnassignedStudentFromCourse(generics.DestroyAPIView): serializer_class = UnassignedStudentFromCourseSerializer queryset = CourseParticipant.objects.all() I have table CourseParticipant with some records | id | course_id | student_id | |:-----------|------------:|:------------:| | 1 | 2 | 2 | | 2 | 3 | 2 | | 3 | 2 | 3 | | 4 | 2 | 4 | I need delete records from this table by course_id and student_id. Now, use DestroyAPIView i can delete record by id, but it's dont right way. How i can delete record from my table by several conditions. -
How to fix "Online shop total cart price and quantity in django"
When i have only one product in the cart, the quantity and price is fine but when i add other items to the cart the total price and quantity doesn't update. I suspected that something might be wrong with the indentation and have reviewed it but it seems fine Here is a link to the git hub code or please specify if a portion of the code is needed. https://github.com/majorbangx/onlineshop I do not get any error message -
Django proxy model, admin methods for list display
class Model1(models.Model): date = models.DateField() f1 = models.ForeignKey('c1.F1', on_delete=models.PROTECT) f2 = models.ForeignKey(F2, on_delete=models.PROTECT, null=True) f3 = models.ForeignKey('c2.F3', on_delete=models.PROTECT, null=True, blank=True) objects = F1Manager() class Meta: ordering = ('-date',) class Model2(Model1): class Meta: proxy = True objects = F2Manager() class Model3(Model1): class Meta: proxy = True objects = F3Manager() Now in admin I have: @admin.register(Model2) class Model2Admin(admin.ModelAdmin): list_display = ['f1_name',] def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.annotate( f1_name=F('f1__name'), f2_name=F('f2__name'), f3_number=F('f3__filenum'), ) return qs def f1_name(self, obj): return obj.f1_name Runserver gives error The value of 'list_filter[0]' refers to 'f1_name', which does not refer to a Field. Can someone throw some light, why this error or how to go about it. Basically the error is because of proxy = True on Model2. I have tried inheritance too, but that also throws same thing. In fact initially the method f1_name was in the Model1 Admin. But because of error I change it and tried this. Thanks in Advance -
Two Different date formats for record in datetimefield - we want to have one format
In our app we use Django 1.11 and Mysql. In our production we encounter problem with date format for a couple of columns. For some record the returned format of datetime field is in form: 2018-03-03T14:48:43Z and for others 2019-06-19T14:28:46+01:00. We would like to return only one format and I think that we prefer this: 2019-06-19T14:28:46+01:00. How to easly update the older record to use the new format? -
How to use authentication with different table in django
I have created a new model and stored data in that table. If i use authenticate method, it checks the auth_user table for the authentication and not my table.Im using postgresql for backend. How to authenticate using table which i created. Im a beginner in django. -
Django special function {% %} on dynamic data coming from javaScript
I used Django-emoticons and I want to put this special function on the data coming from CreateMessage. function createMessage(data) { var author = data['author']; var msgListTag = document.createElement('li'); var imgTag = document.createElement('img'); var pTag = document.createElement('p'); pTag.textContent = data.content; imgTag.src = usrurl; if (author === username) { msgListTag.className = 'sent'; imgTag.src = usrurl; } else { msgListTag.className = 'replies'; imgTag.src =recurl; } msgListTag.appendChild(imgTag); msgListTag.appendChild(pTag); document.querySelector('#chat-log').appendChild(msgListTag); } {% load emoticons_tags %} <div class="messages"> {% emoticons %} <ul id="chat-log" > Documenting is boring but usefull :p <li class="replies"> <img src='{{rec_img}}' alt="" /> <p>When you're backed against the wall, break the god damn thing down.</p> </li> <li class="sent"> <img src='{{rec_img}}' alt="" /> <p>How the hell am I supposed to get a jury to believe you when I am not even sure that I do?! :p </p> </li> </ul > {% endemoticons %} While running, it changes the symbol to emoticons on static data but not on dynamic data. -
Listing files of media dirictory in django through URL
I just Configured my django to render media files to user as discussed in this question and it works perfectly, All my media files are rendered when I request their URL. But when I try to access URL of directory inside my media dirictory in on my server, I wish to get list of all files in that in that directory, but that's not happening in my case. Do I have to define urls and views for each directory in media, or there is specific(automatic) way to handle it in django For example, If folder structure of my media directory is as follows `media` -> `images` -> a.jpg, b.jpg, c.jpg, ... `videos` -> x.mkv, y.mkv, ... `logs` -> 154.log, 13.log So when I visit 127.0.0.1:8000/media It should display images videos logs when I visit 127.0.0.1:8000/media/images It should display a.jpg b.jpg c.jpg and so on... for all directories Note : I am running server in Debug=True mode -
How to update_index for haystack from a external script?
I am using Django Haystack with ElasticSearch backend for my search page. I am using MongoDB as my Database. Everything was working fine in my search page. PROBLEM My web-application uses an external script for changing a field in the backend database using pymongo My database has 2 fields (Files , Analysis). The third party script runs and changes the Analysis field to True or False. After the script has been run , when I search for the filename , it is showing me the updated Analysis in the results. But when I search for the Analysis Field , (say I search for True/False ) It is not listing out this currently updated Analysis, though it has been updated. For example Search : filename Result : filename True Search : True Result : No results found It is working only after I update_index WHAT I TRIED So I figured out that I have to update_index. But I don't know how to update from a third party python script. I tried running os.system("python /myapp/manage.py update_index") I get the error Unknown command: 'update_index' When I saw the management command available from the third party script , it is not listing the haystack … -
"Management data missing or tampered with" while validation of formset of form with ArrayModelFields djongo
I am using djongo for MongoDB integration with Django. I have used two ArraymodelField inside my Model, which internally use Django's formsets. I keep getting Management data is missing or tampered with error while validating my form. I have read about the error and that it exists with formsets and including management data in template file like {{ formset.management_form }} solves it. I also read about prefix usage, which I do use for the ArrayModelFields, but I cannot understand how to explicitly specify it in my views.py file. Below is my code: models.py (Source and Destination are abstract models with ip, port, database, user, password as fields) class LobDetail(models.Model): lob_name = models.CharField(max_length=64, primary_key=True) type = models.CharField(max_length=20) source = models.ArrayModelField( model_container = Source, ) destination = models.ArrayModelField( model_container = Destination, ) def __str__(self): return self.lob_name + " "+ self.type views.py (LobDetailForm is a simple form with all fields included) def add_lobdetail(request): form = LobDetailForm if request.method == 'POST': print('Hey! I AM SUBMITTED') form = LobDetailForm(request.POST) if form.is_valid(): form.save(commit = True) return index(request) else: print('Error Form Invalid') return render(request, 'lobconf/add_lobdetail.html', {'formset': form}) add_lobdetail.html <script type="text/javascript"> $(function() { $('.nestedform_one').formset({ prefix: '{{ formset.source.prefix }}', formCssClass: 'dynamic-formset1', addText: 'Add another source', deleteText: 'Remove' }); $('.nestedform_two').formset({ … -
Is it correct use for Django ModelForm
My question; i'm used ModelForm instead of forms.Form and i want to organize form in html file instead of forms.py file (i don't want to use attr tag because my form.html file is very complicated) Is this usage correct? forms.py class CommentForm(forms.ModelForm): class Meta: model=Comment fields=[ 'name', 'email', 'comment', ] html file <form class="post-comment-form" method="POST"> {% csrf_token %} {% if form.errors %} {% for error in form.non_field_errors %} {{ error }} {% endfor %} {% endif %} <div class="form-row"> <div class="form-item half blue"> <label for="id_name" class="rl-label" >Name</label> {{ form.name}} </div> <div class="form-item half blue"> <label for="id_email" class="rl-label" >Email</label> {{ form.email}} </div> </div> <div class="form-row"> <div class="form-item blue"> <label for="id_comment" class="rl-label">Comment</label> {{ form.comment }} </div> </div> <button type="submit" class="save-button">Submit</button> -
How to run the html and jquery code in django?
I run the jquery file in html and it works but whenever I run the code within django framework within {%block content%} {%endblock%} the sliding function does not work. Why and how to resolve this issue? {% extends 'testapp/base.html' %} {%block content%} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#flip").click(function(){ $("#panel").slideToggle("slow"); }); }); </script> <style> #panel { display: none; } </style> </head> <body> <div id="flip">Click to slide the panel down or up</div> <div id="panel">Hello world!</div> </body> </html> {%endblock%} -
Using HyperlinkedModelSerializer can we make some fields(ForeignKey field) without url, only id(if doesn't have detail-view)
Im using django rest framework. In serializer I used HyperlinkedModelSerializer, but there are some foreign key fields with detail-view so it can be rendered as url, but some of them don't, it gives me the following error: 'Could not resolve URL for hyperlinked relationship using view name "unit-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.'. So how to fix it? serializers.py class MaterialSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Material fields = ('id', 'url', 'name', 'location', 'category', 'unit', 'type', 'price',) views.py class MaterialViewSet(viewsets.ModelViewSet): queryset = Material.objects.all() serializer_class = MaterialSerializer models.py class Material(models.Model): name = models.CharField(max_length=200) location = models.ForeignKey(Location, null=True, on_delete=models.CASCADE) category = models.ForeignKey(Category, null=True, on_delete=models.CASCADE) unit = models.ForeignKey(Unit, null=True, on_delete=models.CASCADE) type = models.CharField(choices=TYPE_CHOICES, default='material', max_length=200) price = models.FloatField(default=0, blank=True, null=True) So in my API I want to be my foreignkey fields 'location' and 'category' with url and 'unit' field only id -
int() argument must be a string, a bytes-like object or a number, not "list" : Django save model
I am trying to save a model but am unable to because of a TypeError I am being given. I have looked at other answers with similar errors but they are different problems. now = dateTime.now() miliTime = int(str(now.hour) + str(now.minute) timeConvert = miliTime - 1200 timeString = str(timeConvert) standard_t = timeString[:1] + ":" + timeString[1:] standardTime = standard_t + " " + p time_1 = standard_time time_2 = standard_time user = StaffMember.objects.get(id = request.session['client']['id']) userPunchCard = PunchCard.objects.get(employee = StaffMember.objects.get(name = user.name)) punch = [] try: if len(userPunchCard.time.punch) < 2: punch.append(time_2) userPunchCard.time = punch userPunchCard.save() except: punch.append(time_1) userPunchCard.time = punch userPunchCard.save() The main issue is trying to save the array. The try and except is to check for a punch is present. Heres the full error Message - TypeError: int() argument must be string, a bytes-like object or a number, not a 'list'. -
All errors result in URLconf circular import
Any error in my django app results in: The included URLconf 'appname.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I realized when stepping through in pdb that any error that occurs in my app results in the URLconf error. The pdb will show the error that actually occurred, but if I continue the console will just print the URLconf error shown above. If I go and fix the error pdb showed such as the SyntaxError I resolved then everything works fine. It seems like any error I have just results in the URLconf error shown above and I am not sure how to resolve it so that I can see that actual error without going through pdb. -
Remove option from generic class view in Django
I just started learning Django this week and I'm trying to figure out how I can remove an option from a select menu being rendered in a class based view. The dropdown is for a Foreign Key field that links to my users table. The functionality here is that I do not want the current user logged into show up on that list (basically I don't want someone to be able to select themself). How can I go about doing this? View: class TransferCreateView(CreateView): model = Transfer template_name = 'points/transfer_form.html' fields = ['receiver', 'message', 'amount'] Model: class Transfer(models.Model): receiver = models.ForeignKey(User, null=False, on_delete=models.CASCADE, related_name='receiver') sender = models.ForeignKey(User, null=False, on_delete=models.CASCADE, related_name='sender') amount = models.IntegerField( validators=[ MinValueValidator(1), MaxValueValidator(1000)], null=False) message = models.CharField(max_length=100) date_sent = models.DateTimeField(default=timezone.now) Basically, I don't want the person who is the sender (which i was going to set in the code in a form_valid() function) to be an option for 'receiver' in the template when it renders. -
Default ModelForm Field (Foreign Key) From URL Parameter
I have a URL which contains a reference_id, this reference ID is getting passed to my HTML file to default the value of the ModelForm. My problem is that the field ModelForm field which I am defaulting is a Foreign Key to another model. The way that I am currently doing it, through the HTML file, the form does not submit due to the above. I'm wondering how I can set this form field to default to the parameter passed through the URL, make it read only, and still have it post to the Model. In the form posted below, it is the 'reference' field which I am attempting to default and in the HTML the tag is how I am currently doing it. Any thoughts or alternatives are more than welcome. MODELS.PY class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() description = models.CharField(max_length=1000) count = models.IntegerField() def __str__(self): return self.cases FORMS.PY class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') VIEWS.PY def add_manifest(request, reference_id): if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): form.save() return redirect('add_manifest', reference_id=reference_id) form = CreateManifestForm() manifests = Manifests.objects.all() context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return … -
not finding the path
I have a problem with my code, I've tried to make a new URL file inside the app and in the main URL file put the function include but I have an error when i run the code, here's my code the error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/index Using the URLconf defined in f_project.urls, Django tried these URL patterns, in this order: admin/ ^$ ^first_app/ The current path, index, didn't match any of these. code for f_project.urls from django.contrib import admin from django.urls import path, include from first_app import views, urls urlpatterns = [ path('admin/', admin.site.urls), path(r'^$', views.index), path(r'^first_app/', include('first_app.urls')), ] code for first_app.urls from django.urls import path from first_app import views urlpatterns = [ path(r'^$', views.index, name='index'), ] please, someone help me to solve it