Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How do I sub-class a Django Model Foreign Key Field
New to Python and Django but I would like to create a custom foreign key field containing a variety of presets to use across my app. I have tried several approaches but have a variety of errors and not sure where to go from here. Goal is a 'BaseFKField' model class that has: on_delete = models.RESTRICT by default blank = False by default related names don't have the typical '_set' suffix for queries, related_name has been challenging I have tried various formulations of this: class BaseFKField(models.ForeignKey): def __init__(self, to, on_delete = None, ok_blank = None, *args, **kwargs): on_delete = models.RESTRICT kwargs['blank'] = ok_blank super().__init__(to, on_delete, blank = ok_blank, *args, **kwargs) class BaseFKField(models.ForeignKey): def __init__(self, to, on_delete=None, *args, **kwargs): super().__init__(to, on_delete, blank = False, *args, **kwargs) Also explored setting kwargs["rel"] in my ___init___ by importing ManyToOneRel and using it like they do with rel_class in the Foreign Key field class but no luck. Errors I have been getting: reverse accessor error for related_name variable set twice missing required argument In general, I am finding it very difficult to create custom fields at all. I have found the docs to be difficult to follow (the example there is very basic). I am … -
how to get user's phone number from network like facebook in django
I want to get user's phone number from network like facebook in django. When we visit facebook's login page, it shows us our phone number in mobile and a text written, "Facebook requests your phone number from network". So I also want to make a django project which can request user's phone number from network. Thank you. -
django related field subset average
i have two models in django app UserDay model: class UserDay(models.Model): date = DateField() @property def avg(self): return self.activities.aggregate(Avg('point')) Activity model: class Activity(models.Model): point = models.SmallIntegerField() userDay = models.ForeignKey( UserDay, on_delete=models.CASCADE, related_name="activities" ) a user day can have "n" activities. i just want to get average of last "m" activities point. HOW CAN I DO IT?? :D -
Django cannot edit user profile ValidationError require username
I create form for edit user profile like this. forms.py class UserEditForm(forms.ModelForm): username = forms.CharField(max_length=100,disabled=True) first_name = forms.CharField(max_length=100,required=True) last_name = forms.CharField(max_length=100,required=True) email = forms.EmailField(max_length=100,required=True) class Meta: model = User fields = ["username", "first_name", "last_name", "email"] I use form in function userEditForm() which check email exits before save data like this code. views.py def userEditForm(request): username = None if request.user.is_authenticated: username = request.user.username user = User.objects.get(username=username) if request.method == 'POST': form=UserEditForm(request.POST) if form.is_valid(): first_name = form.cleaned_data.getcleaned_data.get("first_name") last_name = form.cleaned_data.getcleaned_data.get("last_name") email = form.cleaned_data.getcleaned_data.get("email") #If edit email then check exist before update if not email == user.email: if User.objects.filter(email=email).exists(): message = "Email exist" messages.info(request, message) return redirect('/userEditForm') else: user.first_name = first_name user.last_name = last_name user.email = email user.save() return redirect('/userEditForm') else: print(form.errors.as_data()) else: form = UserEditForm() return render(request,'useredit_form.html',{'form':form}) when I submit form it show error like this. {'username': [ValidationError(['This field is required.'])]} I don't want to change username. How to edit user profile? -
How to use default field values for ForeignKey?
I'm just starting to learn Django and building a simple blog with it. So i have two models Post and PostStatistics. When ever i add a new post, i want that PostStatistics contains all specified default values. How can i achieve this correctly? models.py class PostStatistics(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) post_views = models.IntegerField(default=0) post_likes = models.IntegerField(default=0) post_favorites = models.IntegerField(default=0) class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) user = models.ForeignKey(UserProfile, null=True, on_delete=models.CASCADE) statistics = models.ForeignKey(PostStatistics, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = RichTextField(blank=True, null=True) draft = models.BooleanField(default=False) views.py def add_post(request: HttpRequest): form = PostForm(request.POST) is_draft = True if form.data.get("draft") == "on" else False post = Post( title=form.data["title"], body=form.data["post"], user=request.user, draft=is_draft, statistics = PostStatistics() -> this is not correct ) post.save() return redirect("post") At the moment i get FOREIGN KEY constraint failed. -
Add Plus to dropdown with django
Any ideia how to implement form field with plus icon to add ? Like form in django admin. Thank You -
MongoEngine supported by django-elasticsearch-dsl?
According to Docs can create a class Index inside the Document,... then The Django model associated with this Document like the below code class Django: model = Car I'm using MongoEngine instead of the Default Django model. Do you support MongoEngine or not? if don't support What is your suggested solution? -
Django - The current url didn’t match any of the these
I have Django 4.0.4 I tried the following url : http://127.0.0.1:8000/cp2/sbwsec/1076/o2m/section/wseclmts/47/p/element/sbwblmnt/1077/ but it gives me error Page not found (404) The current path, cp2/sbwsec/1076/o2m/section/wseclmts/47/p/element/sbwblmnt/1077/, didn’t match any of these. Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: I have 1370 patterns - where the correct pattern is on the line 268 as you can see from the debug exception page cp2/ (?P<parent_element_name>\w+)/(?P<parent_id>\d+)/p/(?P<parent_field>\w+)/sbwblmnt/(?P<item_id>\d+)/$ [name='sbwblmnt_epec'] Thank you for the help -
genericviewset(mixins.UpdateModelMixin)
I have a problem with my code, Am Trying to write a generic view set in DRF for updating my view but I got an error. This is my portfolio model: class Portfolio(models.Model): name = models.CharField(max_length=50, blank=False, null=True, default='portfolio') user = models.ForeignKey('accounts.User', on_delete=models.DO_NOTHING, related_name='investor') assets = models.ManyToManyField(Assets, related_name='portfolio_assets') This is my serializer: class PortfolioSerializer(serializers.ModelSerializer): class Meta: model = Portfolio fields = ['id', 'name', 'user', 'assets'] and at the end my view and URL: class PortfolioUpdateDetailDestroy(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin ): queryset = Portfolio.objects.all() serializer_class = PortfolioSerializer def get(self, request, pk): return self.retrieve(request, pk) def put(self, request, pk): return self.update(request, pk) router = DefaultRouter() router.register("Portfolio_Detail", PortfolioUpdateDetailDestroy, basename="Portfolio_Detail") urlpatterns = [ path('', include(router.urls))] when I try to update an object I have to give everything to fields again, I mean I have to update all fields together, if I want to update only the name field I got this error "user": [ "Invalid pk \"0\" - object does not exist."], "assets": [ "Invalid pk \"0\" - object does not exist."] -
xmlrpc.py not found error while using supervisor in docker
hello guys im writing a docker file and compose with ubuntu 20.04 and try to install supervisor inside it docker file : ... RUN apt-get install -y supervisor COPY backend_supervisord.conf /etc/supervisor/conf.d/ docker compose : command: bash -c "python manage.py migrate && supervisorctl reread && supervisorctl reload&&supervisorctl start daphne" daphne is my program name in my supervisor conf file i really did not realize what is happening here and this is the err msg : error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /usr/local/lib/python3.8/dist-packages/supervisor/xmlrpc.py line: 560 -
Django rest framework dictionary is full of escape characters
I have updated a column in the database postgres and it looks like this in the Database [{"author_name": "palmina petillo", "rating": " ", "text": "We really loved it! Food is sophisticated but not pretentious. Service is excellent and price is adequate for Michelin standards and quality of the ingredients. French influence + local produce. 100% recommended!!"}, {"author_name": "Ann dunphy", "rating": " ", "text": "Excellent staff\nFood beautiful"}, {"author_name": "Kieran Aherne", "rating": " ", "text": "Second time eating here and I have to say the food just keeps getting better. Couldn t fault the food or the service. Top quality restaurant and will definitely be back for a 3rd time, eventually \u263a\ufe0f"}, {"author_name": "Deirdre Watson", "rating": " ", "text": "Our party had a delicious and lovely dining experience at Campagne on Thursday evening.. the welcome, food and accompanying wines as recommended with our food by the professional staff are second to none.. I would highly like everyone to try and enjoy this experience just once"}, {"author_name": "Mary Irwin", "rating": " ", "text": "Delighted to enjoy a meal in Campagne again - if anything it was better than we remembered. Excellent staff, delicious food and great buzz. Looking forward to our next visit … -
Uncaught TypeError & memory leak error in materia-table & django
I am working a project with reactjs & material-table for the frontend and Django for the backend. Currently, I am performing CRUD operations using axios on my material-table. However, I have encountered a difficulty when doing the delete request. The table looks like this: enter image description here Everything went well when I delete the 2nd & 3rd row: enter image description here But when I delete the "last row", a bunch of error pops up in console log: DataWorker.js:68 Uncaught TypeError: Cannot read properties of undefined (reading 'id') react-dom.development.js:11102 Uncaught TypeError: Cannot read properties of undefined (reading 'id') react-dom.development.js:88 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method. This is my DataWork.js: export default function DataWorker() { const [entries, setEntries] = useState({ data: [ { id: "", position: "", defect: "", tool: "" } ] }); const [state] = React.useState({ columns: [ { title: "Position", field: "position", width: 150, // lookup: { 1: "Position 1", 2: "Position 2", 3: "Position 3"}, cellStyle: { textAlign: "center" } }, { title: "Defect Type", field: … -
Where are captcha values usually stored?
Long story short, I made a captcha that can generate from 26letters + digits using pillow that looks cool, Now I need a way to verify that captcha value without the using of database A practical and easiest way of doing this is with sessions, It does not require read or write to the DB, But since cookies are stored on the frontend, I don't think this is a very secure way of storing the value of the captcha, I want the attacker to actually decode captcha using machine learning and not session value which I assume would be easier for the attacker to do. Is there a way to hot verify them? Even with the use of APIs it changes nothing, In this case APIs would be just like sessions and the only difference would be sending value to another function vs sending value to another url. Are there any other alternatives to where these "single use only values" are stored? Or Is there truly a way to hot verify I haven't thought of? -
Payment subscription using PayPal and Django is this possible if the user does'nt have account with paypal
I develop an app using Django and i want a user to be able to pay me $5 a months. i found STRIPE but it's not working in my country. I want a user to be able to pay me with credit card or debit card. but is it possible for a user to be able to pay me without opening paypal account, or it is possible for a user to open an account with paypal before he/she can pay me. I get confused.