Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any method to join one level past a related_name?
I'm repeatedly running into a data situation that I feel django probably has a shortcut for, but I can't find it... I want to access a model one relationship beyond a queryset I selected via a related_name. It feels like there should be a one-liner for this, but the best I've figured out is: for p in team.players: do_whatever(p.user.email) Using select_related will precache the data, but won't actually give it to me in a usuable form. team.players.select_related('user') # still returns queryset of Players, not Users It just seems like there should be some way for me to get a query_set of the associated users via one call. Something like annotate: users = team.players.annotate('user') # doesn't work Is there any method that does what I'm looking for? Or is the "for - in" loop the only way to go? The basics of my classes (greatly simplified): class Team(models.Model): name = models.CharField() class Player(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="players") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="players") captain = models.BooleanField() Is there any one-liner or optimization beyond doing a select_related followed by a for-in? -
Github Actions implementation in project with test machine
Current architecture of our project is pretty simple: Multiple Github repos merge in Master and deploy to Server. But we want to add Testing to it. And currently I'm investigating Github Actions possibility. Is it possible to make this setup: Code getting merged to "Develop" branch and trigger Github Action Github Action push code to Test server and run all Unit Tests return test result, maybe as Email or something. If tests are successful Develop branch getting merged to Master. Is it possible to setup all of this just with Github Action or we will need to add Jenkins or Travis?? Thank you for your time. -
ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation
I am trying to deploy Django app on AWS elasticbeanstalk and I am following the official document carefully https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html .but still I am getting an error when I run eb create django-env , which first error saying Instance deployment failed to install application dependencies. The deployment failed. the bunch of errors follow(see the screenshot) my folder structure seems alright and I have the requirements.txt in the root directory with all the dependency specified I am using: Django==4.0.3 my machine is Mac M1 I have installed awsebcli on the venv and globally just on case -
File handling in django
I am trying to access the csv file which i passed in my form and saved in media directory. I am able to access the file if i manually enter the path(localhost://8000/media/1.csv) but it throws an error saying "No such file or directory" when accessing from open function. def home(request): print("Rendering Home...") if request.method == "POST": uploaded_file = request.FILES['csvFile'] fs = FileSystemStorage() name = fs.save(uploaded_file.name,uploaded_file) url = fs.url(name) csv_fp = open(f'{url}', 'r') //ERROR:"No such file or dir media/1.csv" reader = csv.DictReader(csv_fp) headers = [col for col in reader.fieldnames] out = [row for row in reader] return render(request, 'home.html', {'data' : out, 'headers' : headers}) return render(request,"home.html") -
How to host Django + Selenium Scrapper on ubuntu properly or how to host scrapper in the cloud?
basically I am facing a problem regarding my Django and selenium website. My Django function contains selenium code to go and scrape details sent by my front end. It works perfectly fine on my PC. The scrapper must run until the end of the page and it usually takes hours before reaching the end. It is basically calling my API endpoint which starts scraping and then returns "done" as a response. Now I want to host it on ubuntu server on AWS EC2 instance. Which I did and works perfectly fine. But as I said the scrape works for hours, and till the end of the page it doesn't return anything in response and the request stays alive for hours, which as you know is against the security feature of Nginx and the request dies with a 503 error. The default time for Nginx request is I think 30 seconds or something but I tried changing it but no luck. Is there a different way of hosting scrappers? This scrapper will be used by one person but I am thinking of making it public so more people will use it in the future. That's why I would like to know … -
Why the html custom form is not working django
I have a contact page with a simple form. Here is views.py: def contact_view(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, settings.ADMIN_EMAILS) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "base/contact.html", {'form': form}) def success_view(request): return HttpResponse('Success! Thank you for your message.') this is contact.html: {% block content%} <main class="page contact-page"> <section class="portfolio-block contact"> <div class="container"> <div class="heading"> <h2>Contact me</h2> </div> <form method="post"> {% csrf_token %} <div class="mb-3"><label class="form-label" for="name">Your Name</label><input class="form-control item" type="text" id="name"></div> <div class="mb-3"><label class="form-label" for="subject">Subject</label><input class="form-control item" type="text" id="subject"></div> <div class="mb-3"><label class="form-label" for="email">Email</label><input class="form-control item" type="email" id="email"></div> <div class="mb-3"><label class="form-label" for="message">Message</label><textarea class="form-control item" id="message"></textarea></div> <div class="mb-3"><button class="btn btn-primary btn-lg d-block w-100" type="submit" value="submit">Submit Form</button></div> </form> </div> </section> </main> {% endblock %} When I use form.as_p it works very well but when I use this template it is not working it only shows in the terminal that a post request was made. -
GeoDjango - set initial value (location) for PointField in form (OSMWidget)
I want to create a form to choose a location with PointField. I use OSMWidget as a widget, and I want the initial location to be defined by user's ip. I use the following standard method of CreateView for it: def get_initial(self): init = super().get_initial() try: (lat, lon) = utils.get_user_coords(self.request) print(lat, lon) init['residence_location'] = Point(lon, lat) except geoip2.errors.AddressNotFoundError: pass print(init) return init However, it locates the map at (0,0) (i guess? somewhere under Ghana) whatever the (lat, lon) is. I know it sees this data, because if I remove this function altogether, it locates the point at France (the default location per docs). Why it doesn't work? -
I can't install django-celery
When trying to install Django-celery on both desktop and laptop, these errors occur. After reading various forums and using various installation options, I was able to install Django-celery. At least that's what pip tells me. But when trying to import django-celery the following errors occur. Why do these errors occur and what do I need to do to fix them? I'm using Python 3.1. -
model relationship and Queries in Django not a clear
what does these lines of code mean in Django View: i couldn't find a details explanation, I came to Django from a Laravel background, so I can understand the models and relationships... thanks customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) -
installing channels redis in windows10 without errors
am trying to use Redis as the back store channel layer in Django but am getting installation errors when it comes to building the wheel for hiredis module. Am on Windows 10 and have just learned it is not supported in windows. what should I do so as to use RedischannelLayer backend settings in Django settings.py file -
No Reverse Match coming up with URL keyword
This seems like I must be missing something really simple. I'm trying to use the url command for a link. I keep getting a NoReverseMatch error. The code in the HTML looks like this: Batch Upload test I'm just learning this so I duplicated the link, one in a button and one as an url. If I take out the second line the HTML loads find and the button takes me to the correct page. When I add the second line I get the NoReverseMatch error. I have it added to the installed apps in the settings page but I would think if I had done this wrong the first button wouldn't work at all. If instead I link it to a name in the base module like this: test it works fine. Is there some place special I need to list the MyApp application in order for python to find it when using url? -
The model TokenProxy is already registered in app 'authtoken'
I am facing this problem with migrating in Django admin after I updated the app name 'rest_framework.authtoken' in django project settings. It gives me error The model TokenProxy is already registered in app 'authtoken'. I know I should have added this and migrate before creating super user but now I have already created the project and migrated lots of models and there is a data in it. Can help me how I can resolve this problem. I also tried to undo migrations with command python manage.py migrate books but it again does not recognize the word books. Please help me with this. Here is my apps in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'traderskamp_app', 'rest_framework.authtoken', 'rest_framework', 'corsheaders', ] Here is the exact error: File "C:\Python39\lib\site-packages\rest_framework\authtoken\admin.py", line 51, in admin.site.register(TokenProxy, TokenAdmin) File "C:\Users\Anwar\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\sites.py", line 126, in register raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model TokenProxy is already registered in app 'authtoken'. -
Does changing Django database backend require code modification?
I'm currently using sqlite3 as Django database backend. However I'm looking forward to use MySQL in the future. Does changing database backend require source code modifications such as models.py, forms.py, views.py..etc.(other than files that link Django to DB such as settings.py) My guess(not sure) : As my codes interacting with database backend are written in python scripts(not SQL) I guess no source code modification will be needed since it means Django automatically generates SQL querys with my python codes that match with current linked database backend. -
How to write a way to the file for django-upgrade whithout an error?
I have a Django project, that names 'dj_post', and I have 2 apps in it: 'dj_post' and 'testdb'. Then I wanted to use the django-upgrade library to get rid of problems with the code in file of main app urls.py I installed that library and then wrote the text below to the command promt: django-upgrade --target-version 4.0 dj_post/dj_post/urls.py And then I had this: ` Traceback (most recent call last): File "c:\users\денис\appdata\local\programs\python\python38\lib\runpy.py", line 194, in _ru n_module_as_main return _run_code(code, main_globals, None, File "c:\users\денис\appdata\local\programs\python\python38\lib\runpy.py", line 87, in _run _code exec(code, run_globals) File "C:\Users\Денис\AppData\Local\Programs\Python\Python38\Scripts\django-upgrade.exe\__ma in__.py", line 7, in <module> File "c:\users\денис\appdata\local\programs\python\python38\lib\site-packages\django_upgrad e\main.py", line 53, in main ret |= fix_file( File "c:\users\денис\appdata\local\programs\python\python38\lib\site-packages\django_upgrad e\main.py", line 70, in fix_file with open(filename, "rb") as fb: FileNotFoundError: [Errno 2] No such file or directory: 'dj_post/dj_post/urls.py' ` And tell me, actually, please, how to write the way to my project file correct. Thanks in advance. -
Django unable to serve static files from s3 bucket
I created a few models and pushed my project to a development server on an AWS EC2 instance. I used Django storages and followed the docs to configure my settings.py. when I run manage.py collectstatic the static files are pushed to the bucket successfully, but when I access the Django admin the CSS is missing. Can anyone help me fix this? My bucket permissions { "Version": "2012-10-17", "Id": "Policy1650117254896", "Statement": [ { "Sid": "Stmt1650117250899", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": "arn:aws:s3:::agristore.001/*" } ] } My settings file STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '***' AWS_STORAGE_BUCKET_NAME = '****' AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False My Nginx settings server { server_name <my ip>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/venv/src; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django Page not found error on url redirect
So I'm dealing with a little problem here. So what i wanna do is: sign up an user, then redirect him to a new page that contains a form which will collect some additional info about him and then after he submits the form, it should redirect him to the login page. I want this version because only new users should complete this form. signup view class SignUpView(CreateView): form_class = SignupForm success_url = reverse_lazy('user_ski_experience:user_questions') template_name = "signup/signup.html" additional info view class CreateInfoView(LoginRequiredMixin, CreateView): model = AdditionalInfoModel form_class = AdditionallnfoModelForm template_name = "user_ski_experience/additional_info.html" def get_form_kwargs(self): variable_to_send = super(CreateInfoView, self).get_form_kwargs() variable_to_send.update({'pk': None}) variable_to_send.update({'pk_user': self.request.user.pk}) return variable_to_send def get_success_url(self): return reverse('login') -
Rendering database data to browser in Django
I am having difficulties with showing database data in browser with Django. I have, for show my issue, just one date in my database. When I go to the Django Shell I got this: >>>from events.models import Event >>>Event.objects.all() <QuerySet [SuperBowl22] My models.py has: from unicodedata import name from django.db import models from django.forms import DateTimeField class Event(models.Model): name = models.CharField('Name´s event', max_length=120) timeEvent = models.DateTimeField ('Event´s date') seat_position = models.ForeignKey(Seat_position, blank=True, null=True, on_delete=models.CASCADE) fanatic = models.OneToOneField(EPS, blank=True, null=True, on_delete=models.CASCADE) def __repr__(self): return self.nombre My views.py has: from .models import Event from token import RIGHTSHIFTEQUAL from django.shortcuts import render from django.http import HttpResponse from datetime import date def all_events(request): event_list = Event.objects.all() return render(request, 'events/event_list.html', {'event_list': event_list} ) My event_list.HTML has: {% extends 'base.html' %} {% block title %}Showing database info{% endblock title %} {% block content %} <h1>Result(s) of database consultation:</h1> <ul> {% for events in event_list %} <li>{{ event.name }}</li> {% endfor %} </ul> {% endblock content %} I run the runserver with no errors and go to http://127.0.0.1:8000/events/ and the browser shows: Result(s) of database consultation: . Why the HTML is not showing <QuerySet [SuperBowl22] or it equivalent? Have I some typo or any small mistake? The … -
Couldn't pass parameter "smm" to the specified path
<li><a href="{%url 'corebloc_app:service_type%} smm">Marketing & Management Services</a></li> This is the HTML code, trying to pass the string "smm" to this: path("services/<str:service_type>", views.service_type, name="service_type") So that I could have a path "services/smm" on my address bar. -
Django cannot change password error didn't return an HttpResponse object. It returned None instead
I create form for change password like this. forms.py class PasswordChangeForm(forms.Form): password = forms.CharField(max_length=32,required=True,widget=forms.PasswordInput) repassword = forms.CharField(max_length=32,required=True,widget=forms.PasswordInput,label="Password Confirmation") def clean(self): cleaned_data = super(PasswordChangeForm, self).clean() password = cleaned_data.get("password") repassword = cleaned_data.get("repassword") if password != repassword: raise forms.ValidationError( "Password and Confirm Password does not match" ) In views.py I save new password like this code views.py def changePassword(request): username = None if request.user.is_authenticated: if request.method == 'POST': form = PasswordChangeForm(request.POST) if form.is_valid(): username = request.user.username user = User.objects.get(username=username) password = form.cleaned_data.get('password') user.set_password(password) user.save() messages.success(request, "Your password has been changed successfuly.!") return redirect('/changePassword') else: print(form.errors.as_data()) else: form=PasswordChangeForm() return render(request,'changepassword_form.html',{'form':form}) It show error like this. ValueError at /changePassword The view device.views.changePassword didn't return an HttpResponse object. It returned None instead. The password was changed after show error. It auto logout and I can login with new password but it not redirect to form. How to fix this error? -
django debug toolbar: no such session
I've been trying to set up the Django debug toolbar. I follow every step in documentation, I add the path in urls.py I add the middleware I add the debugtoolbar in Installed apps, but yet I come up with this error: Operational error : no such table : django_session -
How to upload File from ajax to django backend?
Any ideia how to upload File (.pdf) from ajax to django backend ? customerForm.addEventListener('submit', e => { e.preventDefault() $.ajax({ type: 'POST', url: '', data: { 'csrfmiddlewaretoken': csrf[0].value, 'identity_type': $('#id_identity_type').val(), 'identity_number': $('#id_identity_number').val(), 'file': $('#id_file').val() }, success: function(response) { console.log('SUCCESS') }, error: function(error) { console.log(error) } }) Thank You -
How can I use tag set in Django(jinja)?
I want use below code in Django template but I get this error : Invalid block tag on line 255: 'set'. Did you forget to register or load this tag?. {% set Ne_page = page_data.current_page +1 %} {% set Pr_page = page_data.current_page -1 %} When I use {% load set %} for load set tag I get this error: 'set' is not a registered tag library. Must be one of: admin_list, admin_modify, admin_urls,... I use another function like if or for and ... and work fine but when use set I have error, How can I use set tag for increment a variable? -
Static file not working in Django "js/jquery.magnific-popup.min.js" 404
All static file is probably working but 2 files are not working. I want results like this is my HTML filecmd error 404here is my codemy HTML fileDjango response -
Django set_password(password) doesn't hash the password
In Django documentation, it says that it hashes the password but is not saving it, so I have to save it, as I did. If I create a superuser then everything is ok, but when I try to create a user account, the password gets saved unhashed into the database. I try to use make_password, but that doesn't work either, I get the same result. Do you have any idea? models.py from django.contrib.auth.hashers import make_password from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from datetime import datetime from django.core.validators import MinLengthValidator from .CHOICES import * from django.utils.translation import gettext_lazy as _ from django.db import models # Create your models here. country_choice = COUNTRY_CHOICE class CustomAccountManager(BaseUserManager): Here is the custom user model. def create_superuser(self, email, username, first_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, first_name, password, **other_fields) Here is the user model. def create_user(self, email, username, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) user.set_password(password) # user.make_password(self.request.data[password]) Here is where I … -
Django: Reverse for 'verify-payment' with arguments '('',)' not found. 1 pattern(s) tried: ['course/u/(?P<ref>[^/]+)/$']
i wrote a view to verify payment bbut when i hit the payment button i get this error that say Reverse for 'verify-payment' with arguments '('',)' not found. 1 pattern(s) tried: ['course/u/(?P<ref>[^/]+)/$'] i know it's a url configuation error, i am not passing in the right arguments but i dont know what to pass in, i already tried payment.ref views.py def verify_payment(request: HttpRequest, ref: str) -> HttpResponse: payment = get_object_or_404(Payment, ref=ref) verified = payment.verify_payment() return redirect("userauths:profile") models.py class Payment(models.Model): order_id = models.CharField(max_length = 50 , null = False) payment_id = models.CharField(max_length = 50) user_course = models.ForeignKey(UserCourse , null = True , blank = True , on_delete=models.CASCADE) user = models.ForeignKey(User , on_delete=models.CASCADE) course = models.ForeignKey(Course , on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=False) email = models.EmailField() ref = models.CharField(max_length=200) verified = models.BooleanField(default=False) def __str__(self): return f"Payment: {self.course.price}" def save(self ,*args, **kwargs): while not self.ref: ref = secrets.token_urlsafe(50) objects_with_similar_ref = Payment.objects.filter(ref=ref) if not objects_with_similar_ref: self.ref = ref super().save(*args, **kwargs) def amount_value(self) -> int: return self.course.price * 100 def verify_payment(self): paystack = PayStack() status, result = paystack,verify_payment(self.ref, self.course.price) if status: if result['course.price'] / 100 == self.course.price: # if result['amount'] / 100 == self.course.price: self.verified = True self.save() if self.verified: return True return False …