Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing object to a Django Class-Based Generic View
The user is presented with a simple table that displays a list of Food object data alongside an option to log that food item. ... {% for food in foods %} <tbody> <tr> <th scope="row"><a href="{% url 'food-detail' food.id %}">{{ food.name }}</a></th> <td scope="row">{{ food.data1 }} g</td> <td scope="row">{{ food.data2 }} g</td> <td scope="row">{{ food.data3 }} g</td> <td scope="row"><a href="{% url 'food-entry' food.id %}">Add</a></td> </tr> </tbody> {% endfor %} ... When a food is logged, a basic entry object should be created on the back-end. class Entry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) food = models.ForeignKey(Food, on_delete=models.CASCADE) servings = models.DecimalField(default=1, max_digits=4, decimal_places=2) date_of_entry = models.DateField(default=timezone.now) def __str__(self): return self.food.name In Corey Schafer's series on Django, we're able to set the user field within the CreateView's form_valid() method. class EntryCreateView(CreateView): model = Entry fields = ['servings'] def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) I have encountered function based solutions for similar tasks, such as: product = Product.objects.filter(id=kwargs.get('item_id', "")).first() A lot of the logic is happening under the hood, so I'm struggling to ascertain what data I'm able to access / utilize from within my EntryCreateView(CreateView) class. Is there a standard solution for setting an Entry's 'food' member data? My case seems to … -
Django - how to handle time duration
I am trying to display the elapsed time during a race. class results(models.Model): race_id = models.ForeignKey(Race, on_delete=models.CASCADE) runner_id = models.ForeignKey(Runner, on_delete=models.CASCADE) race_start = models.DateTimeField() race_finish = models.DateTimeField(blank=True, null=True) obs = models.TextField(blank=True) def __str__(self): return self.race_id.race_cod+" - "+self.runner_id.name class Meta: verbose_name_plural = "Results" Looking here I have found the following guides: Django model elapsed time between two DateTimeFields Django: What's the best field type to represent time elapsed? Unfortunately, the solution presented there seems a little bit complex. I also have found this workaround in the .html view page <div class="info-box-content"> <span class="info-box-number">Time - {{ results.race_finish|timesince:results.race_start }}</span> </div> the issue with this one is that everything over 24 hours came as x days, yy hours - while my need is to display the duration as HH:mm Any hints here? -
Django Choice Field HTML Custom Output
I'm currently working on a Django project and I'm facing a bit of headache. I need to "convert" an HTML page (form) to a proper functioning Django Form App. The problem comes exactly in the ChoiceField (the two choices Manhã and Tarde). On the left, it's the Django Form HTML output and on the right, there's the original HTML page. The styling is different and I can't figure out how I can make them equal. Also, I wanted to make them horizontally aligned, but Django it's not so flexible as I thought in this matter. I hope you can give me clear tips and light in this strange darkness, I have a couple of frontend skills but nothing above the average. https://i.stack.imgur.com/CU0MA.png -
Django save long running process on completion
I want to create an application that interacts with external APIs which create and manage a long running process (can be minutes/hours). Django app would save a model instance only when the process is successful. On form submission, external API is triggered to run a process with parameters from form submission. External API gives job uuid, what's the preferred way of checking the status? Should it be checked in Model save() in a while loop (via job status GET requests to external API)? Or is there a better way. -
Image not loaded on template
This is my view ob = article.objects.raw("select * from blogapp_article as a inner join blogapp_useradd as b on a.userid=b.uname ORDER BY a.id DESC") 'data1': ob On template {% for item in data1 %} <img src="{{ item.upic.url }}" style="width: 60px"> {% endfor %} -
re-usable code for Django's migrations, which works also outside migrations
This is about creating users, groups and more instances in Django, in bulk manner, and re-using the same creation code in the regular app and in migrations as well. There is a problem in RunPython when code tries to use some models imported in a regular way. For example below is true when running migration (apps is django.db.migrations.state.StateApps argument) from django.contrib.auth.models import User assert apps.ready assert User != apps.get_model('auth', 'User') >>> User <class 'django.contrib.auth.models.User'> >>> app.get_model('auth', 'User') <class '__fake__.User'> >>> type(app.get_model('auth', 'User')) <class 'django.db.models.base.ModelBase'> Then using both kinds of models together will result in TypeError like: TypeError: 'Group' instance expected, got <Group: Bots> Of course, a question is how to avoid changes in code, but have code working with both models (migrations and regular app) am I forced to load Django's commands inside migrations? -
Getting AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint' in Django 1.11
I am using Django 1.11 and when trying to import UniqueConstraint, I am getting this terrible AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint' error. I don't want to step down to unique_together, because it seems like being depreciated. So why I get this error in the latest version of Django ?! I am importing it the following way: from django.db import models class CalendarAccount(models.Model): class Meta: managed = False db_table = 'my_table' constraints = [ models.UniqueConstraint(...), ] -
GeoDjango on AWS Elastic Beanstalk: OSError: libcrypto.so.1.1: cannot open shared object file
Trying to run GeoDjango on AWS EBS. I had to compile GDAL from source and install it into usr/local/gdal, along with proj4 and geos. This fixed my original issue, but now I am confronted with this error: from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/gis/gdal/libgdal.py", line 47, in <module> lgdal = CDLL(lib_path) File "/usr/lib64/python3.6/ctypes/__init__.py", line 343, in __init__ self._handle = _dlopen(self._name, mode) `OSError: libcrypto.so.1.1: cannot open shared object file: No such file or directory` I can't seem to find that libcrypto.so.1.1 file. I was able to find the following: Location: /usr/lib64/ libcrypto.so libcrypto.so.10 libcrypto.so.1.0.2k libcrypt.so Location: /lib64/ libcrypt.so.1 I don't think Libcrypto.so.1.1 is installed on this EC. -
Getting admin template errors when changed default django user model
Hello I get this errors in log file when open http://127.0.0.1:8000/admin/custom_users/customuser/ I create a custom user model to let my users login by email. I googled some errors in this log and maybe it is known django bug, but I not find any solution. Exception while resolving variable 'errors' in template 'admin/change_list.html'. Traceback (most recent call last): File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'NoneType' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup current = getattr(current, bit) AttributeError: 'NoneType' object has no attribute 'errors' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'errors' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [errors] in None Exception while resolving variable 'show' in template 'admin/change_list.html'. Traceback (most recent call last): File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/Users/User/CODE/python/learn/django/venv/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'show' … -
Navbar dropdown menu href links not a working properly (Django+Bootstrap)
I am creating a small web application with using Django and Bootstrap4. In my Project Folder in Django, I have the templates and one of them is the base template. The other templates extend the base template. I have added the Bootstrap CDN to the base template and is working fine. I have created Bootstrap Navbar which get a dropdown when adjusted to screen size. The issue is when I click a nav-link it adds the path in its href to the current path displayed in my browser i.e the location of the previous nav-link and searches for that. Hence it gives me an error. Upon clicking it should only take the path of only the clicked nav-link. My code is below. The href links are coming from my urls.py file. Please advise how to resolve this. Thanks. base.html code -
Functions Callbacks Not Working - Dash Plotly
I have the application below that uses dash plotly. If i execute this application in a single file/page application all acllbacks works correctly. But in this case I using dash multipage application with Django. And my callbacks stop to work, the computed-table and table-backlog. I not sure why these callbacks not working regarding that there's no error in runtime or code as well. The objective of callback is perform calculations in dash table once values is changed by user. Full Project: https://github.com/CaioEuzebio/DjangoDashboard/blob/master/app/as_dash.py Application: import sys from random import randint import base64 import io import datetime from dash.dependencies import Input, Output, State import dash import dash_core_components as dcc import dash_html_components as dhc import pandas as pd import random import plotly.graph_objects as go import dash_table import dash_table_experiments import dash_table import dash_bootstrap_components as dbc import os, time from os import listdir import os.path, time import datetime import subprocess from website.views import * PLOTLY_LOGO = "https://p7.hiclipart.com/preview/243/790/417/doing-business-as-company-logo-name-creative-company-logo.jpg" def dispatcher(request): ''' Main function @param request: Request object ''' app = _create_app() params = { 'data': request.body, 'method': request.method, 'content_type': request.content_type } with app.server.test_request_context(request.path, **params): app.server.preprocess_request() try: response = app.server.full_dispatch_request() except Exception as e: response = app.server.make_response(app.server.handle_exception(e)) return response.get_data() def _create_app(): ''' Creates dash application ''' app … -
Vue.js / Nuxt App that serves up django pages
This is more of a general but very specific question as it pertains to a large, preexisting ecommerce site so I'll do my best to be as specific and succinct as possible... I have a monolithic Django App that currently uses Django Templates as its frontend layer. Everything has been fine tuned down to the last pixel to extract as much SEO value out of the current setup. The company now wants to move to a Vue.js FE, however they want to do this process piecemeal, and NOT do the whole SPA in one go. This brings up the following challenge: I understand that with these new vue/react libraries, when seo web crawlers crawl the page, the js code needs to be "pre-rendered" in order to see what's actually on the page. And because we are revamping a lot of widgets that have to do with products, their names, their prices, etc. i fear that we are going to lose some very relevant data that have to do with keeping our SEO score high. That being said, I'm wondering if it's at all possible to create a Nuxt app, and then wrap some of the django template pages inside of … -
How to make queryset in django?
item_list = Item.objects. filter(location_id=location_id) image_list = Image.objects.filter(?????) class Image(models.Model): item = models.ForeignKey(Item, models.on_delete=CASCADE) I want to get only those images which item_id in the first queryset item_list -
Documenting a django project (django 2 + drf + drf-access-policy)
I'm documenting a django project that use DRF. I already generated a dynamic API schema using openapi and redoc. Very cool solutions However, I miss the permissions part in all of this I have a lot of permissions (permission_classes) in the viewsets and some functions. Do you know any solution to include the permission in the schema, or in a documentation in general? Going further, how do you document permissions in a APIs in general? I already have an idea: include the permissions in a custom description in the schema, but it's still dirty Thanks. José.- PS: Sorry for the poor english -
Filter by String Embedded Documents from the main document using MongoEngine - Python Flask
I am trying to filter embedded documents by String (LIKE Query SQL equivalent) from the parent document. Here's what I have now: def resolve_friend(root, info, **kwargs): phone = kwargs.get('phone', None) search_string = kwargs.get('searchString', None) try: // I am retrieving the parent doucment by phone number first account = AccountModel.objects(phone=phone).first() if account is None: return ResponseMessageField(is_success=False, message="User does not exists.") top_friends = None // Now I want to filter the Friends field from the account by the search string. // In the friends' field, there are multiple documents. The idea is to get the friends // matching the string from their first_name / last_name if search_string: regex = re.compile('.*' + search_string + '.*', re.IGNORECASE) //doesn't work any of these below # top_friends = account.friends.filter((Q(first_name='test') | Q(last_name='test'))) top_friends = AccountModel.objects(friends__first_name__icontains='tes').all() all_friends = account.friends.filter(request_status="ACCEPTED") //this works fine return retrieve_friend_list_graphql(top_friends=top_friends, all_friends=all_friends) except Exception as e: return ResponseMessageField(is_success=False, message="Account fetch error. " + str(e)) These lines don't work top_friends = account.friends.filter((Q(first_name='test') | Q(last_name='test'))) top_friends = AccountModel.objects(friends__first_name__icontains='tes').all() I am unable to filter the account.friends.filter() with the search string in mongoengine. Here's the full account document with the friends field. { "_id": { "$oid": "5e3485c2dd26ea191faf2861" }, "identity": "0b1170fc50979464c352c34c2e9fd7aa", "username": "Shuvro", "first_name": "", "middle_name": "", "last_name": "", "phone": … -
set choices in django model
class LeaveRequestStatus(IntEnum): open = 0 accepted = 1 rejected = 2 closed = 3 class LeaveRequest(models.Model): status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open) so i had to make this changes to the two classes but i still doesnt work class LeaveRequestStatus(IntEnum): open = (0, 'Open') accepted = (1, 'Accepted') rejected = (2, 'Rejected') closed = (3, 'Closed') class LeaveRequest(models.Model): status = models.PositiveSmallIntegerField(choices=LeaveRequestStatus, default=LeaveRequestStatus.open) But it still doesn't work what i missing or what is not supposed to be there -
Permission to specific field in Django admin panel
I have a model in Django that I want to add instances to it from the admin panel. I have few users that will have access to the admin panel to create new posts to the model and I have 2 questions: It is possible to detect witch user is in the panel to auto-detect the field "Author"? (See the red rectangle in the picture) Can I disable the option to a specific user to mark the "Published" field as true? (See the green rectangle in the picture) -
Django CKeditor using richTextField but when text is long it wont do paragraph
Iam using the RichTextUploadingField from CKeditor and when the text is long and need to do the paragraph it wont do it, in spite of using safe in the template models.py class Manuais(models.Model): descrição = RichTextUploadingField(blank=False) template manual.html {{ manual.descrição | safe }} -
Django Field Error cannot resolve keyword 'is_staff
Cannot resolve keyword 'is_staff' into field. Choices are: dob, experience, id,user, user_id I get the above error when adding trainer as a Foreign Key to the Subscription model and then accessing any record for Subscription model from admin panel class Subscription(models.Model): client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE) trainer = models.ForeignKey(TrainerProfile, null=True, blank=True, on_delete=models.SET_NULL, limit_choices_to={'is_staff': True}) plan = models.ForeignKey(Plan, on_delete=models.CASCADE) transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() -
NameError at /test_submit/ name 'item_name' is not defined in Django
Hello Iam new in django and i try to same my form input to database without form.py just from views but iam getting name error please help me to short out the problem This is my html form code <form class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin" method="post" action="/test_submit/" id='myForm'> {% csrf_token %} <div class="w3-row-padding"> <div class="w3-half"> <p><label>Item Name</label></p> <p><input class="w3-input" type="text" name="item_name" required></p> </div> <div class="w3-half"> <p><label>Brand Name</label></p> <p><input class="w3-input" type="text" name="brand_name" required></p> </div> </div> <div class="w3-row-padding"> <div class="w3-half"> <p><label>Item Size</label></p> <p><select class="w3-select" name="item_size" required> <option value="" disabled selected>Select Size</option> <option value="5k-7k">5k-7k</option> <option value="7k-10k">7k-10k</option> <option value="11-13">11-13</option> <option value="1-3">1-3</option> <option value="4-5">4-5</option> <option value="6-9">6-9</option> <option value="10-11">10-11</option> </select></p> </div> <div class="w3-half"> <p><label>Item Color</label></p> <p><input class="w3-input" type="text" name="item_color" required></p> </div> <div class="w3-half"> <p><label>Item Unit</label></p> <p><select class="w3-select" name="item_unit" required> <option value="" disabled selected>Select Unit</option> <option value="Number">Number</option> <option value="Number">Number</option> <option value="Boxes">Boxes</option> </select></p> </div> <div class="w3-half"> <p><label>Quantity</label></p> <p><input class="w3-input" type="number" name="item_quantity" placeholder="0" required></p> </div> </div> <div class="w3-row-padding"> <div class="w3-half"> <p><label>Purchase Price</label></p> <p><input class="w3-input" type="number" name="purchase_price" placeholder="0.0" required></p> </div> <div class="w3-half"> <p><label>Selling Price</label></p> <p><input class="w3-input" type="number" name="selling_price" placeholder="0.0" required></p> </div> <div class="w3-half"> <p><label>MRP</label></p> <p><input class="w3-input" type="number" name="mrp" placeholder="0.0" required></p> </div> <div class="w3-half"> <p><label>Date</label></p> <p><input class="w3-input" type="date" name="date" required></p> </div> </div> <div class="w3-bar"> <button class="w3-btn w3-blue w3-round">Save</button> <button class="w3-btn w3-blue … -
I try getting members list in a voice channel from a bot and then display on my django app, didnt work
from discord.ext import commands client = commands.Bot(command_prefix = '.') channel = None @client.event async def on_ready(): channel = client.get_channel(677999369642836037) async def members_list(request): curMembers = [] for member in channel.members: curMembers.append(member) return render(request, "discordTool/discordTool.html", { 'members_list': curMembers, }) client.run('my token') I use django and I am well aware of the fact that I need to place the bot code in a different file, my main issue is that I don't know how I would get the members list from the bot if it's placed in a different file? or how to call the bot and run it only whenver I need it to run? -
Django redirect not works
I would like to redirect to another view if a condition is met, but the redirect functionality not show the template, blank screen. I have tried with this. views.py class CustomSendView(LoginRequiredMixin, View, PermissionRequiredMixin): model = None def get(self, request, id=None, *args, **kwargs): if int(self.element.status) != 4: print(reverse('app:' + self.model.__name__.lower() + '_detail', kwargs={"id": str(self.element.id)})) #/app/presupuestos/27/ver/ return redirect(reverse('app:' + self.model.__name__.lower() + '_detail', kwargs={"id": str(self.element.id)})) urls.py # Detail path('presupuestos/<str:id>/ver/', app_views.CustomDetailView.as_view( model=app_models.Budget), name='budget_detail'), The redirect works, this is the django server output: [17/Feb/2020 18:35:14] "GET /app/presupuestos/27/send HTTP/1.1" 302 0 [17/Feb/2020 18:35:15] "GET /app/presupuestos/27/ver/ HTTP/1.1" 200 41908 Anybody could help me please ? Thanks in advance. -
Django Execute a def at a time value
I'm searching for a method to make a def to execute at a time value when I run the server... Example once per day. One solution is to use Celery but i don't want to use it only for a simple def... Any suggestion? I'm using windows. Thanks! -
Return a message and a (downloadable) response to the user within the admin panel
I am having some small troubles being able to map a button with both a downloadable response, as well as a message via message_user(). To give more context, this is what my admin/user page looks like: The issue is primarily within the download buttons. These buttons are created as so (only showing .zip one for simplicity): def download_zip(self, user): if ( user.completed_agreement and user.completed_survey and user.completed_questionnaire and user.completed_feedback ): return format_html( '<a class="button" href="{}" target="_blank">Download</a>', reverse("admin:username-download-zip", args=[user]), ) else: return format_html( '<a class="button" disabled="disabled" title="Cannot download user who has not completed full survey.">Download</a>', ) And on clicking, calls the following function: def download_user_zip(self, request, user): """ Downloades the given username as a zip format. """ # Message to display to the user. self.message_user( request, mark_safe(f"Downloading files for the username <b>{user}</b>."), ) # Grabs the user generated zip file as a memory file. mem_file = download_user_zip_file(user) # Generates the response object. response = HttpResponse( mem_file.getvalue(), content_type="application/x-zip-compressed" ) response["Content-Disposition"] = f"attachment; filename={user}.zip" # Saves the memory file to response buffer. response.write(mem_file) # Returns the response. return response As of right now, the function works in terms of the download. The .zip file is opened in a different tab, and begins downloading. My … -
Generate unique ascending numerical id in django model field
Class Car(models.Model): type = models.CharField('Type', max_length=100) code = models.CharField('Code', max_length=10, blank=True, null=True) Considering I want to make a list of cars depending on their types. I have a model and fields like the above code, I want to make the code uniquely increment based on the type of the car. For instance, if an instance of a car was created with type field as 'HD', then the code would be 'HD-0000001'. The next model created with the type HD as well would be HD-0000002, so on, so forth. If another type is given, it will save as 'type' + 'the last saved number + 1'. I know I have to do something in the save() function, but I can't figure out how to make it unique based on different types. Any suggestions will be truly appreciated. Thank you!