Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NGINX doesn't work when proxy_set_header is set to $host
I've been setting a simple docker-compose for a Django application, in which I have 3 containers: the Django app, a Postgres container, and NGINX. I successfully set up both Django and Postgres and tested connecting directly to their containers, so now the only thing left was to set up NGINX on the docker-compose file. I used the following NGINX default.conf file, from another template repository: upstream django { server app:8000; } server { listen 80; server_name localhost; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://django; 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; } location /static/ { autoindex on; alias /static/; } location /media/ { autoindex on; alias /media/; } } And this was my docker-compose file: version: "2" services: nginx: image: nginx:latest container_name: NGINX ports: - "80:80" - "443:443" volumes: - ./test:/djangoapp/test - ./config/nginx:/etc/nginx/conf.d - ./test/static:/static depends_on: - app app: build: . container_name: DJANGO command: bash -c "./wait-for-it.sh db:5432 && python manage.py makemigrations && python manage.py migrate && gunicorn test.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./djangoapp/test:/djangoapp/test - ./test/static:/static expose: - "8000" env_file: - ./config/djangoapp.env db: image: postgres:latest container_name: POSTGRES … -
Djangp Model form does not display when I include it in the Parent template
Long story short , My form.html Only shows submit button rather than all the fields of the model form <div class="form"> <form action="{% url 'name' %}" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="submit"> <p style="color: red;">Watch it before it gets removed on The Internet</p> </div> Here is forms.py from django import forms from django.forms.models import ModelForm from .models import Person class PersonForm(forms.ModelForm): class Meta: model = Person fields = ['name','email'] when I tried adding html inputs manually on forms.html I was able to make the inputs show on the page , Is something wrong with importing model form like that ?? Also what's weird is that when I click on that submit button since its the only one showing on the page … It takes me to a plain form.html with validation error , since I was submitting empty values Here is how I include it in the Parent template {% include "form.html" %} -
Is there caching property with argument Instead of cache_proerty in django?
I have a serializer like this class PaperEveryoneSerializer(ReadOnlyModelSerializer): author = serializers.SerializerMethodField() address = serializers.SerializerMethodField() def get_author(self, instance): if instance.paper_contractors.filter(profile__user=self.context['request'].user).exists(): return str(instance.author) else: return '' def get_address(self, instance): if instance.paper_contractors.filter(profile__user=self.context['request'].user).exists(): return {"old_address": instance.address.old_address, "old_address_eng": instance.address.old_address_eng} address_with_bun = instance.address.old_address.split("-")[0] hidden_address = address_with_bun[0:address_with_bun.rindex(" ")] old_address_eng = instance.address.old_address_eng hidden_address_eng = old_address_eng[old_address_eng.index(" ")+1:len(old_address_eng)] return {"old_address": hidden_address, "old_address_eng": hidden_address_eng} I am using this code hiding the private info. But this code will evaluate two time for instance.paper_contractors.filter(profile__user=self.context['request'].user).exists() Is there way to prevent evaluating two times for queryset? I am trying to do that with cached property. But it doesn't allow to send arguments. -
Serve Django views with React?
I am making a web application with react as frontend and django-rest-framework as backend. For django, I am following a tutorial. https://www.techwithtim.net/tutorials/django/user-registration/ - here they have made a registration form with django that has proper validation. Is there a way to do the same with React? Essentially, is there a way to show Django templates and views with React? If not, should I just link to the specific Django page hosted on the Django server? Thanks! -
change the Django Rest Framework's default url to a custom
changing default url (http://127.0.0.1:8000/v1) to a custom (https://api.abc.com/v1) Moving the app to another server with custom url is giving me problems in apache What we write in apache configuration to remove port number in ec2 instance for django rest framework -
How to edit and delete records in modelformset in Django
everyone. I can’t solve my problem now. I would like to edit and delete old records and add new records in Update-function. I can create new records in Create-function, though I can’t edit and delete old records in Update-function. I can only add new records in Update in Other-model, though I can’t edit and delete. Whereas, I can’t add new records and edit and delete old records in Update in Spot-model. Then when I try to add new records in Spot-model, this error happens. I don’t understand why the error happens. NOT NULL constraint failed: make_trip_spot.spot_cost I think the difference between Spot-views and Other-views is small. I use modelformset though I don’t understand how to use this formset. Here is my code. models.py class Other(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, related_name='extra') extra_name = models.CharField(max_length=50) extra_cost = models.IntegerField(validators=[MinValueValidator(0, 'Please input 0 or more')]) class Spot(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, related_name='spot') spot_name = models.CharField(null=False, blank=False, max_length=50) spot_time = models.DateTimeField(blank=False, null=False) spot_cost = models.IntegerField(null=False, blank=False, validators=[MinValueValidator(0, 'Please input 0 or more')]) forms.py class OtherForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['extra_name'].required = False self.fields['extra_cost'].required = False class Meta: model = Other fields = ('extra_name', 'extra_cost') widgets = { 'extra_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'extra_name', 'name': … -
how to create user profile automatically when I register with graphene django
I am learning graphql with graphene I would like to know how I can do when registering a user, the profile is also created, I do not upload code because I am only asking for information on how I can do it, I am not asking for it to be given to me by simply providing information -
How can I resolve Circular import?
enter code here from django.urls import path from . import views app_name ='store' urlpattherns =[ path('', views.all_products,name ='all_products') -
Rationale behind __lt field lookup in Django's DateFieldListFilter
What is the idea behind Django's admin filter DateFieldListFilter adding an __lt query for future dates? See excerpt below: self.lookup_kwarg_since = '%s__gte' % field_path self.lookup_kwarg_until = '%s__lt' % field_path ... self.links = (_('This year'), { self.lookup_kwarg_since: str(today.replace(month=1, day=1)), self.lookup_kwarg_until: str(next_year), }) For one, I don't see the need to add next_year to the search here, wouldn't tomorrow (this one actually is there for a daily search and a 7-day search) or something like end_of_the_day be enough? It seems very arbitrary and unnecessary to me. Secondly, wouldn't just having a __gte query without __lt faster? Or, perhaps, even using __range when the dataset is smaller could improve the search performance. -
Implementing simple Modal in Django application
I am struggling with implementing my codepen javascript based Overlay Modal in my Django application. This codepen contains the HTML, CSS, and Javascript code for my modal, and is functional. As you can see in the HTML I have posted bellow, I have a simple page where a user can look at donations, and if they want to see about it, they can click on the view button. When this button is clicked, I want to bring up an overlay like in the codepen, but it is not working. I can't figure out why. I assign all of the proper ids and classes to elements, but my program does not do anything. Can some expert please help :)? My html is down bellow. {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> {% for donation in donations %} <div class="col-lg-4"> <img class="thumbnail" src="{{donation.imageURL}}"> <div class="box-element product"> <h6><strong>{{donation.title}}</strong></h6> <hr> <a class="btn btn-outline-success" id="openModalBtn" href="#">View</a> <h4 style="display: inline-block; float: right"><strong>Free!</strong></h4> </div> </div> {% endfor %} </div> {% endblock content %} Please reach out if you have any questions. Thank you. -
how to automate validation of html
I have a django website where the front-end utilizes django template variables and some pages also have javascript code that modifies the html code. what is the best way to automate validation using tools akin to https://validator.w3.org ? I want to test the following features the page loads without any errors all the django template variables are declared in the context the JS functions that modify the HTML code are creating error-free modifications. Basically, the test will in some way trigger the JS functions that modify the HTML code. Is there a way to automate this? features 1 and 3 are most important while feature 2 is a nice to have. -
I can't store first , last name and email in django admin panel
forms.py this is my form from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserSignUpForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Mate : model = User fields = ['username' , 'email' , 'first_name' , 'last_name' ,'password1' , 'password2'] views.py this is the Sign-Up Function from django.shortcuts import render , redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserSignUpForm # Create your views here. def SignUp(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'your account has be created ! Now Log In{username}!') return redirect('login') else: form = UserSignUpForm() return render(request, 'forms/SignUp.html' , {'form' : form}) I've seen a lot of tutorials and they're doing the same thing -
Django custom form doesn't validate
I have a form that the date adjust to always show date always two weeks in advanced and according to the schedule. My problem is that I cannot get the form to validate. I'm pretty sure it's because I override to form with a __init__ method. I found similary question on stackoverflow, but nothing work. Here my forms.py : forms.py def get_valid_days(): valid_weekday = OpeningHour.objects.exclude(opening_hours='00:00').values_list('day_week', flat=True) all_days = [base + datetime.timedelta(days=x) for x in range(14)] holidays = Holiday.objects.all().values_list('date', flat=True) valid_days = [format_date_for_django_form(day) for day in all_days if day.weekday() in valid_weekday and day not in holidays] return valid_days class ReservationWithoutBadge(forms.Form): dates = forms.ChoiceField(choices=[], label="date", widget=forms.Select(attrs={ 'class' : "form__select" })) def __init__(self, *args, **kwargs): super(ReservationWithoutBadge, self).__init__() self.fields['dates'].choices = get_valid_days() def clean_dates(self): data = self.cleaned_data['dates'] valid_dates = get_valid_days() if data in valid_dates: return data else: raise forms.ValidationError("Don't break my form") Here my views.py views.py def display_available_spot(request): machineID = 4 if request.method == 'POST': form = reservation_without_badge(request.POST) if form.is_valid(): machine_infos = Machine.objects.get(id=machineID) template_name = 'reservation/list_by_date.html' context = {'available_spots': get_available_spots_for_machine(date=request.POST['dates'], minute_duration='1:00:00', staff_point=5, type_reservation='Formation', machine=machineID), 'machine': machine_infos} return render(request, template_name, context=context) else: print(request.POST) print(form.errors) print(form.non_field_errors) return HttpResponse('Validation doesn't work!') No matter what I do, the is_valid() method always return False and it go to the return … -
Django custom migration rollback
I have the following custom Django migration code: from django.conf import settings from django.contrib.auth.hashers import make_password from django.core.management.sql import emit_post_migrate_signal from django.db import migrations def create_user_groups_permissions(apps, schema_editor): emit_post_migrate_signal(verbosity=1, interactive=False, db='default') Group = apps.get_model('auth', 'Group') Permission = apps.get_model('auth', 'Permission') User = apps.get_model('users', 'User') Token = apps.get_model('authtoken', 'Token') # Create the default superuser for development defaults = { 'is_active': True, 'is_staff': True, 'is_superuser': True, 'email': settings.SERVER_EMAIL, } admin, _ = User.objects.get_or_create(username='admin', defaults=defaults) if settings.ADMIN_PASSWORD_DEV: admin.password = make_password(settings.ADMIN_PASSWORD_DEV) admin.save() # Create DRF token for admin _, created = Token.objects.get_or_create(user=admin) # Get permissions can_upload_data = Permission.objects.get(codename='can_upload_data') # Create groups with permissions default_user, created = Group.objects.get_or_create(name='default_user') if created: default_user.permissions.add(can_upload_data) def remove_user_groups_permissions(apps, schema_editor): emit_post_migrate_signal(verbosity=1, interactive=False, db='default') Group = apps.get_model('auth', 'Group') Permission = apps.get_model('auth', 'Permission') User = apps.get_model('users', 'User') Token = apps.get_model('authtoken', 'Token') # Delete DRF token for default superuser Token.objects.filter(user__username='admin').delete() # Get permissions can_upload_data = Permission.objects.get(codename='can_upload_data') # Delete permissions from groups default_user = Group.objects.get(name='default_user') default_user.permissions.remove(can_upload_data) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(code=create_user_groups_permissions, reverse_code=remove_user_groups_permissions), ] Forward migration is fine with it. However, when I try to rollback this migration I get the following error: ... File "/usr/local/lib/python3.9/site-packages/django/db/migrations/operations/special.py", line 196, in database_backwards self.reverse_code(from_state.apps, schema_editor) File "/the_project_name/main_site/users/migrations/0002_fixtures_groups_permissions.py", line 92, in remove_user_groups_permissions default_user.permissions.remove(can_upload_data) File "/usr/local/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", … -
Celery is not writing the task result to the DB
I configured my Django application and I created the DB tables for celery to log the task result. Celery read the db configuration successfully but When I run this code: result = test_celery.run(3) It does not show anything in the task result table Any Idea why it is not writing there. -
Django checking user permission before the view
I have a user model as: class User(AbstractUser): USER_TYPE_CHOICES = ( (1, 'pro_user'), (2, 'consumer'), (3, 'other'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,default=3) Now I want certain views to be only accessed by pro_user and consumer and certain by pro_user only and certain by consumer and other and such combinations I have seen @user_passes_test can be used for this. But for multiple condition how to use it @login_required @user_passes_test(lambda:u: u.user_type == 1,login_url='/page1/') @user_passes_test(lambda:u: u.user_type == 2,login_url='/page3/') def test(request): ..... I want to use this like @login_required @some_decorator(is_user_type1,is_user_type2) <-- pass list of user types allowed and for rest redirect to a url which shows "you are not authorized" def test(request): ... -
How to webscrape images from Google News?
I'm still a bit new to webscraping, trying to scrape the article images from a Google News page and display them in my Django template. I've been following along with the tutorial from towardsDataScience that can be found here. Right now I'm just trying to get the img html data from each article div just to check that I am able to pull the data. The format should look like this: <img alt="A Light in the Attic" class="thumbnail" src="media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg"/> However at the moment my code is returning an empty dictionary which tells me that I am not targeting the image correctly. Any advice from those who are more experienced would be welcome. from django.shortcuts import render, HttpResponse, redirect from django.contrib import messages from .models import * from django.db.models import Count import requests, urllib.parse from bs4 import BeautifulSoup import requests from bs4 import BeautifulSoup def index(request): URL = 'https://www.google.com/search?q=beyond+meat&rlz=1C1CHBF_enUS898US898&sxsrf=ALeKk00IH9jp1Kz5-LSyi7FUB4rd6--_hw:1624935518812&source=lnms&tbm=nws&sa=X&ved=2ahUKEwicqIbD7LvxAhVWo54KHXgRA9oQ_AUoAXoECAEQAw&biw=1536&bih=754' page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') headers = soup.find_all('div', class_='BNeawe vvjwJb AP7Wnd') header_dict = [] for h in headers: header_dict.append(h.text) image = soup.find_all('div', class_="qV9w7d") context= { "header_dict": header_dict, "example": image, } return render(request, 'index.html', context) -
How to implement fullCalendar plugins to my script with django
I want to implement the plugins, which serve to show the month, week and day views The problem is that it does not work for me, I have tried to import it normal inside my script: calendar script calendar implementation But, I get this error "Uncaught SyntaxError: Cannot use import statement outside a module" And I have the plugin files in the static folder, where all the css js files are stored The previous code shows the part where the calendar is implemented, inheriting from a base template with the navbar and the footer Thank you. -
django restr framework firebase admin error "detail": "Invalid token."
I am a bit new to python and I am trying to use firebase admin to send a token to a phone number and do authentication on a phone number using backend as my Django project and I am getting the below error { "detail": "Invalid token." } Please advise me on how I can be able to carry out phone number auth through the back end in an. apiin Django I have already set up the service account on the firebase console but I did not create any app, Is there a need to create an app on firebase console View.py class SendPhoneCodeView(viewsets.ModelViewSet): def post(self, request): cred = credentials.Certificate("firebase-admin.json") firebase_admin.initialize_app(cred) phone = request.data.get('phone') user = auth.create_user(phone=phone) print("User Created Successfully : {0}".format(user.uid)) url.py router.register('v1/send_phone_code', views.SendPhoneCodeView, basename='PhoneModel') model.py class PhoneModel(models.Model): phone = models.CharField(max_length=14) serializer.py class SendPhoneSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ( 'phone', ) with this request { "phone":"+3112456575889" } here's a screenshot of my apps Directory structure -
Requests to localhost from within a view cause the server to stop responding
I am using Djoser to create an authentication backend. I want the following to happen: User registers at http://localhost:8000/auth/users/ with email, username, password, and re_password User receives an activation email at the email they entered with a URL to activate their account. The URL is of the form: <web url>/activate/{uid}/token (eg: http://localhost:8000/activate/Mg/apur8c-6100390a061c5ff081235193867f943a) Clicking on that URL sends a GET request to the server where a view (UserActivationView) receives the extracted uid and token and sends a request of its own to <web url>/users/activation/{uid}/token (http://localhost:8000/users/activation/Mg/apur8c-6100390a061c5ff081235193867f943a). And returns the response that it gets from that request as its response. User account gets activated. This is the code that does all of the above: # Djoser configuration in settings.py DJOSER = { 'LOGIN_FIELD': 'email', 'PASSWORD_RESET_CONFIRM_URL': 'password-reset/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'username-reset/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_CHANGE_EMAIL_CONFIRMATION': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'USER_CREATE_PASSWORD_RETYPE': True, 'SET_PASSWORD_RETYPE': True, } # views.py in user app (users/views.py) from rest_framework.views import APIView from rest_framework.response import Response import requests class UserActivationView(APIView): def get(self, request, uid, token): protocol = "https://" if request.is_secure() else "http://" web_url = protocol + request.get_host() post_url = web_url + '/auth/users/activation/' post_data = {'uid': uid, "token": token} print(f"Sending request to {post_url} with {post_data}") result = requests.post(post_url, data=post_data) # <<-- causes the … -
Django/selenium How to make download button work on a website-client of another website
I am building a website with Django. It displays the content of another website by scraping parts of its HTML with selenium and incorporating that code in my webpage to make it look better. For example, in one page, a table is passed to my website through the context and it's incorporated this way {% extends 'home.html' %} {% block content %} {{ table_name|safe }} {% endblock %} This table also has a download button in each row, and the number of rows changes over time. In my page the download button is displayed but it doesn't work. Is there any way I can make it work? You should also know that the download button does not redirect to a link. -
How do I separate the many to many by individuals in django models?
How do I change the status for each player's payment? I cannot add a status field there as it will change the status for all the users within many to many fields, I want to customize it to have a different status for each user. from django.db import models from users.models import Profile # Create your models here. class Payments(models.Model): match = models.CharField(max_length=30) amount = models.DecimalField(default = 0, max_digits = 5, decimal_places = 2) players = models.ManyToManyField(Profile) datespent = models.DateField('Date Spent') -
How can Control User View class based on Role - Django
I am using class based view and trying to load content based on user Role. I want load form fields enabled or disabled based on user role.... (But still want to show the form for both type of users) MyView: class MyListView(LoginRequiredMixin, UserPassesTestMixin, ListView): def test_func(self): return self.request.user.user_type == 'Business' def get_context_data(self, **kwargs): context['form'] = MyForm(disable_fields=True) # this disable_fields will become true or false based on user role... return context MyForm: class MyForm(forms.Form): comment = forms.CharField(widget=forms.Textarea(attrs={'style': 'height: 4em;'})) ready = forms.BooleanField(label="are you ready?", required=False, initial=False) def __init__(self, disable_fields=False, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) if disable_fields: for visible in self.visible_fields(): visible.field.widget.attrs['readonly'] = True So I want to check user role before or with in the get_context_data function called... Please advise -
DJANGO NEW USER REGISTRATION
is there a way to create a new user from a html file with customs fields without using forms.py and if no how can i add custom columns in auth_user table in postgresql -
Django post-save when the superuser is the sender
I created 3 groups named 'admin', 'teacher' and 'student' and I want every user I register to be in only one of these groups not two. If i create the super-user by entering in the command line 'createsuperuser' it works well,it is added to the 'admin' group, but the problem is that if I create the teacher it is added to the 'teacher' group and also to the 'admin' group and same problem with student. these is the post-save for my 3 profils signals.py @receiver(post_save, sender=User) def admin_profil(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='admin') instance.groups.add(group) @receiver(post_save, sender=Teacher) def teacher_profil(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='teacher') instance.user.groups.add(group) @receiver(post_save, sender=Student) def student_profil(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='student') instance.user.groups.add(group)