Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Iterate List in Dict with Python in the template
I want to iterate with django in the template a list in a dictionary. For example py = {name[a,b,c],age[10,12,13],username[aa,bb,cc]} -
Object of type TemporaryUploadedFile is not JSON serializable
I am trying to run my file upload view in Django as a task using celery, every works fine except when the image file is more than 2.5MB which celery complains that it cant serialize. the reason i am using celery is that I want to get the progress info from each file upload task and create a progress bar from it. below is my code. /views.py def simple_upload(request): if request.method == 'POST' and request.FILES['image']: file = request.FILES['image'] #process_download(file) task = process_download.delay(file) #print(task.task_id) return redirect('index') return render(request, 'upload.html') @shared_task(bind=True) def process_download(self, image_file): process_recoder = ProgressRecorder(self) print('Upload: Task Started') # time.sleep(50) fs = FileSystemStorage() buffer = io.BytesIO() chunk_size = 0 for chunk in image_file.chunks(): chunk_size += sys.getsizeof(chunk) buffer.write(chunk) process_recoder.set_progress(chunk_size, image_file.size) buffer.seek(0) image = ImageFile(buffer, name=image_file.name) fs.save(image_file.name, image) return 'Done' is there any way i could make celery serialize the images that are larger than 2.5, using the Django settings FILE_UPLOAD_MAX_MEMORY_SIZE = 50*1024*1024 does not work too? -
Missing migration files
I am stuck at this error for missing migration files.. Do I need to drop the whole database to reset the migrations or is it possible to do some type of migrate rollback for that app gigs? Does anyone know how to solve it? Would highly appreciate the help! -
How do I get Django's 'context' variables accessible to more than one view?
Is it possible to have the variables of a context block accessible to more than one view? Can one create "constants" in Django 'views.py'? I have two pages: 'index.html' and 'post_list.html'. They both use the model 'Post', but the two pages aren't identical. So the DRY principle went out the window. A quick search dug out some older questions about writing the variables into 'settings.py' or writing a block of code like def settings... How is it done with Django 3.x? -
Can I override the related_name of a ForeignKey in a proxy model?
I have a Django model ActivityLog to track general user related activities in the system. I created a proxy model StudentActivityLog where I gathered the student specific business logic related to user activity. This proxy model has a custom model manager too. class ActivityLog(models.Model): person = models.ForeignKey( "Person", on_delete=models.PROTECT, related_name="activity_logs" ) # ... class StudentActivityLogManager(models.Manager): def custom_something(): # ... class StudentActivityLog(models.Model): objects = StudentActivityLogManager() class Meta: proxy = True # ... When I have a Person instance, I would like to be able to write person.student_activity_logs.custom_something() to access the method of the student model manager. However, this attribute is not available, I can only access person.activity_logs but that obviously doesn't have custom_something(). I know that StudentActivity.objects.filter(person=student).custom_something() will work, but I was wondering if I can avoid this tedious format. -
Django not displaying content of an existing model, instead displays a pair of double quotes(" ") in its place
Like the title says when i try to display some aspect of a model is displays quotes instead HTML {% block content %} <div> {% for listings in listing %} <p>"{{ listing.title }}"</p> {% endfor %} </div> {% endblock %} what shows up views.py def getListingAll(request): listing = Listing.objects.all return render(request, 'all.html', {"listing":listing} ) models.py class Listing(models.Model): title = models.CharField(max_length=150) available_till = models.DateField('Available till') description = models.TextField(max_length=2000) pub_date = models.DateTimeField('Date published', auto_now = True) price_per_day = models.IntegerField(default=0) def __str__(self): return self.title -
Best Practice for Junction Table Form
As stated in the title, I want to use a junction table from my model as the form. Below i've included the models (only the necessary fields). Currently, I have an html template that shows information regarding the dataset. I have a function that goes to the source system and gets all of the columns. The same operation grabs them from the destination system. The aim is to ultimately be able to match columns from the source system to the destination system. To do this, I pull of the columns into the dataset_columns table and mark it as either 'source' or 'destination'. I would like to use a form with the dataset_column_junction table that would allow me to match a 'destination' column to a 'source' column. (I should mention that we don't expect to pull in all source columns). class csc_data_sets(models.Model): dataset_id=models.CharField(primary_key=True, max_length=36, default=uuid.uuid4) class dataset_columns(models.Model): column_id=models.CharField(primary_key=True, max_length=36, default=uuid.uuid4) dataset_id=models.ForeignKey(csc_data_sets, models.DO_NOTHING, db_column='dataset_id',blank=True, null=True) class dataset_column_junction(models.Model): destination_column_id = models.OneToOneField(dataset_columns, primary_key = True, on_delete=models.CASCADE,db_column='destination_column_id') source_column_id = models.ForeignKey(dataset_columns, models.DO_NOTHING, related_name='source_column_id', db_column = 'source_column_id') I have a few attempts but all of them feel sloppy or don't function well. I was hoping to see if someone's tackled this before and if there is a …