Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DetailView getting values of ManyToMany relationship
I want to get post tags with ManyToMany relationship, to display related posts with the same tags. The problem is that I don't know how to access the tags of the current post. model class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) # author = tags = models.ManyToManyField(Tag, related_name='post_tags') date_created = models.DateTimeField(auto_now_add=True) time_to_read = models.PositiveIntegerField(blank=True) text = models.TextField() image = models.ImageField(upload_to='photos/%Y/%m/%d') is_published = models.BooleanField(default=True) view class GetPost(DetailView): model = Post template_name = 'blog/post.html' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data() post_tags = Post.tags.all() incorrect #context['related'] = Post.objects.filter(tags__in=post_tags)[:3] am i need to override get_object?? or i can get it in context_data? ty -
Django admin: the most proper way to limit choices of dropdown window?
I am trying to customize dropdown for one of my models named Recipe. The problem is I do not want duplicates appear. Say, administrator selected choice X from the first dropdown, then he or she clicks on the second one but there are the same choices though. Because of it admin can create a recipe with two identical tags, for example, so I would want to deprecate this logic. -
Django Can you please explain my code why if statement not working?
I am using signals where I am using this logic for update user data. author = MyAuthors.objects.filter(user=instance) if not author and instance.is_blog_author and instance.email: MyAuthors.objects.create(user=instance,is_blog_author=instance.is_blog_author,first_name=instance) if I remove not from if statement then user data not updating. Can you please explain why user data not updating if I use if author and instance.is_blog_author and instance.email ? -
Sending Outcome of Javascript Calculations to Django Backend
I have an HTML form where users type in the name of items and value corresponding to it in an input form, which is reflected when the form is submitted to Django backend. In my HTML form I have included some Javascript so that the total of these values are reflected instantly without refreshing and even before submitting the form. My goal is to send the total amount reflected in the HTML to the related class Model after submitting. Note that the reason for the question is that the total values are not manually added they are directly calculated using Javascript. Here is a sample to make things more clear. Here is the HTML Template: <tr> <td> <input placeholder="Type in the Equipment and assets" type="text" class="form-control" name="item_1" id="item_1" {% if form.is_bound %}value="{{ form.item_1.value }}"{% endif %}/> {% for err in form.item_1.errors %} <small class="text-danger mb-2 ml-2">{{ err }}</small> {% endfor %} </td> <td> <h6 style="float:left; margin-right:5px; margin-top:7px">$</h6> <input type="number" class="form-control w-25 subtotal-group subtotal-group-1" name="item_1_amount" id="item_1_amount" {% if form.is_bound %}value="{{ form.item_1_amount.value }}"{% endif %}/> {% for err in form.item_1_amount.errors %} <small class="text-danger mb-2 ml-2">{{ err }}</small> {% endfor %} </td> </tr> <tr> <td> <input placeholder="Type in the Equipment and assets" type="text" … -
ValueError at /plants/plants/ too many values to unpack (expected 2) when using django_filters
Hej! I'm having trouble with my django filter. When I put {{myFilter}} in the template I only get an ObjectNumber and when I put {{myFilter.form}} I get the error: ValueError at /plants/plants/ too many values to unpack (expected 2) Does anyone have an idea what's going on? # views.py def plants_view(request): plants = Plant.objects.all() myFilter = PlantFilter(plants) context = {"plants": plants, "myFilter": myFilter} return render(request, 'plants/search_table.html', context) # filters.py class PlantFilter(django_filters.FilterSet): class Meta: model = Plant fields = ['name',] it doesn't matter if I use fields = [ ] or fields = '__all__' . template.html {% extends "landing/base.html" %} {% load static %} {% load i18n %} {% load admin_urls %} {% block page-title %} {%translate "View Plants" %} {% endblock %} {% block head %} <link href="{% static 'landing/vendor/tabulator/dist/css/tabulator.min.css' %}" rel="stylesheet"> <link href="{% static 'landing/vendor/tabulator/dist/css/bootstrap/tabulator_bootstrap4.min.css' %}" rel="stylesheet"> {% endblock %} {% block content %} <br> <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> {{myFilter.form}} <button class="btn-primary" type="submit">Search</button> </form> </div> </div> </div> </br> # models.py class Plant(models.Model): name = models.CharField( max_length=200 ) def __str__(self): return f"{self.name}" def serialize(self): return { "Name": self.name } -
SQL AND PYTHON EXPRESSION MEANING
Hello i found this expression on some source code i was reading. what does the comma sign mean (between order_item and created). Is 'created' a reserved word in sql? Also if you have any source to learn using sql with python would be great thanks. Heres the expression: order_item, created = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) -
Passing a list of strings (uuids) back and forth between django views and template
On one of the pages of my django project I have a check box to select uuids corresponding to a model. This is what I have on the views.py page and it works well to create a checkbox. def template_page(request, uuid_selects=None, option_1=False): ... class uuidCheckBox(forms.Form): uuid_selects = forms.ModelMultipleChoiceField(queryset=uuid_model, widget=forms.CheckboxSelectMultiple) uuid_select_field = uuidCheckBox() args.update({'uuid_select_field': uuid_select_field}) ... render(request, landing.html, args) On my template page I have this: <form action='get_uuid_selects' method='GET'> {{ uuid_select_field }} <input type='submit' value='Submit' /> </form> Which redirects back to this view: def get_uuid_selects(request): uuid_selects = request.GET.getlist('uuid_selects') return landing_page(request, uuid_selects) This all works fine however when I try to pass this list of uuids back to the template as a hidden value and return it when the user accesses another form the list doesn't work. For example I pass the list as an argument following the approach here This is the views.py for template: def template_page(request, uuid_selects=None, option_1=False): ... if uuid_selects: args.update({'uuid_selects': json.dumps(uuid_selects)}) ... render(request, landing.html, args) Then I pass this list of uuids back to the template page so that it is a hidden value in another form on the template.html page. <form action='to_option_1' method='GET'> <button type='submit'>Option 1</button> {% if uuid_selects %} <input type="hidden" value= {{ uuid_selects }} name="uuid_selects"> … -
Should I use build APIs for my POS web application?
I'm building a POS(Point of sale) web application using Django for my client. This is a single instance web app. I just want to know, should I build APIs to separate Backend and Frontend? Whare are the benefits to build the APIs? -
Soft Delete. Move records or create "deleted" column
I am a little confused about which is better for soft delete. There are two ways for Soft Delete. create table for deleted records.(In this way we will make copy for the records in the table of deleted records, then delete it from its table) create extra column called deleted,(In this way we will only change the status of this field to true , then at display records we will filter according to this extra field) -
How to do nested group by with annotation in django orm?
I have the following data: publisher title -------------------------- ----------------------------------- New Age Books Life Without Fear New Age Books Life Without Fear New Age Books Sushi, Anyone? Binnet & Hardley Life Without Fear Binnet & Hardley The Gourmet Microwave Binnet & Hardley Silicon Valley Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Algodata Infosystems But Is It User Friendly? Here is what I want to do: I want to count how many books of the same titles are published by each author. I want to get the following result: {publisher: New Age Books, title: Life Without Fear, count: 2}, {publisher: New Age Books, title: Sushi Anyone?, count: 1}, {publisher: Binnet & Hardley, title: The Gourmet Microwave, count: 1}, {publisher: Binnet & Hardley, title: Silicon Valley, count: 1}, {publisher: Binnet & Hardley, title: Life Without Fear, count: 1}, {publisher: Algodata Infosystems, title: But Is It User Friendly?, count: 3} My solution goes something along the lines of: query_set.values('publisher', 'title').annotate(count=Count('title')) But it is not producing the desired result. -
Cannot access request.data in log filter
I am using Django REST Framework, and following this django logging - django.request logger and extra context answer to include custom data to my log records. When trying to access record.request.data inside filter() (to store it to record.data as that answer suggests) I get RawPostDataException: You cannot access body after reading from request's data stream. I have tried many things, none of which worked. Cannot manually rewind the request's data stream, nor get a fresh copy of the request object. I never manually access request.body, as the SO answers suggest avoiding. Any help would be appreciated. -
Datetime received a naive datetime whereas I precised before the timezone
I am working a Django project. Here is my code : today = datetime.datetime.now() currentperiod = Day.objects.get(enddate__gte=today.date(), startdate__lte=today.date()) And I got that message : RuntimeWarning: DateTimeField Day.startdate received a naive datetime (2021-10-04 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s.%s received a naive datetime " So I tried that : today = datetime.datetime.now() today = pytz.timezone("Europe/Paris").localize(today, is_dst=None) currentperiod = Period.objects.get(enddate__gte=today.date(), startdate__lte=today.date()) But it does not work whereas I used pytz, I suppose it comes from today.date() but I don't know how to proceed further ... Could you help me please ? Thank you very much ! -
Django add to many to many field working without save
What's the difference between group.reportedBy.add(request.user) group.save() AND group.reportedBy.add(request.user) It gets saved to the DB even without me doing .save() -
want to return dictionaries in lists Python Django
I want to return dictionaries of lists. With total, grand total, tax amount and name in each list. ''' #branches tax report and total - FBR and NFBR def branch_report(request, params): branch = Order.value('name', 'sub_total', 'grand_total', 'tax_amount') report = report[''] for name in Order.find_all('name'): info = { "name": branch.get('name'), "sub_total": branch.get('sub_total'), "grand_total": branch.get('grand_total'), "tax_amount": branch.get('tax_amount'), } report.append(info) return response_format(SUCCESS_CODE, SUCCESSFUL_RESPONSE_MESSAGE, report) ''' I want a result like this: ''' { "code": 200, "message": "Request was Successfull", "data": { "branches": [ { [ { "name": "Bedian 1", "id": 13, "sub_total": null, "tax_amount": null, "grand_total": null, "with_fbr_sub_total": null, "with_fbr_tax_amount": null, "with_fbr_grand_total": null, "without_fbr_sub_total": null, "without_fbr_tax_amount": null, "without_fbr_grand_total": null } ] } ''' -
Why is django not able to display Images and videos in AMP-story player
I have been stack on weeks trying to resolve this issue, I don't know why the AMP Story wouldn't load images that I post through the Django database, but somehow i have observed a very strange behavior of it being able to load images and videos which are not been requested from the database and also if images are been loaded from the asset directory i have to add the image format like JPG, PNG etc.. in order for it to display in the AMP Player. My major concern now is : 1.How do I request images and videos from the Django database to be able to work in the amp story player? 2.Since the player needs me to specify the file format of the image eg, JPG,PNG,JPNG etc.. How do i go about it? Here is a sample code of what i did, This is the player! {% extends "base.html" %} {% block content %} {% for a in amp %} <amp-story standalone title="Joy of Pets" publisher="AMP tutorials" publisher-logo-src="assets/AMP-Brand-White-Icon.svg" poster-portrait-src="assets/cover.jpg"> <amp-story-page id="cover"> <amp-story-grid-layer template="fill"> <amp-img srcset="{{ a.images.url }}" width="720" height="1280" layout="responsive" amp-story-player-poster-img> </amp-img> </amp-story-grid-layer> <amp-story-grid-layer template="vertical"> <h1>{{ a.title }}</h1> <p>{{ a.description }} </p> </amp-story-grid-layer> </amp-story-page> <!-- Page 1 (Cat): … -
How do I build a points based voting system (Django)
I have designed a system with five tables. Two tables are of users, buyers and sellers. And the remaining two tables are of products and companies. The buyers can have a relationship with the products and sellers can have relationships with products. The sellers and products also have relationships with the companies. Please note that the product can change companies at any time. Also, seller, product and buyer are all people (I labeled them that way for clarity) Now where I need help, I need to know how to design this part of the system based on this requirement. I need to create a points based rating system that will rate like a quiz, in such a way that; Every seller can rate product. Every product can rate seller. Both buyer and seller can rate company Company can rate product and seller Admin of the rate can rate companies and sellers SUMMARY Existing Relationships Buyer - products seller - products sellers - company product - company Goal Sellers will have 3 set of ratings from (buyers, company, product) each set with different unique parameters to rate. Product will have ratings from sellers alone Companies will have 3 sets of ratings … -
TinyMCE: Django admin custom HTML field displays incorrectly in HTML page
I use Django on backend and VueJS on frontend. I use tinymce for creation custom HTML field. description = CustomHTMLField('Description', blank=True, null=True) Settings for tinymce: TINYMCE_DEFAULT_CONFIG = { 'plugins': 'print preview textcolor importcss searchreplace autolink autosave save directionality visualblocks visualchars fullscreen image link media codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount textpattern noneditable help charmap emoticons', 'toolbar': 'insert | undo redo | formatselect | bold italic backcolor forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help', 'cleanup_on_startup': True, 'custom_undo_redo_levels': 10, 'width': 'auto', 'language': 'ru', } TINYMCE_FILEBROWSER = True Code of CustomHTMLField: from contextlib import suppress from tinymce import HTMLField class CustomHTMLField(HTMLField): def pre_save(self, model_instance, add): if not add: return super(CustomHTMLField, self).pre_save(model_instance, self.attname) html_field: str = getattr(model_instance, self.attname, "") with suppress(AttributeError): return html_field.replace('../../../../', '../../../../../') I need to add some text with list into this field. On Django admin page I have indent: But on frontend I don't have the indent: How can I fix the problem? -
i need help to convert this code from django to nodejs
i need help to convert this code from django to nodejs def post(self, request): path = '/achievements/achievements.json' base = str(settings.BASE_DIR) try: with open(base+path) as f: achievements = json.load(f) except: return Response(status=status.HTTP_404_NOT_FOUND) for achievement in achievements: self.find_or_create(achievement) return Response({'data': achievements}, status=status.HTTP_200_OK) -
Django : How to get month data in week wise format in django
class Car(models.Model): name= models.CharField() model = models.CharField() date = models.DateTimeField(default=datetime.now) This is my Model ( Car ) If I pass date params ( 2021-07-09 ), I need last 1 month of data from this date. ( Eg : 2021-07-9 - 30 DAYS ). I'm using Django Rest framework. I need 30 days of data's in week format ( 7 days data in one set like wise..) can anyone help me to come out of this situation.. Thank you...!! -
Filter django model using Dictionary Comprehension
I have a model, called cards, which contains a number of elements I want to loop through. So I was trying to use some dictionary comprehension as follows: cards = Card.objects.filter(device=device) output = { c.id : [c.generateData(), c.sensor.getLatestTime()] for c in cards} While running that code, it breaks on the output statement with the following error: The QuerySet value for an exact lookup must be limited to one result using slicing. Most of the pre-existing answers I found for that exact error were for cases where the queryset is being confused with a single field, as in 1, 2. However in my case, I am expecting, and handling it as a queryset by looping through it. I have also seen a question that is similar in here about using dictionary comprehension on the models, however as far as I can see, my format is almost the same (Unless the list as a second parameter is causing an issue somehow?) -
daphne run in supervisor returns an error django.core.exceptions.ImproperlyConfigured
why daphne returns an error to me via supervisor django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure () before accessing settings. But when I run it out of supervisorctl, it works. I have a system variable defined. Is it a mistake to run it in venv?. supervisor conf [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8099 # Directory where your site's project files are located directory=/srv/app/ # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/srv/venv/bin/daphne -u /srv/run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers mysite.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=1 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/srv/log/daphne.log redirect_stderr=true -
Django-filer upload location change
How do I access image URLs for Filer-fields also how to change the upload location Class CustomFilters(models.Model): input_file = models.ImageField( upload_to='input/images/', blank=True, null=True) bg_image_one = FilerFileField(null = True,on_delete = models.CASCADE) name = models.CharField(max_length=50) action = models.CharField(max_length=150, choices=ACTION_CHOICES) is_active = models.BooleanField(default=False) Currently, i am trying this bg_image_one.image.url -
What is the best WAY to create a django model instance with a model form with blank and null set true on certain fields?
I have the following model: class Foo(models.Model): field1 = models.CharField(max_length=100) field2 = models.ForeignKey(AnotherModel, on_delete=models.CASCADE) field3 = models.ImageField(blank=True, null=True) field4 = models.CharField(max_length=15, blank=True, null=True) And here is my view: def myView(request): form = FooForm(request.POST or None) if form.is_valid(): # What is the best to extract to filled fields by the user # so that I will know what to pass the objects.create() method field2 = form.cleaned_data.get('field1) # how to know if that's empty since it is not required Foo.objects.create(field1="do not want it to be empty" ) What is the best way to check if the value of the fields is not empty and pass it to the create method? -
I get this django error 421, b'service not available (connection refused, too many connections when signing up for my account, i dont really know?
SMTPConnectError at /investor/signup (421, b'service not available (connection refused, too many connections)') This Error has been delaying for days now, i'm really stuck while sending email with django and i'm a beginner in django that why i do not have many idea on how to solve this issue please can anyone help? Setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxxxxxxxxxxxxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxxxxxxxxxx!?' EMAIL_USE_TLS = True -
buffer = _builtin_open(filename, 'rb') PermissionError: [Errno 13] Permission denied: 'C:/Users/Users/OneDrive/Desktop/projects/Barracuda'
Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1483, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 11, in execfile stream = tokenize.open(file) # @UndefinedVariable File "C:\Users\bbuug\AppData\Local\Programs\Python\Python39\lib\tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') PermissionError: [Errno 13] Permission denied: 'C:/Users/bbuug/OneDrive/Desktop/projects/Barracuda' Process finished with exit code 1