Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: choice display with queryset values
I want to use get_status_display on template, from a queryset with just some fields from model. I have a model with a choices field (status). class Operation(models.Model, ModelMixin): operation_area = models.ForeignKey('operations.OperationArea', null=True) created = models.DateTimeField(auto_now=True) indication = models.NullBooleanField() observation = models.TextField(blank=True, null=True) rate = models.IntegerField(blank=True, null=True) scheduling = models.DateTimeField(blank=True, null=True) status = models.IntegerField(choices=OPERATION_TYPE) class OperationArea(models.Model, ModelMixin): campaign = models.ForeignKey('campaigns.Campaign') person = models.ForeignKey('registrations.Person') user = models.ForeignKey('authentication.User') area = models.CharField(max_length=1, choices=OPERATION_AREA) My query is: Operation.objects.filter(operation_area__user=user).values('id', 'created', 'operation_area__person__name', 'status') From this a get a dict, but get_FOO_dislpay is a instance method and don't works on a dict. I don't want to use .only() because he brings operation_area object and to get the person.name he makes another query, like this operation.operation_area.person.name. Any thoughts how to work with one query and get_FOO_display? -
error when running a website in django server by cmd
when i want to see my django file in their server....i open cmd and go to manage.py directory: C:\Users\computer house\Desktop\ahmed> and then i type : python manage.py runserver but i see this error : Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ahmed' what can i do to solve this problem and run my website in the server correctly ? -
Django python doesn't work
You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): news. Run 'python manage.py migrate' to apply them After I run this command and it gives me error python manage.py migrate Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/danazholdykhairova/Desktop/original/bootcamp/config/settings/local.py", line 5, in <module> from .base import * # noqa File enter code here"/Users/danazholdykhairova/Desktop/original/bootcamp/config/settings/base.py", line 267emphasized text REDIS_URL = f'{env("REDIS_URL", default="redis://127.0.0.1:6379")}/{0}' ^ SyntaxError: invalid syntax -
How to get nearest time from the list?
I have a class: class ScheduleEntry(models.Model): DOW_CHOICES = ( (1, _("Monday")), (2, _("Tuesday")), (3, _("Wednesday")), (4, _("Thursday")), (5, _("Friday")), (6, _("Saturday")), (7, _("Sunday")), ) starts_at = models.TimeField(verbose_name=_("Starts at")) day_of_week = models.PositiveSmallIntegerField(choices=DOW_CHOICES, verbose_name=_("Day of week")) def next_start(self): # what is here? I'd like to get nearest start at future. E.g if in starts_at stored 10:00 AM and in day_of week stored Friday and today is Friday 10:30 I want to get 10:00 AM of next Friday. How to do this? -
nested loop to display all data from models django
i need to display all data from models in django i have two list one has all rows and another has all columns , what is want to do something like {{student.username }} i am trying to use nested loop to get all data , i know this "row.{{column}} " is wrong but did not find the solutions {% for row in rows %} <tr> {% for column in columns %} <td>{{ row.{{column}} }}</td> {% endfor %} </tr> {% endfor %} can any one guide how me how to use like this manner ? -
Django: HTML modal only works for a single object rather than all objects
For some reason when trying to create a modal in django for every object in a list it only seems to work for the first one and not the rest. Each object is iterated through using the template tag for loop: {% for original in corpus.original_set.all %}. The full code is shown below. PLEASE INDICATE WHETHER YOU NEED FURTHER CODE. Aim: these objects are text files, to which the method display_text_file_orig reads the contents of the file. This content is what I want displayed in each of the modals when the button (myBtn) is clicked. <tr> <td>{{ object.corpus_name }}</td> <td> {% for original in corpus.original_set.all %} <button id="myBtn">{{ original }}</button> <div id="myModal" class="modal"> <div class="modal-content"> <div class="modal-header"> <span class="close">&times;</span> <h2>{{ original }}</h2> </div> <div class="modal-body"> <p>{{ original.display_text_file_orig }}</p> </div> <div class="modal-footer"> <h3>Type: Original documentation with predefined source.</h3> </div> </div> </div> {% endfor %} </td> </tr> models.py class Corpus(models.Model): user = models.ForeignKey(User, on_delete=CASCADE, null=True) corpus_name = models.CharField(max_length=50, unique=True) def get_absolute_url(self): return reverse('show-corpus', kwargs={'pk': self.pk}) def __str__(self): return self.corpus_name class Original(models.Model): corpus = models.ForeignKey(Corpus, on_delete=CASCADE) original_file_name = models.CharField(max_length=50) original_file = models.FileField() def display_text_file_orig(self): with open(self.original_file.path) as fp: return fp.read().replace('\n', '<br>') def __str__(self): return self.original_file_name class Suspicious(models.Model): corpus = models.ForeignKey(Corpus, on_delete=CASCADE) suspicious_file_names = … -
django.db.utils.DataError: value too long for type character varying(650)
I have a model TextField that I have recently changed it's max_length from 650 to 1500. class Comment(models.Model) ... comment_text = models.TextField(max_length=1500, blank=True, null=True) I have performed makemigrations and migrate, and there are no issues on my local server when I post a comment that is 650+ characters. However when I post a comment over 650+ characters on my remote server, it returns this error: File "/home/james/postr/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/james/postr/env/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/james/postr/env/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/james/postr/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: value too long for type character varying(650) even though I've checked the remote code has changed to max_length=1500. Any idea what the problem is? -
How to design a blogging website in django for dynamic number of post objects for each post?
I'm new to django.But I've designed a basic blog app.I want to design a tutorial website in django.So it can have dynamic number of images(screenshot of some implementation) and text body explaining those images.So each post can require different number of images and text body.How would models.py change in this case? Or how to achieve this? -
Django: adding a new row to a model that has a foreign key relationship with another
I have a django rest API with the following code: models.py: from django.db import models class Actor(models.Model): id = models.CharField(max_length = 50, primary_key = True) login = models.CharField(max_length = 50, unique = True, blank = False) avatar_url = models.CharField(max_length = 100, blank = False) def __str__(self): return self.login class Repo(models.Model): id = models.CharField(max_length = 50, primary_key=True) name = models.CharField(max_length =50, blank=False) url = models.CharField(max_length=100, blank=False, unique = True) def __str__(self): return self.name class Event(models.Model): id = models.CharField(max_length = 50, primary_key = True) type = models.CharField(max_length = 50) actor = models.ForeignKey(Actor, on_delete = models.PROTECT) repo = models.ForeignKey(Repo, on_delete=models.CASCADE) created_at = models.DateField() def __str__(self): return self.name serializers.py: from models import Actor, Repo, Event class ActorSerializer(serializers.ModelSerializer): class Meta: model = Actor fields = ('id', 'login', 'avatar_url') class RepoSerializer(serializers.ModelSerializer): class Meta: model = Repo fields = ('id', 'name', 'url') class EventSerializer(serializers.ModelSerializer): actor = ActorSerializer() repo = RepoSerializer() class Meta: model = Event fields = ('id', 'type', 'actor', 'repo', 'created_at') views.py: from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from models import Actor, Repo, Event from serializers import ActorSerializer, RepoSerializer, EventSerializer class EventView(ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer Event model has foreign key to Actor and Repo models. So, it … -
How to override make the save method of the Model working depends on a specific field changing in Django?
class MyModel(models.Model): ... status = models.IntegerField(blank=True, null=True, default=0) ... def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.status == 1: ... count + 1 ... else: pass I override the save() method in the Model, what I wanna to implement is: if the "status"(default value equals 0) changes from 0 to 1, then "count + 1" So, there are 4 conditions during saving: "status" changes from 0 to 1: count + 1 "status" changes from 1 to 0: pass "status" equals 0 not change: pass "status" equals 1 not change: pass With my implementation, everyone works well but the last one, the "count + 1" still runs when the "status" not change, from 1 to 1 (which means has not been edited) during saving. I tried self.id, self._state.adding, etc, but failed. What should I do to keep the last condition going correct? Need your help, thanks! -
Is it safe to use stored procedures over Django?
We have a production environment with MongoDB as backend. We are expecting to face nearly 300K users. It has to handle so many connections. We will have registration and login as well. We are getting options to run the queries directly as Stored procedures ie. via Javascript in server OR use Django to create REST APIs and use them. We are looking into pros and cons of both. It will be very useful if experienced developers can help us. Which will be more useful? -
How to write tests for custom Django generic view?
I didn't understand the way we should write tests for Django views. Because, my case felt different than others. I have a view, let's say MyView, inherits from CreateView of Django generic class based views. But, in the background, I mean in the form_valid function, this view tries to connect to a remote server with a Python library, then fetches data according the input of the user, then process other details and saves the object if everything is OK, if not, it returns custom errors. What should be my way to handle this kind of view so I can write a test? -
Form invalid errors not getting displayed in Django
Upon submitting the form, i have configured to display the errors of the form in another page. But all i am getting is the form with no errors. Here is my code. forms.py class leads_form(forms.Form): assigned_to = forms.ChoiceField(required=True,widget=forms.Select(attrs={'class':'form-control'})) ref = forms.CharField(max_length=50,required=False,widget=forms.TextInput(attrs={'class':'form-control'})) lead_type = forms.ChoiceField(choices=dicto.lead_type_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'})) priority = forms.ChoiceField(choices=dicto.priority_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'})) hot = forms.ChoiceField(choices=dicto.hot_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'})) source = forms.ChoiceField(choices=dicto.source_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'})) mls_lead = forms.ChoiceField(choices=dicto.true_false_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct'})) auto_imported = forms.ChoiceField(choices=dicto.true_false_dict.items(),required=False,widget=forms.Select(attrs={'class':'form-control slct'})) inquiry_date = forms.CharField(max_length=50,required=False,widget=forms.TextInput(attrs={'class':'form-control'})) lead_closed_date = forms.CharField(max_length=50,required=False,widget=forms.TextInput(attrs={'class':'form-control'})) created_by = forms.CharField(max_length=50,required=False,widget=forms.TextInput(attrs={'class':'form-control'})) property_id = forms.CharField(required=False,widget=forms.HiddenInput()) set_status = forms.ChoiceField(choices=dicto.set_status_dict.items(),required=True,widget=forms.Select(attrs={'class':'form-control slct','placeholder':'set status'})) contact=forms.IntegerField(required=True,widget=forms.HiddenInput()) def __init__(self,user,*args,**kwargs): super(leads_form,self).__init__(*args, **kwargs) self.user=user self.fields['created_by'].initial = self.user self.fields['assigned_to'].choices = [(o.id, str(o.username)) for o in CustomUser.objects.all()] and my view def add_lead(request): try: prop=Property.objects.filter(created_by=request.user.id) except Property.DoesNotExist: prop=[] if request.user.user_type != 3: form = leads_form(request.user) form1=prop_requirement_form() else: form = leads_form(request.user) form1=prop_requirement_form() form.fields['assigned_to'].choices= [(request.user.id, str(request.user.username))] if request.method == 'POST': form = leads_form(request.POST) if form.is_valid(): print("joes") else: return render(request,'contacts/errsd.html',{'form':form}) The form returns invalid ,but a form with no errors is displayed. -
Django - get the query by date using postgresql "to_date"
I need to get raw objects using Django .objects.raw functions like : SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000-02-07','YYYY-MM-DD') AND to_date('2027-02-15', 'YYYY-MM-DD') in pgAdmin select return good result, but when i put it to django there is an error: File "C:\Users\User\Desktop\test_task\test_app\views.py", line 110 queryset = Document.objects.raw('SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000 - 02 - 07','YYYY - MM - DD') AND to_date('2027 - 02 - 15', 'YYYY - MM - DD')') ^ SyntaxError: invalid syntax what is the syntax problem? -
How clean_botcatcher(self): automatically called?
I got confused, does django automatically calls clean_botcatcher(self): . Does it acts as listener which got triggered when bot makes changes to values? from django import forms class FormName(forms.Form): name = forms.CharField() email = forms.EmailField() text = forms.CharField(widget=forms.Textarea) botcatcher = forms.CharField(required=False,widget =forms.HiddenInput) def clean_botcatcher(self): botcatcher = self.cleaned_data['botcatcher'] if len(botcatcher) > 0: raise forms.ValidationError("Gotcha BOT") return botcatcher -
Website in Django
I need to make a simple user interface preferably a login page and implement acceess control too. Besides in it users could creates entry for the database based on a simple form. Also admin can query different results from the database. Thats all of it. Which framework should I use. I learned about Django, will that be helpful and easy to understand. Please help me regarding this. P.S I wanted to use python hence I stumbled upon Django. -
What does url resolving mean in Django?
I'm working with Django and wanted to create a custom template tag which needs a url. The tag is very similar to the default url template tag. I tried to derive my custom template tag from the url tag from django but I don't understand what this means args = [arg.resolve(context) for arg in self.args] kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()} view_name = self.view_name.resolve(context) See: https://github.com/django/django/blob/master/django/template/defaulttags.py#L428 What does url resolving means and why do you have to do it? Why not just use the args and kwargs directly? -
Django change name of image from ImageField
I would like to change the name of an image coming renaming it to the color of the door. Here is my code: class Door(models.Model) : image = models.ImageField(upload_to='doors') color = models.ForeignKey(Color, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, default='119.99') I've looked at multiple things but I don't know yet how to do it. Please help me if you know the answer to my problem. -
How to get request in ModelResource django-import-export
How to get request.user from method queryset of ModelResource in django-import-export? class PeopleResource(ModelResource): class Meta: model = People exclude = ('id','agent', 'public_id', 'active') def dehydrate_placeA(self, people): ... ... def get_queryset(self): query = People.objects.filter( ..... request.user ) return query -
unable to receive multiple images in django
i am doing an hotel booking web app in django, the problem is i whave written the models perfectly with foreign key references, The main problem i got with this Reference In my web app , i want a progress bar on uploading images, for that i have included in my code through the given reference. But the problem is the images doesn't get stored when i uploaded . Here are my models hotel_rating_choices = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ('6','6'), ('7','7'), ) class Hotel(models.Model): Hotel_Name = models.CharField(max_length=50) location = models.CharField(max_length=20) no_of_rooms = models.IntegerField() room_price = models.IntegerField() rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3) hotel_main_img = models.FileField(upload_to='hotel_images/') uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) def __str__(self): return self.Hotel_Name class Hotel_image(models.Model): hotel_img = models.ImageField(upload_to = 'hotel_images/', blank = True, null = True) hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name="hotel_images") Here is my form class add_hotel(forms.ModelForm): class Meta: model = Hotel fields = ('Hotel_Name', 'location', 'rating','no_of_rooms', 'room_price', 'hotel_main_img', ) widgets = { 'hotel_main_img' : forms.ClearableFileInput(attrs={'multiple': True}) } Here is my view class BasicUploadView(FormView): template_name = 'photos/basic_upload/index.html' model = Hotel form_class = add_hotel success_url = reverse_lazy('home') def get(self, request, *args, **kwargs): form = add_hotel return render( self.request, template_name = self.template_name, context={'form' : form} ) def … -
Django: Database query and templates
I am facing a little trouble with the views.py section in this marketplace ecommerce app. I would like to show the "product category for each product" belonging to each Vendor in the my_products.html page. I have assigned one category to one product only. But I am unsure if these 3 lines of code in views.py, my_products.html and urls.py are working together correctly. categories = Category.objects.get(name=request.name) <td><a href="{% url 'shop:Edit_Product' product.category.category.name product.slug %}">{{ product.name }}</a></td> path('edit_product/<slug:c_slug>/<slug:product_slug>/', views.EditProduct, name='Edit_Product'), Thanks for any help as I'm new to Django, this being the third month I'm learning it. Following is the code in a more complete form: my_products.html <thead class="bg-success"> <tr> <th> <th>Product Title</th> <th>Price ($)</th> <th>Status</th> </th> </tr> </thead> <tbody> {% for product in products %} <tr> <td>{{ forloop.counter }}</td> <td><a href="{% url 'shop:Edit_Product' product.category.category.name product.slug %}">{{ product.name }}</a></td> <td>{{ product.price }}</td> <td>{% if product.available %}Active {% else %} Disabled {% endif %}</td> </tr> {% endfor %} </tbody> edit_product.html {% extends 'base.html' %} {% load staticfiles %} {% block title %} Edit Your Cushion Collection - Perfect Cushion Store {% endblock %} {% block content %} Edit Product page {% endblock %} views.py (shop app) @login_required(login_url="/") def MyProducts(request): products = Product.objects.filter(user=request.user) categories = … -
Where in a django project should I set up a mongoengine connection?
I've been reviewing my own code and came across this: settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'test_db', 'HOST': 'mongodb://localhost:40000, localhost:40001, localhost:40002, localhost:40003/?replicaSet=test_replica' } } mongoengine.connect( db=DATABASES['default']['NAME'], host=DATABASES['default']['HOST'], ) which sort of stroke me as odd cos it does seem odd to set up a connection to the DB used in the settings.py file. I mean in that case I will have to handle some exceptions that may be thrown in case connection is not established properly or is not established altogether which means writing more code in settings.py. I don't like the idea. The first thing that comes to my mind is to move it to a different.py file then do all the stuff needed in there and just run it in settings.py but what is the right way to do it? -
Pass GET parameters to url in Django
In my project I have a lot of cases where I need to pass the GET parameters of the current url to the next one. My current solution looks like this: <a href="{% url 'blog_list' post.pk %}?{{ request.GET.urlencode }}"> Go to postxyz </a> This works but I have a lot of links that are looking like this so I wonder if there is better solution. Or should I create a custom template tag for this? -
How to implement Google Map in Django
We have a kids school page. We need to display 2 things on map . 1. To get Latitude and Longitude details for a Kids Playschool name and display the playschool on map. 2. Based on kids playschool name , We need to display 4 nearest play schoools with distance display between main school and 4 other schools . Tried below method , but couldn't get the display : https://django-geoposition.readthedocs.io/en/stable/ -
javascript - replicate a div on button click
I have a html with various form elements: <div class="card border-bg-light mb-3" id="card_steps"> <div class="card-header bg-transparent" id="card_header"> <span class="pull-right clickable close-icon" data-effect="fadeOut"><i class="fa fa-times"></i></span> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.step_description.errors }} <label for="{{ form.step_description.id_for_label }}">Step:</label> {{ form.step_description }} </div> </div> <div class="card-body" id="card_body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="fieldWrapper"> {{ form.can_edit_email.errors }} <label for="{{ form.can_edit_email.id_for_label }}">Editable:</label> {{ form.can_edit_email }} </div> <div class="fieldWrapper"> {{ form.step_notification_period.errors }} <label for="{{ form.step_notification_period.id_for_label }}">Notify user before launch date:</label> {{ form.step_notification_period }} </div> <div class="fieldWrapper"> {{ form.step_attachment.errors }} <label for="{{ form.step_attachment.id_for_label }}">Upload:</label> {{ form.step_attachment }} </div> </form> </div> </div> In my next card div i have a link Add Steps which upon clicking will create a div which is exactly the same as the div card_steps above and it will be right below the card_steps div, so how do i go about doing this in javascript? <div class="card"> <div class="card-body"> <a href="#" class="card-link" id="add_step">+ Add Step</a> </div> </div>