Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ReCAPTCHA with Model Form
I have a ModelForm like so: # forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ['email', 'title', 'language', 'file'] labels = { 'email': 'E-Mail', 'title': 'Video Title', 'file': 'Attach File' } I am trying to add ReCAPTCHA functionality like so: # forms.py from captcha.fields import ReCaptchaField class UploadForm(forms.ModelForm): captcha = ReCaptchaField() class Meta: model = Upload fields = ['email', 'title', 'language', 'file'] labels = { 'email': 'E-Mail', 'title': 'Video Title', 'file': 'Attach File' } However, whenever I view this form, there is no Captcha field, from what I suspect is Django only taking in the fields from the ModelForm. How do I tell Django to also add the Captcha field? Project settings for good measure NSTALLED_APPS = [ 'about.apps.AboutConfig', 'users.apps.UsersConfig', 'content.apps.ContentConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'storages', 'captcha' ] # ReCAPTCHA for forms RECAPTCHA_PUBLIC_KEY = '*****' RECAPTCHA_PRIVATE_KEY = '***** -
Setting up a detail view in Django
I'm new to Django and learning about creating apps and projects. Recently I've set up a view and everything appears to be working but I'm wanting to set up a detailed view for each object. I'm getting the following error Invalid block tag on line 11: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag? {% extends "layout.html" %} 2 {% block title %}{{course.title}}{% endblock %} 3 {% block content %} 4 <article> 5 <h2>{{course.title}}</h2> 6 {{ course.description }} 7 <section> 8 {% for step in course.step_set.all %} 9 <h3>{{ step.title }}</h3> 10 {{ step.description }} 11 {% endblock %} 12 </section> 13 </article> 14 {% endfor %} -
How to link one app detail page with a link redirect to another app detail page?
I'm new to Django. I have a question about link one app detail page with a link redirect to another app detail page. I have 2 apps. The first app I have to show all the singer's information. The second app is to display the singer's event information. And I want to When I choose to click to see the singer's information It will display information, music, videos, including events, and when I click on an event I would like it to be linked to on that event's details page on the second app. What should I do? I want to know which app should I create the URL? app singer : urls.py urlpatterns = [ path("singer", views.PlayerListView.as_view(), name="singers"), path("singer/<str:slug>", views.PlayerDetailView.as_view(), name="singer"), ] views.py class SingerDetailView(DetailView): model = Singer def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["event"] = Event.objects.filter(singer=self.object) return context singer_detail.html {% for events in event %} <div> <a href="..............................."> <img src="src="{% static "img/events.png" %}"> <p>{{ events .name }}<p> </a> /div> {% endfor %} When I click the link on the singer_datail page I want it to display information of Events I clicked on the event_detail page app event : urlpatterns = [ path("events/", EventListView.as_view(), name="eventlist"), path("events/<str:slug>/", EventDetailView.as_view(), name="event"), ] … -
How to create/implement messages in django for when user registration input data is invalid?
I have a form in django that inherits from UserCreationForm (the only addition is that it asks for an email by default as well). I have manually entered input html into the template instead of just using {{ form }} so I have more customization over how it looks. The form works fine and I can create users with it, the issue I have is I can't seem to be able to get messages to work for when user data input does not meet the required criteria (e.g passwords don't match, username already exists, etc.). Since I am not using {{ form }} those messages aren't coming through automatically. Is there a way I can easily bring in the default messages from the django form? Or if not how can I create my own messages. I've tried a few things like what I have below: EDIT: Maybe I should mention that my messages do come through and display in the HTML, but the conditionals I try to use don't work as intended. My django form: class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] My view: def registerPage(request): form = CreateUserForm() if request.method == 'POST': form … -
Django ORM Filtering inside db functions returning multiple duplicate rows
I have to list all clients and annotate them total amount of loan and payments inside of one sql query. I tried it with next fragment of code: clients = Client.objects.all().order_by('fullname').annotate( loans_total=ArrayAgg( 'sales__loan', filter=Q(Q(sales__created__gte=start_date) & Q(sales__created__lte=end_date)) ), payments_total=ArrayAgg( Case( When(payments__amount_currency="SUM", then=F('payments__amount') / F('payments__rate')), default=F('payments__amount'), output_field=FloatField() ), distinct=True, filter=Q(payments__created__gte=start_date) & Q(payments__created__lte=end_date) ), ) but it returns multiple duplicated records of rows and result of their sum is multiplied by 30 in this case; -
Django Query Reversed StartsWith
I have a model that contains folder path , and I want to get directories which contains an exact path. This is my model : class Directory(models.Model): name = models.CharField(max_length=5) path=models.CharField(max_length=100) In this model; name field is allways somethng like this "A" or "ZDCF" Naming rule is simple : a uniqeu char by using least character ( A, B, ....Z, AA, AB...) Path names have two simple rules : Always finishes with a dot "." Sum of upperside paths "A.B." And this is what I want : I want to select all upperside directories that contains a specific directory path. I will try to explain with an Image : Lets say these circles are my directories. In this example I picked the 'D' named directory and want to get upper directories "C" , "B" and "A". I dont't want to get 'E' , 'F' , 'G' , 'H' and 'J' named directores. If I use this code : myDir = Directory.objects.get(name='D') listDir = Directory.objects.filter(path__startswith=myDir.path) listDir QuerySet will contains 'E' , 'F', 'G' , 'H' and 'J'. But I don't want them. And if I use this code : myDir = Directory.objects.get(name='D') listDir =[] for xDir in Directory.objects.all(): if myDir.path.startswith(xDir.path): listDir.append(xDir) … -
Inserting data in django
I have this code in views where data inserted V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname,Old_Student=old,New_Student=new, Payment_Type=payment,ESC_Student=esc,Last_School_Attended=last,Address_OF_School_Attended=add, Education_Levels=educationlevel,School_Year=schoolyear,Courses=course,strands=strands,Student_Types=stype ) V_insert_data.save() studentenrolment = StudentsEnrollmentRecord.objects.filter(id=V_insert_data) return render(request, 'accounts/print.html', {"studentenrolment":studentenrolment} ) I don't know what is wrong with this code, can somebody help me to configure this ? I just want that after the record inserted I can get the id and print it to the another html. I received this error -
Asgi deployement to ubuntu using django, nginx, daphne always results in 502 Bad Gateway
I had a working django server and then after adding channels i had to use asgi and i did so by following this tutorial which didnt work then i referred to the official deployement documentation But no luck always 502 Bad Gateway supervisor config [program:project_name_asgi_daphne] directory=/home/ubuntu/Lamar/ command=/home/ubuntu/env/bin/daphne -u /home/ubuntu/Lamar/daphne.sock --root-path=/home/ubuntu/Lamar/ walidproject.asgi$[program:project_name_asgi_workers] command=/home/ubuntu/env/bin/python /home/ubuntu/Lamar/manage.py runworker process_name=asgi_worker%(process_num)s numprocs=1 environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 autostart=true autorestart=true redirect_stderr=True stopasgroup=true nginx config upstream channels-backend { server 0.0.0.0:8000; } server { listen 80; server_name 35.178.143.19; location /static/ { autoindex on; alias /home/ubuntu/Lamar/main/static/; } location /media { autoindex on; alias /home/ubuntu/Lamar/media/; } location / { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } -
is it possible to 'measure' level of nestedness of a django model instance
I have a Comment model that have a Parent field which is a ForeignKey to itself: so users can comment on comments etc. Is it possible for a specific item to get its level of nestedness: which is a number of parents till the last one which has no parent (but has a post field non-empty)? I mean it is relatively easy to do just with a recursive function, but I wonder if there is a more efficient instrument using perhaps Django queries? -
Is django is only for the local machine? If not how do you turn it to a real website?
Why you can go to the Django web only from your machine? How to get a real http link? -
insert an object for all my objects in a model django
I want to add a new object from a model to all my model's objects Example: I have a model Train which has many trains in it. Now I have another Model Car which has 6 cars. I want all my trains in the Train model to have the 6 cars in it. In fact, If I would like to add, by using the admin interface, a new car (car 7), I would like all my trains to have it without having to select all the trains. Also, if I want to add a new train, I should have the 6 cars in it directly without having to go in the model Car and add the new train. I have declared my models as the following: class Train(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Car(models.Model): train = models.ManyToManyField(Train) name = models.CharField(max_length=200) def __str__(self): return self.name I can't make this work, please help me.... -
Django templates. Any way to nest {{ }} in {% %}?
I am working with a Django templates. I want to pass a variable to my template called js_files which is a list of JavaScript files that I want to add to the end of the HTML. For example, here is a sample js_files array: js_files = ['fancy_dialog.js', 'animate_everything.js'] In my Django template, I would like to be able to do something like this: {% for js_file in js_files %} <script src="{% static '{{ js_file | safe }}' %}"></script> {% endfor %} This is what I get: <script src="/static/%7B%7B%20js_file%20%7C%20safe_file%20%7D%7D"></script> <script src="/static/%7B%7B%20js_file%20%7C%20safe_file%20%7D%7D"></script> This is what I desire: <script src="/static/fancy_dialog.js"></script> <script src="/static/animate_everything.js"></script> The syntax "{{ js_file | safe }}" does exactly what I want it to. But I cannot summarily wrap that value with "{% static 'JS-FILE-VARIABLE-HERE' %}". It doesn't nest. Anyway to do this? -
Django Reset auto-increment
So I have a Django application going and in my models.py I have a field that has models.AutoField(primary_key=True). I went into the admin site and deleted some rows off the table, yet when creating a new object the auto-incremented value picked up where it left off instead of going back to 1. Is there any way I can reset this? I've already tried removing the field, running my migrations, then adding my field back. -
Python command doesnt work for me in Terminal
when i try to run some django command from the terminal i have no response ! here the image for illustrate that! Image of the terminal -
Django exclude filed__in not filtering data
So i have this query data_list = ModelOffice.objects.values_list('office_name',flat=True) data = ModelPerson.objects.filter().exclude(flag=1,office_name__in=data_list) i want to pick a person that not have office in ModelOffice, but it still pick it -
How do I stop a resource from appearing in list view in django rest framework
I've done some work following the django rest framework tutorial. I would like to add the ability to make a snippet private, so that no other users can see it. I created an extra field to the snippet and I have tried to implement this using object permissions. It works in that it stops other users from seeing it in the detail view (403 forbidden) but it still shows the snippet in the list view, with all of it's fields in the open. How do I stop an resource from showing in the list view? I have a model like so: class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) ... private = models.BooleanField(default=False) serializer: class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField( view_name='snippet-highlight', format='html') class Meta: model = Snippet fields = ('url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style', 'private') Viewset: class SnippetViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = ( permissions.IsAuthenticatedOrReadOnly, SeeSnippet, ) @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) def highlight(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) def perform_create(self, serializer): serializer.save(owner=self.request.user) permission: class SeeSnippet(permissions.BasePermission): """ Custom permission to only allow owners … -
How can I refer to a html in css?
I'm developing a python website, and I have some files, home.html that the content is: {% extends "layout.html" %} {% block content %} <h1>This is the main page</h1> {% endblock %} And the layout is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</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 rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Python</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{{ url_for('about') }}">About</a> </li> <li class="nav-item"> <a class="nav-link" href="{{ url_for('login') }}">Login</a> </li> </ul> </div> </nav> {% block content %} {% endblock %} </body> </html> And I have some html files more, but I want to refer from css file to some label of any html file. Like .body [html="home.html]{ backgroud: red; } -
django inherited model that has the same pk as the parent
I have two models, one inherits from the other. Both are database tables. When creating an instance of the inherited model I want it to have the same pk value as the parent. But, for some reason, it looks like when they have the same pk, the inherited instance keeps updating as the parent updates. For example: class ModelA(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True) title = models.CharField(max_length=1000) revision = models.IntegerField(default=0) class ModelB(ModelA): pass When creating new ModelB instance, I'm doing this (copying the id): model_a_dict = ModelA.objects.filter(id=model_a.id).values()[0] model_b = ModelB(id=model_a_dict['id'], title=model_a_dict['title'], revision=model_a_dict['revision']) model_b.save() Now, when updating model_a, the model_b gets updated as well. For example: model_a.title = "other title" model_a.save() then model_b.title would change as well. -
How to pass instance primary key into a django form field?
I have a detail view with a link to a form where the user can write a note that will appear on the detail view. I would like the form to automatically enter the detail view instance primary key as a foreign key (for example, as model attribute "subject"). Such that when the user calls the form to enter a note, the user does not also have the select the subject from a dropdown as it is obvious that the note pertains to the previous detail view. This is all just to make a more streamlined UX. My hacky solution was to get the URL using a 'HTTP_REFERER' request and parse the pk from the URL, then pass the pk into context data in the view, and finally enter it as a value in template. For example: # view def get_url_pk(self): url = self.request.META.get('HTTP_REFERER') t = url.split('/') pk = int(t[-1]) return pk class TaskNotesCreate(CreateView): template_name='tasknotes_new.html' form_class = TaskNoteForm model = TaskNote def get_context_data(self, **kwargs): context = super(TaskNotesCreate, self).get_context_data(**kwargs) context['pk'] = get_url_pk(self) return context def get_success_url(self, **kwargs): obj = self.object return reverse('task_view', kwargs={'pk': obj.subject_id}) # template ... <div class="form-group"> <label for="exampleInput" class="required"> <input type="hidden" name="subject" value="{{ pk }}"> </div> This works … -
Django model field is only able to select certain ManyToMany fields
I am new to Django/Web Dev/Databases. I have a model setup like this: class Device(modes.Model): name = modesl.CharField(max_length=255) class Event(models.Model): name = models.CharField(max_length=255) applicable_devices = models.ManyToManyField(Device) class Property(models.Model): name = models.CharField(max_length=255) applicable_devices = models.ManyToManyField(Device) applicable_events = modeles.ManyToManyField(Event) Now what I want to happen is when I create a new "event" I will supply a applicable_device. Then once I create all my events I will then create all my properties. But based on whatever applicable_device I select when creating the property do I want to be able to add the property. For example... Devices = [Xbox, Roku] Properties ---p_name = applicable_device = [Xbox] ---o_name = applicable_device = [Roku] ---x_name = applicable_device = [Xbox, Roku] Events ---start = applicable_device = [Xbox, Roku] applicable_properties = [p_name, o_name, x_name] ---stop = applicable_device = [Roku] applicable_properties = [o_name, x_name] ---play = aplicable_device = [Xbox] applicable_properties = [p_name, x_name] So basically I will create those 3 events and put which device they apply to. Then I will start to create my events and based on whatever device I select for my event, should only give me the option for the properties that are also set to that same applicable device. -
Get data from clicked elements Django
I have a page where User can select people to add in his team. One side of the page is the list of the people to select. When user click Add to the team, it goes to the right side where we have the list of the selected people. I don't understand how I can get the data on the selected side from the view in django.. For example on the left: <div class="card-body" id="team-list"> <p class="card-text">Select today's teammates:</p> <ul class="list-group list-group-flush"> {% for tech in techs %} <li class="list-group-item"> <span class="name" name="{{tech.id}}">{{tech}}</span> <span class="move" style="float: right;">Add to the team</span> </li> {% endfor %} and on the right: <div class="card-body" id="selected-list"> <h3 class="title">You have selected the following teammates for today: </h3> <ul class="list-group list-group-flush" style="list-style-type: none;"> </ul> </div> The click is handled by a little js click event like this: var selected = document.querySelector('#selected-list ul'); var team = document.querySelector('#team-list ul'); function clickHandlerTeam(e){ if(e.target.classList.contains('move')){ if (e.target.textContent == 'Add to the team'){ console.log('changing add'); e.target.textContent ='Remove from the team'; selected.appendChild(e.target.parentNode); } else { console.log('changing remove'); e.target.textContent = 'Add to the team'; team.appendChild(e.target.parentNode); } console.log('****************'); } return; } Thanks for your help -
when i sign up a new user i want to save to different group that is each user assigned to a particular model using django post_save signals
i have two models fed into a signals.py file with two post_save signals each referencing two different models with a common sender, User, when I create a user, for example, a doctor, I discovered a user is saved with both groups, these groups are doctor and patient, I want a situation where if I create a user, a user which is related to a model(One To ONE relationship) is assigned only one group out of the two i.e User saved to doctor group not user having patient and doctor assigned to it, I also want a user details on creation saved to the associated model, I only get user.username saved to a particular model. i also have issues updating my patient profile page but the doctor's profile page updates, the patient doesn't, please what am I doing wrong, would appreciate your inputs this is my signals.py from django.db.models.signals import post_save from .models import * from django.contrib.auth.models import User from django.contrib.auth.models import Group def create_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='doctor') instance.groups.add(group) Doctor.objects.create( user=instance, name=instance.username, ) print("Profile Created For Doctor") post_save.connect(create_profile, sender=User) def create_patient_profile(sender, instance, created, **kwargs) if created: group_patient = Group.objects.get(name='patient'): instance.groups.add(group_patient) Patient.objects.create( user_p=instance, name=instance.username, ) print("Profile Created … -
Simple database insert and delete via Ajax in Django application
I'm working on a Django application that involves various people, companies, and products. I'd like to include the ability for logged in users to "favorite" any number of those people, companies, and products. I'm a pretty new Django developer and my knowledge of Javascript is scant, so I'm struggling to apply the existing Django/Ajax tutorials to my situation. Here's what I have so far. I'm going to include just the bits about favoriting a person since I presume that solution for favoriting companies and products will be virtually identical. # models.py (relevant tables only) class Person(models.Model): first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True) # many other irrelevant fields omitted class CustomUser(AbstractUser): fav_people = models.ManyToManyField(Person, through='FavoritePerson', through_fields=('user', 'person'), related_name='users', ) fav_companies = models.ManyToManyField(Company, through='FavoriteCompany', through_fields=('user', 'company'), related_name='users', ) fav_products = models.ManyToManyField(Product, through='FavoriteProduct', through_fields=('user', 'product'), related_name='users', ) class Meta: verbose_name_plural = 'Custom Users' def __str__(self): if self.first_name and self.last_name: return f"{self.first_name} {self.last_name}" else: return f"{self.username}" class FavoritePerson(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='favorite_people' ) person = models.ForeignKey(Person, on_delete=models.CASCADE, null=True, blank=True, related_name='favorite_people', ) created = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Favorited People' def __str__(self): return f"{self.user} - {self.person}" Here's the relevant portion of my template where it displays a star outline if the person … -
Custom rest_framework authentication not getting called
I am using djangorestframework 3.9.2 I have following setting for rest_framework .... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'my_project.middlewares.authentication.CentralAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'my_project.middlewares.authorization.CentralAuthorization' ], } .... And my directory structure is this ├── app1/ └── my_project ├── __init__.py ├── middlewares │ ├── __init__.py │ ├── authentication.py │ └── authorization.py ├── settings │ ├── __init__.py │ ├── commons.py │ ├── development.py │ └── logger.py ├── urls.py └── wsgi.py My authentication script is not getting call whenever I access my URL. Is there something I am missing over here? -
Migrations not Updating for Django App Running in Docker Containers
I am using Docker to run my multi app Django Project and run the web, experience, and db layer in separate containers. If I change something in the frontend docker exec -it <container name> bash into the containers python manage.py makemigrations python manage.py migrate It says that there are no changed to migrate and changes nothing. How can I get my changed to update in real time or quickly running python manage.py migrate ?