Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django EditForm Unexpectedly Concatenating Fields
I have a weird scenario where my modal edit form is showing up odd.. The last two fields of mine are showing up concatenated to each other rather than on their respective lines... I feel like this could just be an issue with commas or seperators somewhere but maybe there's more to it. I guess maybe I've been staring at this too long. Any thoughts on what would cause this? views.py class UpdateCrudUser(View): def get(self, request): id1 = request.GET.get('id', None) employee1 = request.GET.get('employee', None) description1 = request.GET.get('description', None) stakeholder_group1 = request.GET.get('stakeholder_group', None) stakeholder_quadrant1 = request.GET.get('stakeholder_quadrant', None) obj = Stakeholder.objects.get(id=id1) obj.employee = employee1 obj.description = description1 obj.stakeholder_group = stakeholder_group1 obj.stakeholder_quadrant = stakeholder_quadrant1 obj.save() user = {'id':obj.id,'employee':obj.employee,'description':obj.description,'stakeholder_group':obj.stakeholder_group,'stakeholder_quadrant':obj.stakeholder_quadrant} data = { 'user': user } return JsonResponse(data) html: // Create Django Ajax Call $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val().trim(); var employeeInput = $('input[name="formemployee"]').val().trim(); var descriptionInput = $('input[name="formdescription"]').val().trim(); var stakeholder_groupInput = $('input[name="formstakeholder_group"]').val().trim(); var stakeholder_quadrantInput = $('input[name="formstakeholder_quadrant"]').val().trim(); if (employeeInput && descriptionInput && stakeholder_groupInput && stakeholder_quadrantInput) { // Create Ajax Call $.ajax({ url: '{% url "polls:crud_ajax_update" %}', data: { 'id': idInput, 'employee': employeeInput, 'description': descriptionInput, 'stakeholder_group': stakeholder_groupInput, 'stakeholder_quandrant': stakeholder_quadrantInput }, dataType: 'json', success: function (data) { if (data.user) { updateToUserTabel(data.user); } } }); } else { alert("All … -
What is the role of using two dashes here __year in the example below ? im new in learning django
Get the question that was published this year. >>> from django.utils import timezone >>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year) <Question: What's up?> -
django, class based views, DeleteView, redirect
massive noob here (worse than that, actually, I went to a bootcamp). About two days in now and I officially don't even know the terms I'm looking to google for. I have a collection of documents about a house. I'd like to organize them with aw django project. The categories for the documents are 'purchase', 'inspection' and 'rooms'. The category is selected with a dropdown on a form generated by the django CreateView (I uh, suspect that's what creates it?). If I delete a document, I want to be redirected to whatever URL I clicked the 'delete' button from. If the document was a 'room,' redirect me to the URL named 'rooms' (that's where I had to delete it from), same for the others. When the views have 'fields' it's straightforward as if/else. However, with DeleteView, there are no 'fields' and so I do not know (or, understand) what I'm looking to use to get the proper URL. How would one achieve said behavior? urls.py path('', index, name='home_index'), path('inspection/', DocsListView.as_view(template_name='inspection_list.html'), name='inspection'), path('inspection/<slug:slug>', DocDetailView.as_view()), path('purchase/', DocsListView.as_view(template_name='purchase_list.html'), name='purchase'), path('purchase/<slug:slug>', DocDetailView.as_view()), path('rooms/', DocsListView.as_view(template_name='rooms_list.html'), name='rooms'), path('rooms/<slug:slug>', DocDetailView.as_view()), path('homedoc-create/', DocCreateView.as_view(), name='doc_create'), path('homedoc-update/<slug:slug>', DocUpdateView.as_view(), name='doc_update'), path('confirm-delete/<slug:slug>', DocDeleteView.as_view(), name='doc_delete'), ] models.py class HomeDocs(models.Model): name = models.CharField(max_length=255) img … -
Show Bootstrap 5 Modal on Page Load with Django Messages
I've been playing around with Bootstrap 5 lately. I've got an idea that involves showing a modal on page load, but it's not working. In the developer tools console, I'm seeing this error: Uncaught ReferenceError: bootstrap is not defined Here's what I've got so far: List view template {% block head %} {{ block.super }} <script> var test_modal = new bootstrap.Modal( document.getElementById('notification') ); test_modal.show(); </script> {% endblock head %} . . . {% if messages %} <div class="modal" id="notification" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {% for m in messages %}#} {{ m }} {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> Ok </button> </div> </div> </div> </div> {% endif %} I know the block.super and messages are working as I've tested these bits independently of setting this up together. I've tried putting the if messages in the modal-body but this doesn't seem to help. I was thinking that maybe the JS was being called before the template could get access to the objects. All the SO posts about this type of thing are super old and use jQuery and button triggers, both of which … -
Breaking for/if loops in HTML within Django
I am using HTML Templates in Django and searching through a list of objects. If one of them exists, I want to print something out. However, once that is printed. I do not want to print any more, even if more exist. (i.e. if the condition is met on one of the objects I want to print out the same thing I would if the condition is met on 100 of the objects) Here's what I have so far: {% for object in objects %} {% if object.attr1 == true %} Placeholder {% endif %} {% endfor %} If object.attr1 is true for any of the objects I want to print placeholder. But I only want to do it once. Difficulties within Django models have made it so that using this type of for loop is one of my only solutions. Is this possible? -
Populate Django username field with generated username
I would like the user name field for my Django registration to populate with the following function - def generateUsername(): username = firstname[0] + middlename[0] + lastname[0] + randomStringDigits(6) + getDateTimeStr() return username I am currently using the UserCreationForm model from Django and would prefer to find away to integrate into this, however if the best option is to custom my own user model then I am happy to do this also. views.py - def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) forms.py - class UserRegisterForm(UserCreationForm): email = forms.EmailField() firstname = forms.CharField(max_length=20) middlename = forms.CharField(max_length=20) lastname = forms.CharField(max_length=20) class Meta: model = User fields = ['email', 'firstname', 'middlename', 'lastname'] -
How to locally host a Django project?
I am trying to run a Django website, and I want the ability for all devices that are connected to the same router as my computer to be able to access the website. I have looked in several places, and questions like this, or this. Both approaches didn't work. I can access the website from my computer, but not from my cellphone, for example. (Both connected to 'X' network) I really don't know what to do since I can't find another answer, possibly because I am not searching for the question correctly, but I would love it if anyone could help me. -
STATICFILES_DIRS error when trying to migrate tables - django heroku
I've been trying to get my project up on Heroku for almost 2 days now! Worked through a lot of problems but now I can't seem to migrate the new database due to an error with static files. All of my pages on website are live and working except one page, I was getting a 500 error. I turned debug on to see what was going on and it needs the new database to be migrated. I run the command heroku run python manage.py migrate but am getting the following error: SystemCheckError: System check identified some issues: ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. Here is my relevant base-settings file: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) STATIC_URL = '/static/' # STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] and my prod settings:import os from .base import * import dj_database_url DEBUG = True ADMINS = [ ('name', 'email') ] try: SECRET_KEY = os.getenv('SECRET_KEY') except: print("Error getting key") ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { } } db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Any help would be greatly appreciated!! This has been a huge pain getting the website even able to deploy with … -
TypeError at /bokeh.html----join() argument must be str or bytes, not 'dict'
enter image description here bokeh.html view.py [2]: https://i.stack.imgur.com/XiEDm.png showing error -
Django Dynamic Settings
I am creating a portable Django server that will be used by different people on separate servers. Am I able to create dynamic settings for each user that they can change? For example Time Zone: instead of having TIME_ZONE = "America/New_York" in settings.py, can I have a settings page that allows them to update the configuration of the Django settings without them actually accessing the server? I also want to use this with Cors Headers for the CSRF_TRUSTED_ORIGINS = [] setting. Thank you. -
Need to know the required frameworks for project
I need to build a university portal website for my university project. In addition I also need to make a google chrome extension for taking auto attendance using webcam and also monitor browser traffics. This extension will be connected to the server. Right now I only know Django framework. Can someone please help me by telling which frameworks I need to learn to make this work. I've no experience. Thanks. -
Error when using encrypted SearchField as key for custom user model (Django): AttributeError: 'NoneType' object has no attribute '_meta'
I have followed this tutorial to customize the user model in my django app: https://testdriven.io/blog/django-custom-user-model/ The idea is to get rid of "username" and use "email" as the user key. I could follow the instructions and it worked allright, no problem. Apart from that, I need all my database fields to be encrypted (and, some of them, searchable). So I used this library: https://pypi.org/project/django-searchable-encrypted-fields/ And, also, no problem. I could encrypt my DB fields. The issue comes when I also try to encrypt my Django customUser's "email" field, by doing this: class CustomUser(AbstractBaseUser, PermissionsMixin): _email_data = fields.EncryptedCharField(max_length=100, blank=True) email = fields.SearchField(hash_key="94fd9321e57f061805...redacted...43d9485776dee73a", encrypted_field_name="_email_data", unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email This breaks my user model. After doing this, when I try to create a superuser I get this error (after typing the email address): (base) C:\Users\jaume\Desktop\Projects\repos\whistleblower>python manage.py createsuperuser Email: admin@admin.com Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, … -
I have a problem hosting my django website on Cpanel Console
enter image description here i get this error in my Cpanel. its a django website -
code working on jupyter-notebooks but indexing error in django
df = pd.read_csv('balancesheet.csv') c = df['TotalAssets'].values[-1] This is the code not really complicated but throws TypeError: string indices must be integers in django, working ok on jupyter-notebooks and python env, is it a version related issue ? i'm using python 3.7.9 and Django 2.2.17 -
Only one page loads running Django with Nginx and uWSGI - "504 Gateway time-out"
I'm running Django with Nginx and uWSGI. When I load up my app, it all looks fine, but then none of the other pages load. For instance, I load up my login page, and then after entering my username and password, the page just sits there loading. Not even any error messages. After around 2 minutes, I get a "504 Gateway time-out" page. I've already ruled out any problems with my authentication system, because I can turn off "@login_required" and each page loads (But again, I can't access other pages after loading up the initial page). I've also tried restarting the Docker container, switching around the ports, and checking that Nginx and my database are running. I get the following output after I run sudo docker-compose -f docker-compose-deploy.yml up --build: Building app Step 1/19 : FROM python:3.8-alpine ---> 64df5e2068e3 Step 2/19 : ENV PATH="/scripts:${PATH}" ---> Using cache ---> e76b22f5b7da Step 3/19 : COPY ./requirements.txt /requirements.txt ---> Using cache ---> fb7943523b91 Step 4/19 : RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers ---> Using cache ---> 5f8d10408c3a Step 5/19 : RUN pip install -r /requirements.txt ---> Using cache ---> c428d1ecd21c Step 6/19 : RUN apk del .tmp ---> Using … -
Amazon WS S3: I'm getting this error message: "The bucket you are attempting to access must be addressed using the specified endpoint."
how can I address the bucket using the correct endpoint? I'm using Django to create my app. -
what does hazard sign mean in sublime text?
I just write some codes in sublime text and when I try to save it some hazard sign appear beside the lines somebody knows what does it mean? -
Compare dates and times in Django
How to use comparative operators on date and time What is the problem in the example below? in models.py start_sale=models.DateTimeField(default=datetime.datetime(2018,5,3)) in views: time = datetime.datetime.now() in template: {% if course.start_sale|date < time.date and course.start_sale|time < time.time %} {% else %} {% endif %} this code dont show error but dont work dont compare datetime -
Save only a single element into a ManyToManyField
I have an app wich has a Meet and this meet could have only one guest or more than one guest. I defined Meet model with a ManyToManyField relationship with User and a field to choice if the meet is going to be with single guest or it'll be in a team (with many guests) as follow: class Meet(IndexedTimeStampedModel): kind_meet = models.CharField(max_length=50, choices=MEET_CHOICES) guests = models.ManyToManyField(User, related_name='guests') I did a form with Meet Model, so first the user select the kind of meet that he would like to do and on the next page he will select the guest or guests of the meeting. My fight is, if the user choose a single meet how can I force him to select just one guest on a select box in a template? On my ModelForm, I try to restrict this defining the widget of guests field as Select but ManyToManyField just accept a list of values and Select return the value as string not a list. This cause an error "Enter a list of values" when I submit the form. My second try was change the widget to SelectMultiple but this allow the user to select more than guest. class Meta: … -
At Django pagination template code <a href="?page=...">, why does url link start with "?page="?
At Django pagination template code <a href="?page={{page_obj.previous_page_number}}> why does url link start with ?page=? Why is there no root(?) url in this code? for example, at url pattern path('post/', views.PostLV.as_view(), name='post_list'), <a href="post/?page={{page_obj.previous_page_number}}> I think post/?page=... is right than ?page=. -
How to prevent Django from renaming key column in model with managed=False?
I have two models in Django with managed=False, because they are generated by SQL. Django's Querysets based on these models do not generate the SQL queries they should. They add an '_ID' suffix to a column name that I never specified. This causes the queries to fail. The models: class MaterialsPerBatch(models.Model): BATCH = models.CharField(null=False, max_length=255) MATERIAL = models.ForeignKey('ColumnsPerMaterialStatic', on_delete=models.CASCADE) class Meta: db_table = "CDH_MATERIALS_PER_BATCH" managed = False class ColumnsPerMaterialStatic(models.Model): MATERIAL = models.CharField(primary_key=True, null=False, max_length=255) MATERIAL_LINK = models.CharField(null=False, max_length=255) class Meta: db_table = "CDH_COL_PER_MAT_STATIC" managed = False I want to filter the first model by BATCH, and find all corresponding second models that share the MATERIAL field. The query looks like this: qs = models.MaterialsPerBatch.objects.filter( BATCH__in=['foo', 'bar']).values('BATCH', 'MATERIAL__MATERIAL_LINK') I get this error: "django.db.utils.DatabaseError: ORA-00904: CDH_MATERIALS_PER_BATCH"."MATERIAL_ID": invalid identifier" Inspecting qs.query shows that Django runs the following query in the background: SELECT "CDH_MATERIALS_PER_BATCH"."BATCH", "CDH_COL_PER_MAT_STATIC"."MATERIAL_LINK" FROM "CDH_MATERIALS_PER_BATCH" INNER JOIN "CDH_COL_PER_MAT_STATIC" ON ("CDH_MATERIALS_PER_BATCH"."MATERIAL_ID" = "CDH_COL_PER_MAT_STATIC"."MATERIAL") WHERE "CDH_MATERIALS_PER_BATCH"."BATCH" IN ('foo', 'bar') So the question is, why does Django turn "CDH_MATERIALS_PER_BATCH"."MATERIAL" into "CDH_MATERIALS_PER_BATCH"."MATERIAL_ID"? I never specified any '_ID' suffix. How do I tell Django not to add that suffix? -
Generate automatic username for user upon registration using their input and my python script
I have a Django project set up with the basic User Registration models set up as standard. My user database currently collects a username, email and password on registration. I would like to make it so that the username is generated for the user automatically and stored with the email and password in my database. I have how the I'd like to generate this username with the below python script - import random import string import datetime def getFirstInitial(): firstInitial = firstName[0] return firstInitial def getMidInitial(): middleInitial = middleName[0]; return middleInitial def getLastInitial(): lastInitial = lastName[0] return lastInitial def createUsername(): username = getFirstInitial() + getMidInitial() + getLastInitial() + randomStringDigits(6) + getDateTimeStr() firstName = input(); middleName = input() or "0"; lastName = input(); createUsername() My current user forms.py - from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() firstname = forms.CharField(max_length=20) middlename = forms.CharField(max_length=20) lastname = forms.CharField(max_length=20) class Meta: model = User fields = ['email', 'firstname', 'middlename', 'lastname'] My current user views.py - from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() … -
Django looks in `templates` when loading static file
I am new to Django and I have the following issue: when I try lo link my layout.html to styles.css Django looks in the wrong place. The layout.html code which reads: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css'}" rel="stylesheet"> </head> and the structure of my encyclopedia dir is as follows: ├── db.sqlite3 ├── encyclopedia │ ├── __init__.py │ ├── __pycache__ │ ... │ ├── models.py │ ├── static │ │ └── encyclopedia │ │ └── styles.css │ ├── templates │ │ └── encyclopedia │ │ ... └── search.html │ ├── tests.py │ ├── urls.py │ ├── util.py │ └── views.py ├── manage.py └── wiki I did check the `settings.py` file in dir `wiki` and it does have a: `STATIC_URL = '/static/'` line. Yet Django keeps looking in `templates` as per the following error message: [![error message from VS Code][1]][1] Can anyone tell me what I am doing wrong? [1]: https://i.stack.imgur.com/SoBYv.png -
DRF How to structure urls for photo sharing web app? (Structure/Best practice)
Currently building backend API using Django Rest Framework for a group photo-sharing project. I'm trying to understand what's the best way to structure my API endpoints and I've encountered a problem (more like a question) for the best way to implement it. Here are my models: class Photo(models.Model): uploader = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="photos" ) image = models.ImageField(upload_to=get_image_path) upload_date = models.DateField(auto_now_add=True, editable=False) class Collection(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=500, blank=True) thumbnail = models.ImageField(blank=True) creator = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="created_collections" ) members = models.ManyToManyField(CustomUser, related_name="collections") photos = models.ManyToManyField(Photo, related_name="collections") Basically each user can create a Collection model which holds different photos he can share with others and they can upload too. The endpoints I have right now are the basic ViewSet ones: Photo: /api/photo GET/POST /api/photo/id GET/DELETE/PATCH Collection: /api/collection GET/POST /api/collection/id GET/DELETE/PATCH My question is: What should be the endpoint for a user to add a photo to a collection? (the best way to implement it) I've thought of a few options which are: 1.POST request to /api/collection/id containing the ID of the photo I want to add. 2.POST request to /api/photo/id containing the ID of the collection I want to add the photo to. 3.Using a PATCH method maybe? … -
How to implement concurrent requests rate limit at client side
My python/django distributed application has to integrate with a third party api which has a restriction of say 20 concurrent requests per minute. It blocks us for a specified period of time if we exceed this limit. How do we implement this limit in our application so that we do not end up making more than 20 concurrent requests to the client. We have been able to implement per min or per hour based rate limit using redis but I am not sure how to achieve this concurrent requests issue. Is this possible to achieve this using redis ?