Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Attaching the logged-in User to object after object creation
I am trying to have a logged in User fill out a form to create a Group. On Group creation, I need the User to automatically be added to the Group. For this problem, we are working with two models - User and Group. User is the default model provided by Django. Group is defined like so: class Group(models.Model): name = models.CharField(max_length=255, unique=True) admins = models.ManyToManyField(User, default=1, related_name='user_username') all_users = models.ManyToManyField(User, default=1) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') def get_admins(self): return ", ".join([u.username for u in self.admins.all()]) def add_admin(self, user): self.admins.add(user) def get_all_users(self): return ", ".join([u.username for u in self.all_users.all()]) def add_user(self, user): self.all_users.add(user) self.save() def is_admin(self, user): if user in self.admins.all(): return True else: return False And the view I'm trying to refactor is: @login_required def user_generated_group(request): if request.method == 'POST': form = GroupForm(request.POST) user = request.user if form.is_valid(): group = Group.objects.create(name=form.cleaned_data['name']) group.add_admin(user) group.add_user(user) group.save() return HttpResponseRedirect(reverse('home')) else: form = GroupForm() context = { 'form': form, 'type': 'group', 'sidebar': Sidebar(request), } return render(request, 'form.html', context) The goal is to utilize Django's built-in CreateView. The refactored view so far looks like: class CreateGroup(LoginRequiredMixin, CreateView): model = Group form_class = GroupForm template_name = 'form.html' I have yet to implement … -
Creating a python package with a Django app as a CLI
I have a test Django app with a command. I can run that command the normal way: python manage.py mycommand I'm willing to create a Python package that will expose mycommand as a normal command that can be ran from the terminal. The structure of my project looks like this: ├── codedeploy/ │ ├── __init__.py │ ├── cloud/ │ ├── entrypoint.py │ ├── examples/ │ ├── main/ │ ├── manage.py │ ├── requirements.txt │ ├── scripts/ │ ├── strategies/ │ └── tools/ ├── setup.py The __init__.py is empty. The entrypoint.py looks like this: #!/usr/bin/env python3 import os def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') from django.core.management import execute_from_command_line execute_from_command_line(["manage.py", "codedeploy"]) The entry_point of my setup.py looks like this: entry_points={ "console_scripts": ["codedeploy=codedeploy.entrypoint:main"], } When I package my project and install it in a venv, and then run codedeploy, I get the following error: Traceback (most recent call last): File "/private/tmp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'codedeploy' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/private/tmp/venv/bin/codedeploy", line 10, in <module> sys.exit(main()) File "/private/tmp/venv/lib/python3.7/site-packages/codedeploy/entrypoint.py", line 14, in main execute_from_command_line(["manage.py", "codedeploy"]) File "/private/tmp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/private/tmp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/private/tmp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", … -
How to get the .env file into the remote host server
Quick question how to get the .env conf file into the server. I have three settings file in my project base, development, production. I think testing and staging is an overkill It is encouraged to put .env in .gitignore file. so it won't be included in version control. in Heroku, it is easy to set the environment variable in the settings tab. what about other hosting services without such a feature? since I push to my repository and pull from the server, How I am I suppose to get the API keys stored in the .env since it will ignore it (it's in gitignore) file? should I create in the server? or is there a way it is done? Newbie question I know. -
Django TypeError in ModelForm
I am just trying to render a ModelForm and I keep getting the following error: "TypeError: EditManifestSelect.Meta.fields cannot be a string. Did you mean to type: ('reference',)?" I did indeed try to type it as suggested above, but just continue to receive the same error. Any Ideas? FORMS.PY class EditManifestSelect(forms.ModelForm): class Meta: model = Manifests fields = ('reference') VIEWS.PY def edit_manifest(request): if request.method == "POST": form = EditManifestSelect(request.POST) if form.is_valid(): form.save() return redirect('display_orders') else: form = EditManifestSelect() return render(request, 'edit_manifest.html', {'form': form}) 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 -
Sending multiple checkbox answers within form by ajax
I am trying to send form data to my Django application using ajax. I am using this JQuery which works fine (to a point) $ (function () { $('#filtersForm :checkbox').change(function() { $.ajax({ url : "/ajax-search/", data: $("#filtersForm").serialize(), type : "GET", success : function(html) { console.log("success"); replaceJobs(html); }.bind(this), error : function(xhr,errmsg,err) { console.log("error"); }.bind(this) }); }) }) There are a number of checkboxes in the form using a forms.ModelMultipleChoiceField. My django form looks like: class FilterSearchForm(forms.Form): job_location = forms.ModelChoiceField( queryset=OfficeBase.objects.filter(name="Remote"), widget = FilterCheckboxSelectMultiple, required=False) job_type = forms.ModelMultipleChoiceField( queryset=Employment.objects.filter(active=True), widget = FilterCheckboxSelectMultiple, required=False) job_category = forms.ModelMultipleChoiceField( queryset=Category.objects.filter(active=True), widget = FilterCheckboxSelectMultiple, required=False) Which produces html like: <ul class="list-unstyled list-increase-spacing"> <span class="form-checkbox"> <li> <input id="id_job_category_0" type="checkbox" name="job_category" value="1"/> <label id="label-id_job_category_0" for="id_job_category_0"> Category 1</label> </li> </span> <span class="form-checkbox"> <li> <input id="id_job_category_1" type="checkbox" name="job_category" value="2"/> <label id="label-id_job_category_1" for="id_job_category_1"> Category 2</label> </li> </span> </ul> When multiple boxes are checked, I am only getting the last one in my view. I am getting the items usingfor key, value in self.request.GET.items(): How do I ensure I get all checked items? -
Best way to implement depending fields dynamically in Django admin
Hello I have an idea about shop on Django. I want something about class Category with name and jsonfield which storing attribute names ("size", "color") for category. And I have a model Product with fk to Category and field attributes, also json {"size":"M", "Color":"red"}. Now I have 2 questions. 1) Is it idea acceptable? 2) i have admin for Product and I want this behavior: then user select category for product, the field "attributes" automatically render the template with attribute names for this Category, something like this: {"size": "", "color":""} Thank you. -
How to substitute a variables to TextField() in the admin page at Django 1.11?
location / models.py from django.db import models class City (models.Model): name = models.CharField (max_length = 10, default = '', blank = False) class Country (models.Model): name = models.CharField (max_length = 10, default = '', blank = False) metatags / models.py from django.db import models class MetaTag (models.Model): description = models.TextField () Now suppose the admin creates the MetaTag from the admin page. He wants to write a phrase at description field, for example "Paris is not the capital of Germany". But, since there are a lot of cities and countries, need to create only one MetaTag, according to the type "{City.name} is not the capital of {Country.name}" (something similar to the Django template). Thus, only one note of MetaTag is created, and, depending on the conditions at the view, a certain city and a certain country are inserted from the database to this description (the Admin can enter any phrase and any number of variables). -
ERROR: Complete output from command python setup.py egg_info
I want to add location feature on my django project. In internet I found, first I have to install 'pip install django-google-address'. This gives an error, how to solve this? ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\Dell\AppData\Local\Temp\pip-install-g_nwddg7\django-google-address\ -
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({ …