Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create multiple entries for one model in a Django modelform
Sorry if the title is confusing, I can't really think of how else to word it. I am creating a site where there are many quizzes. Each Quiz model class Quiz(models.Model): name = models.CharField(max_length = 80) description = models.CharField(max_length = 300) num_questions = models.IntegerField(default = 10) slug = models.SlugField(max_length = 20) img = models.URLField(blank = True) # allow it to be none def __str__(self): return self.name def get_questions(self): return self.question_set.all() looks like this... and it has some attributes like name, description, etc. There are many Question models that have ForeignKey to one Quiz: class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete = models.CASCADE) img = models.URLField(blank = True) # allow none` content = models.CharField(max_length = 200) def __str__(self): return self.content def get_answers(self): return self.answer_set.all() and then there are some Choice models that have ForeignKey to one Question: class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) content = models.CharField(max_length = 200) correct = models.BooleanField(default = False) Now. I want to create one single ModelForm from which I can create 1 quiz record, and then 10 question records with 4 choice records per question. It would be very nice if they could automatically set their foreignkey to the Question that is being created. How … -
How can I have separate trigger and filter conditions in a Django UniqueConstraint?
Given the following models: class Customer(models.Model): pass class User(models.Model): email = models.EmailFIeld(blank=True, default="") customer = models.ForeignKey(Customer, ...) I want to enforce the following: IF user has email IF user has customer email must be globally unique IF user has no customer email must be unique within the user's customer I attempted to implement this with two UniqueConstraints: UniqueConstraint( name="customer_scoped_unique_email", fields=["customer", "email"], condition=( Q(customer__isnull=False) & ~Q(email=None) ), ), UniqueConstraint( name="unscoped_unique_email", fields=["email"], condition=( Q(customer=None) & ~Q(email=None) ), ), Testing has revealed that this still allows a user without a customer to be created with an email identical to an existing user (with a customer). My understanding is that this is because UniqueConstraint.condition determines both when the unique constraint should be triggered and what other records are included in the uniqueness check. Is there any way to achieve my desired logic in the database, ideally in a Django ORM-supported way, and ideally with a UniqueConstraint or CheckConstraint? This must occur in the database. It's obviously possible in Python, but I want the extra reliability of a database constraint. -
Should i use Django DRF or Flask RESTful to write a backend for NextJS frontend and firebase database
Hi Guys i'm developing a website for real-state agent the website would have login functionality for users to login and leave reviews for the listings and also has an admin page for him to add listings from xml files. i decided to do the frontend in nextjs but i'm not sure which framework to choose to develop the backend with firebase database -
Django - "The MEDIA_URL setting must end with a slash." error causes issues for setting file path in Windows
So if you set MEDIA_URL under settings.py without a forward slash (this thing /, you can't do backward slashes I've tried) at the end you get ERRORS: ?: (urls.E006) The MEDIA_URL setting must end with a slash. The issue with this is if I want to store files locally for tests and have the front-end retrieve it for testing locally. If you're on Windows specifically if you set MEDIA_URL=os.path.join(BASE_DIR, 'media/') you get double backwards slashes between directories like so: '/C:\\Users\\Blah\\Documents\\media/videos\\user_6badb4b8-33ba-4bb9-aa9a-2e3afb359960\\2de754bd-644e-466b-8dbb-e4d47a90aaee.mp4' As you can see there's that one forward slash in after media amongst all the double backward slashes, that might cause issues when looking for that address, but if you're running on mac it'll use forward slashes instead which is fine. How can you circumvent this so that you get consistently slashed paths that can be rendered by an image or video components in React Native, when developing on Windows? -
How many separate apps should I have with my Django app
How many apps should I have in my Django project. For instance, I am building a pet application where there can be owners, pets, veterinarians, etc. For now sticking to only the 3 I mentioned should I have these as separate apps within my Django project or should I just create one app to handle everything. I will be adding more features as time goes on. The idea I had was to create a project django-admin startproject mypets Then create an application for each: python manage.py startapp pet and python manage.py startapp pet_owner and python manage.py startapp veterianarian As I mentioned before, there are other features I will be adding to my application like photos todo like feature and so on. My concern is that my project is going to get big which is why I want to separate pet_owner and pet each as their own apps. I was thinking this is exactly what I should do but then realized that when I went to mypets.urls.py file and I was thinking about forwarding some requests to a path I quickly realized that I want my route to always have mypets/. urlpatterns = [ path('admin/', admin.site.urls), path('mypets/petowner/', include('petowner.urls')), path('mypets/pet/', include('pet.urls')), ] … -
How to retrieve the data from the database and display it in a textbox for users to update it
I have a webpage where it is supposed to allow users to update the data from the database but the data is unable to display in the textbox, how do I make it able to display it in the textbox? This is my current webpage where the users need to manually type in all the data they want to update inside the text box. What I wanted is like this, the data is already retrieve from the database for the users to see, and let say they want to update the customer name, they just need to chnage the customer name and click on the submit button to update it, how do I make it able to retrieve the data? views.py @login_required() def updatedata(request, id): photo = Photo.objects.get(id=id) if request.method == 'POST': Photo.mcoNum = request.POST.get('mcoNum') Photo.reception = request.POST.get('reception') form = UpdateForm(request.POST) if form.is_valid(): form.save() return redirect('logdata') else: form = UpdateForm return render(request, 'updatedata.html', {'form': form}) updatedata.html <!doctype html> {% extends "home.html" %} {% block content %} {% load static %} <br><br> <h2 class="text-center">Edit Log Data</h2> <hr> <div class="col-md-6 offset-md-3"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update" class="btn btn-secondary"> </form> </div> {% endblock %} forms.py class UpdateForm(forms.ModelForm): … -
Django 3 tier architecture [duplicate]
I'm working on a project and i'm not sure if Django is a 3 tier (Not same as MVC), so Does Django follow the three-tier architectural design pattern? -
DRF: How to set a correct view_name with the action decoration in a viewset
I have the next action decorator method, I pretend to filter the teachers on the model: @action(detail=True, methods=(['GET'])) def get_teachers_by_area(self, request, pk=None): teachers = self.get_serializer().Meta.model.objects.get_teachers_by_area(pk=pk) if teachers: teacher_serializer = TeacherByAreaListSerializer(teachers, many=True) return Response( { 'ok': True, 'conon_data': teacher_serializer.data }, status=status.HTTP_200_OK ) else: return Response( { 'ok': False, 'detail': 'No se encontró el Área de Conocimiento.' }, status=status.HTTP_400_BAD_REQUEST ) The files of the urls are next: Router.py router = routers.DefaultRouter() router.register( r'school-period', SchoolPeriodViewSet, basename='school_period' ) router.register( r'knowledge-area', KnowledgeAreaViewSet, basename='knowledge_area') urlpatterns = router.urls Urls.py path('user/api/', include('applications.users.routers')), path('school/api/', include('applications.school.routers')), And the Serializers.py of the model is next: class KnowledgeAreaSerializer(serializers.HyperlinkedModelSerializer): teachers = serializers.HyperlinkedRelatedField( view_name='knowledge_area-detail', read_only=True, ) I just pretend return the data (teachers) like an url with the action decorator mentioned before: def to_representation(self, instance): data = super().to_representation(instance) return { 'id': instance.id, 'name': instance.name, 'coordinator': { 'id': instance.coordinator.person.id, 'name': instance.coordinator.person.full_name() }, 'sub_coordinator': { 'id': instance.sub_coordinator.person.id, 'name': instance.sub_coordinator.person.full_name() }, 'objective': instance.objective, 'observations': instance.observations, 'teachers': instance.teachers, 'created_at': instance.created_at } But the problem is that I could not indicate the correct URL of the action method, I did a lot of research but did not find anything about it or with the same requirements. Thanks for helping me by the way. -
django DoesNotExist admin panel good
I have an issue that the try except block. So the admin panel shows entry into the tables but when I run the following piece of code, it goes in the exception handling part try: visitors = Owner.objects.exclude(user=request.user).filter(checked_in=True).count() current = Owner.objects.get(user=u) friends = Friendship.objects.filter(Q(from_friend = u) | Q(to_friend = u)) except Owner.DoesNotExist: print(visitors) visitors = None The code hits the except part and prints the value of visitors as if it exists but then why it calculates that the Owner does not exist , I do not understand. -
How to convert this function to make it function?
I am using this function in upload_to= in models.py: def uuid_profilepicture(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) now = datetime.now() return os.path.join(f'profilepicture/{now.year}/{now.month}/{now.day}/', filename) How can I make it generic function, so I can pass different param for the folder name? -
Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P<id>[0-9]+)/$']
I have a web page where it allows the users to update the existing data from the database, but when i click on the update button, it suppose to redirect the users to the next page but instead I got this error: Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P[0-9]+)/$'], any idea on how to fix this issues? traceback error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/updatedata/5/ Django Version: 3.1.4 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms', 'channels'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template E:\Role_based_login_system-master\templates\home.html, error at line 0 Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P&lt;id&gt;[0-9]+)/$'] 1 : &lt;!doctype html&gt; 2 : &lt;html lang="en"&gt; 3 : &lt;head&gt; 4 : &lt;!-- Required meta tags --&gt; 5 : &lt;meta charset="utf-8"&gt; 6 : &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; 7 : 8 : &lt;!-- CSS --&gt; 9 : {% load static %} 10 : &lt;link rel="stylesheet" href="{% static 'style.css' %}"&gt; Traceback (most recent call last): File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view … -
Django ORM How to force using LEFT JOIN for Foreign key
Just another question about "How to not use raw queries?" I have two models: class User(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) soname = models.CharField(max_length=100) group = models.ForeignKey('Group', on_delete=models.PROTECT) class Group(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) Only one User with id=5 has Group (it's important). I need to implement query like this (using LEFT JOIN): SELECT * FROM User LEFT JOIN Group ON Group.id = User.category WHERE User.name LIKE '%test%' OR User.soname LIKE '%test%' OR Group.name LIKE '%test%' And i want to get all records, even with Users without Groups. But if i try to use this: _res = User.objects.filter( Q(name__icontains='test') | Q(soname__icontains='test') | Q(group__name__contains='test') ) I get only one record with id=5, because ORM generate query with INNER JOIN. Can anyone tell me if there is an easy way to get Django ORM to use LEFT JOIN without building complex constructs, writing your own query builder, and using raw queries? -
Update profile picture through clicking on picture itself Django
I'm trying to find some info online on how to update my user's profile picture on the profile page in the same way that social media applications do it, i.e. by clicking on the profile picture itself and getting asked for the file upload straight away. However, all I'm finding online is options to create a form to do that job, but then it's going to be an upload button that does the job, which isn't the same? How do I get this done: how do I get the image to be clickable and to open a file upload after I click it that would then update my model ImageField? Thanks! -
django.db.transaction.TransactionManagementError: cannot perform saving of other object in model within transaction
Can't seem to find much info about this. This is NOT happening in a django test. I'm using DATABASES = { ATOMIC_REQUESTS: True }. Within a method (in mixin I created) called by the view, I'm trying to perform something like this: def process_valid(self, view): old_id = view.object.id view.object.id = None # need a new instance in db view.object.save() old_fac = Entfac.objects.get(id=old_id) new_fac = view.object old_dets = Detfac.objects.filter(fk_ent__id__exact = old_fac.id) new_formset = view.DetFormsetClass(view.request.POST, instance=view.object, save_as_new=True) if new_formset.is_valid(): new_dets = new_formset.save() new_fac.fk_cancel = old_fac # need a fk reference to initial fac in new one old_fac.fk_cancel = new_fac # need a fk reference to new in old fac # any save() action after this crashes with TransactionManagementError new_fac.save() I do not understand this error. I already created & saved a new object in db (when I set the object.id to None & saved that). Why would creating other objects create an issue for further saves? I have tried not instantiating the new_dets objects with the Formset, but instead explicitely defining them: new_det = Detfac(...) new_det.save() But then again, any further save after that raises the error. Further details: Essentially, I have an Entfac model, and a Detfac model that has a … -
PostgreSQL (Django - Production ) - Function similarity(character varying, unknown) does not exist
I just hosted my Django website on pythonanywhere with paid account. I am using Postgresql database, Everything is working fine but TrigramSimilarity is not working. In local host everything is working fine but in production it gives error. kindly help me , i have been searching but haven't found anything. Thanks in advance. Error: Exception Value: function similarity(character varying, unknown) does not exist -
<link rel="preconnect" href="{% static 'css/custom.css' %}" type="text/css"> css don't load
It can be a silly question but in django I am using s3bucket and cloudfront to serve my static files.I am trying to use preconnect but when I use preconnect CSS don't load. <link rel="preconnect" href="{% static 'css/custom.css' %}" type="text/css">. -
Running out of quotation marks. (Django statics with document.write)
This element: <img id="img" src="{% static 'pd.jpg' %}" /> should go here: popup.document.write("<img src={% static 'pd.jpg' %} />") So think i need a third kind of quotation marks, or ? popup.document.write(String(<img src="{% static 'pd.jpg' %}" />)) at least is not working. -
Django Class Based Views Forbidden (Referer checking failed - no Referer.) - webhook
I have made a class based view to act a webhook but whenever a request comes in I get Forbidden (Referer checking failed - no Referer.): /gc_callback/ I do have the csrf_exempt decorator for dispatch but it seems it does nothing def dispatch(self, *args, **kwargs): return super(Webhook, self).dispatch(*args, **kwargs) Any suggestions? -
Django ModelForm - ManyToMany nested selection
I'm building a Django application and I'm facing an issue I don't know how to solve... I'll try to explain it as clear as I can. I've got an app called "Impostazioni" which has a model called "AnniScolastici": class AnniScolastici(models.Model): nome = models.CharField(max_length=50) class Meta: verbose_name = "Anno scolastico" verbose_name_plural = "Anni scolastici" def __str__(self): return f"{self.nome}" I also have another app called "Attivita" which has a model called "Laboratori": class Laboratori(models.Model): nome = models.CharField(max_length=25) durata = models.IntegerField(default=0) anniscolastici = models.ManyToManyField(AnniScolastici) note = models.TextField(null=True, blank=True) class Meta: verbose_name = "Laboratorio" verbose_name_plural = "Laboratori" def __str__(self): return f"{self.nome}" I've coded up another model called "RichiesteLaboratori" which is related to different models in my Django app (and on the two above, of course): class RichiesteLaboratori(models.Model): date_added = models.DateTimeField(auto_now_add=True) date_valid = models.DateTimeField(null=True, blank=True) provincia = models.ForeignKey("impostazioni.Province", related_name="richiesta_provincia", null=True, on_delete=models.CASCADE) istituto = models.ForeignKey("contatti.Istituto", related_name="richiesta_istituto", null=True, on_delete=models.CASCADE) plesso = models.ForeignKey("contatti.Plesso", related_name="richiesta_plesso", null=True, on_delete=models.CASCADE) classe = models.CharField(max_length=25) numero_studenti = models.PositiveIntegerField() nome_referente = models.CharField(max_length=50) cognome_referente = models.CharField(max_length=50) email = models.EmailField() telefono = models.CharField(max_length=20) termini_servizio = models.BooleanField() classi_attivita = models.ManyToManyField(AnniScolastici, related_name="richiesta_anniScolastici") laboratori = models.ManyToManyField(Laboratori) note = models.TextField(null=True, blank=True) approvato = models.BooleanField(default=False) class Meta: verbose_name = "Richiesta - Laboratorio" verbose_name_plural = "Richieste - Laboratorio" def __str__(self): return f"{self.pk}" I'm … -
POST method doesn't recieve any information from Form (DJANGO & BOOTSTRAP)
I have a form which registers a new user, I used Bootstrap 5 to make it look nice. However, when I press the submit button the form does not validate. The error it shows when I write print(form.errors) says that every field is required, which means it didn't recieve anything. Why does this happen? This is my code: HTML <div class="card" id='signup_card'> <div class='card-header'> <h2 class='card-title'>Sign Up</h2> </div> <div class='card-body'> <form method='POST' action="" id='create_user_form' style="color: #fff;"> {% csrf_token %} <label for='usernameInput' class="form-label">{{form.username.label}}:</label> <input type="text" id='usernameInput' style="margin-bottom: 20px;"> <label for='phoneNumberInput' class="form-label">{{form.phone_number.label}}:</label> <input type="text" id='phoneNumberInput' style="margin-bottom: 20px;"> <label for='emailInput' class="form-label">{{form.email.label}}:</label> <input type="text" id='emailInput' style="margin-bottom: 20px;"> <label for='password1Input' class="form-label">{{form.password1.label}}:</label> <input type="text" id='password1Input' style="margin-bottom: 20px;"> <label for='password2Input' class="form-label">{{form.password2.label}}:</label> <input type="text" id='password2Input' style="margin-bottom: 20px;"> <button class="btn btn-primary" type='submit'>Submit</button> </form> </div> models.py class Account(User): phone_number = BigIntegerField() forms.py class CreateAccountForm(UserCreationForm): class Meta: model = Account fields = ['username', 'email', 'phone_number', 'password1', 'password2'] views.py def signup(request): if request.method == 'GET': form = CreateAccountForm() ctx = { 'form':form } return render(request, 'signup.html', ctx) if request.method == 'POST': form = CreateAccountForm(request.POST) if form.is_valid(): form.save() else: print(form.errors) return render(request, 'index.html') -
Python Environ Django - How to specify to read a different dot env file for dev, test and prod?
Background As I am getting ready for Django deployment to production, I realized that I need to split my settings.py file into different environments. I am trying to have each environment's settings file read a different .env file for that specific environment. Like such: As seen in the documentation # website.settings.dev from .common import * import environ env = environ.Env() # Take environment variables from .env file environ.Env.read_env('.env.dev', recurse=False) print(env('SECRET_KEY')) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ... Issue The .env.dev file is never read and my SECRET_KEY env variable is never loaded onto the system, with python manage.py check, I get the following: File "C:\website\settings\dev.py", line 10, in <module> print(env('SECRET_KEY')) File "C:\project\virtual-env\lib\site-packages\environ\environ.py", line 165, in __call__ return self.get_value( File "C:\project\virtual-env\lib\site-packages\environ\environ.py", line 361, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable (virtual-env) PS C:\project> However, if I were to rename my .env file back to .env and read the file with environ.Env.read_env() Everything works, and my print statement prints out my secret key. Question Why can't environ read the specified file? How to specify a file for … -
How do I reference my model in a nested folder structure to dump data in Django 3.2?
I'm using Django 3.2 and Python 3.9. I have this project directory setup + cbapp - manage.py - settings.py + models - __init__.py - crypto_currency.py In my settings.py file, I have INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cbapp', ] I want to dump some data to a fixtures file, so I tried $ python3 manage.py dumpdata cbapp.models.crypto_currency > ./cbapp/fixtures/crypto_currency.json CommandError: No installed app with label 'cbapp.models.crypto_currency'. What's the proper way to reference my model to dump data? -
How to load editorJs scripts integrated with django after an ajax call?
I am using editorJs for my description field as follows: epic_description = EditorJsField( editorjs_config={ "tools": { "Image": { "config": { "endpoints": { "byFile": "/imageUlaod/", "byUrl": "/imageUlaod/", }, "additionalRequestHeader": [ {"content-Type": "multipart/form-data"} ], } }, "Attaches": { "config": { "endpoint": "/fileUPload/", } }, } }, blank=True, null=True, ) But I also call this form of this field via ajax to load it. And it turns out that the script for the editorJs is not loaded at all. When I looked to my console it uses the cdn url https://cdn.jsdelivr.net/sm/jsdelivr-separator.js. Now I have no idea how to solve this issue since I do not know what script to load in the first place I check at the url to see if I can download the js file. Eiih nothing. Any help would be appreciated highly. -
'WSGIRequest' object has no attribute 'get'... API link from google
I am trying to use the Books APIs from google to import books to the website and save them in the database. Unfortunately, I have a problem with the get method and I don't know where the problem is. I get an error like in the subject. search_url = "https://www.googleapis.com/books/v1/volumes?q=search+terms" params = { 'q': 'Hobbit', 'key': settings.BOOK_DATA_API_KEY } r = request.get(search_url, params=params) print(r.text) return render(request, "BookApp/book_import.html")``` -
Trouble starting Django project w/o errors
This is the original code in urls.py. Similarly, errors in view.py, and the app url.py files automatically appear whenever I start a project in django (3.2.8). I've just begun coding, no one I've asked can answer why. HELP! from django.contrib import admin from django.urls import path