Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
session id changing after login, so how to preserve session id created before logged in
e-commerce website on django, i am creating a cart either user logged in or not via session_id. For example guest can add an item to it's cart. And cart that created by the session id. Then let's say guest decides to login. So I want to move the guest's cart to logged in user's cart. But when user logged in, session_id is changes. And I can't find the old session id. How can I preserve session id that created before logged in. or is there a better way to accomplish this task. -
Django form - custom user
I created a custom user in django as it follows: class Customer(AbstractBaseUser): ... in my form I imported the class: from account.models import Customer class PostForm(forms.ModelForm): ... client_code = forms.ModelChoiceField(queryset=Customer.objects.all(), required=True, widget=forms.Select( attrs={ 'class':'form-select form-select-sm', 'aria-label':'Default select example', })) ... I run the server and this error is shown: AttributeError: type object 'Customer' has no attribute 'objects' The project structure is: account -- models.py -- forms.py ... post -- models.py -- forms.py ... -
ManagementForm data is missing or has been tampered Django FormTools Wizard
views.py FORMS = [("customer", CustomerModelForm), ("supplier", SupplierModelForm), ("brand", BrandMasterModelForm)] TEMPLATES = {"customer": "add_customer.html", "supplier": "supplier_master", "brand": "add_brand.html"} class MultiStepWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] return render(self.request, "dashboard_inventory.html", {"data":form_data}) urls.py path('manage_sales/', MultiStepWizard.as_view(FORMS), name="MultiStepWizard") forms.py class CustomerModelForm(forms.ModelForm): class Meta: model = Customer fields = ('name','address','contact','email','state','gstin','pan') class SupplierModelForm(forms.ModelForm): class Meta: model = Supplier fields = ('name','address','city','manager','contact') widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'address':forms.TextInput(attrs={'class': 'form-control'}), 'city':forms.TextInput(attrs={'class': 'form-control'}), 'manager':forms.TextInput(attrs={'class': 'form-control'}), 'contact':forms.TextInput(attrs={'class': 'form-control'}), } class BrandMasterModelForm(forms.ModelForm): class Meta: model = BrandMaster fields=('brand_name', 'suppliername') widgets={'brand_name':forms.TextInput(attrs={'class': 'form-control'}),'suppliername':forms.Select(attrs={'id':'choicewa','class': 'form-control','required': 'true'}), } Hi everyone, m trying to use formtool to save multistep forms with my own templates. But I am getting error "ManagementForm data is missing or has been tampered Django FormTools Wizard" while saving first form, then unable to proceed further. Please help. -
Hot to get string in template?
view.py queryset = a:1,2,3|b:1,2,3 # this is category return render(request, 'project/company_ad_write.html', {"data":queryset}) filter.py @register.filter(name='get_category') def get_category(str): str = str.split('|') return str What I want. {{data.category|get_category['0']}} result a:1,2,3 and again str = str.split(':') result a and 1,2,3 Do you have any idea? -
DRF-simple-JWT: New user registered but not able to login
I am able to create a New User using the "register" endpoint. I can the user being created on the admin page as well. When I try to get an access token for the newly created user I get the error "detail": "No active account found with the given credentials". I am correctly passing the valid credentials so I don't know what the problem might be. Here I have demonstrated the same. Here goes the code: serializers.py from rest_framework import serializers from .models import CustomUser from django.contrib.auth.hashers import make_password class RegisterUserSerializers(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('email', 'password') extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def validate_password(self, value: str) -> str: """ Hash value passed by user. :param value: password of a user :return: a hashed version of the password """ return make_password(value) views.py from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import AllowAny from .serializers import RegisterUserSerializers from rest_framework_simplejwt.tokens import RefreshToken class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request): reg_serial = RegisterUserSerializers(data=request.data) if reg_serial.is_valid(): newUser = reg_serial.save() if newUser: context = { "message": f"User … -
how do I check validation error in django
I am trying to validate fields which are filtered by user. if in filtered data have entered any special character then I wish to print validation error in backend. I am getting Invalid data in output if I pass special characters by url. but getting below error invalid data.. Internal Server Error: /sites/live-data/ UnboundLocalError at /sites/live-data/ return render(request, 'live-data.html', {'sites': sites.json(), 'categories': categories.json()}) UnboundLocalError: local variable 'sites' referenced before assignment here is the code Validations.py def validateAlphanumeric(alphanumeric): alphanumeric_pattern = re.compile(r"^[0-9a-zA-Z]*$") validate_alphanumeric = RegexValidator(alphanumeric_pattern, 'Only alphanumeric characters are allowed.') try: validate_alphanumeric(alphanumeric) return True except ValidationError: return False views.py def liveData(request): ip = request.session['ip'] label = "" category = "" status = "" ordering = "" try: ordering = request.GET['order_by'] except: pass try: category = request.GET['category'] status = request.GET['status'] except: pass if not request.user.is_staff: label = request.session['label'] site_url = ip+"/sites/list/" category_url = ip+"/setup/category/list/" if Validations.validateAlphanumeric(category) and Validations.validateAlphanumeric(status): print("valid.") headers = { 'authorization': "Bearer *****", } params = { 'label': label, 'category': category, 'status': status, 'ordering': ordering } sites = requests.request("GET", site_url, headers=headers, params=params) categories = requests.request("GET", category_url, headers=headers) else: print("invalid data..") return render(request, 'live-data.html', {'sites': sites.json(), 'categories': categories.json()}) -
Redirect within a class based view
I'm working with a FormView. In order to access the page, the user has to pass a certain test. Otherwise, they'll be logged out and redirected. Where within this CBV is the best place to put the redirect logic? Thanks! -
Django Images arent showing in HTML template using Dropzone JS
I'm using the dropzone.js on my django project for editing image i send image on submit button my view function show the data but i'm not able to show the on the html template that i have taken from the user. Predefined {'context':context} is visible but when i append it inside my if condition it run successfully but show not appearance on the html template def index(request): allimg = [] userimg1 = "" userimg = "" if (request.method == 'POST'): i=0 img=[] while(request.FILES.get('file['+str(i)+']')!=None): img1=( request.FILES.get('file['+str(i)+']')) print(img1) img.append(img1) i=i+1 for image in img: imgsize=image.size/1024 userimg = Picture(image=image,name=image.name) userimg.save() print(userimg.image.name) # width = int(request.POST.get('imgwidth')) rot = rotater('media/' + userimg.image.name, 90) userimg1 = EditPicture(editimage=rot,name=image.name) userimg1.save() allimg.append([userimg,userimg1]) return render(request, 'imgeditor/Homepage.html',allimg) return render(request, 'imgeditor/Homepage.html') <body> <div class="container"> <form action="/imagerotate/" method="POST" class="dropzone" enctype="multipart/form-data" name="dropZone" id="myDropzone"> {% csrf_token %} <div class="fallback"> <input name="file" type="file" multiple> </div> </form> <button type="submit" value="Submitbtn" id="submit-all" class="btn btn-primary">Submit</button> </div> <div class="container"> {%for userimg,userimg1 in allimg%} <img src="media/{{ userimg.image }}" width=100px height="=100px"> <img src="media/{{ userimg1.editimage }}" width=100px height="=100px"> {% endfor %} </div> </body> <script> Dropzone.autoDiscover = false; const myDropZone = new Dropzone("#myDropzone", { paramName: 'file', autoProcessQueue: false, clickable: true, maxFilesize: 5, params: {}, uploadMultiple: true, parallelUploads: 10, maxFiles: 10, addRemoveLinks: true, // acceptedFiles: … -
Django rest framework: many to many through model write-able
I have a Order model and Item model. Each order consist of multiple Items. I connect the relationship with through model called OrderItem. Below is my code Models: class Order(models.Model): PAYMENT_TYPES = [ ('COD', 'Cash On Delivery'), ('STRIPE', 'Stripe Credit/Debit'), ('PAYPAL', 'Paypal') ] STATUSES = [ (1, 'Process'), (2, 'Completed'), (3, 'Hold') ] number = models.CharField(max_length=255) total = models.FloatField(null=True) credits_issued = models.FloatField(null=True) paid = models.FloatField(null=True) expected_delivery = models.DateTimeField(null=True) payment_type = models.CharField(max_length=255, choices=PAYMENT_TYPES, null=True) date = models.DateTimeField(default=now) status = models.CharField(max_length=2, choices=STATUSES) note = models.CharField(max_length=255, null=True) ordered_by = models.ForeignKey(User, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) items = models.ManyToManyField(Item, through='OrderItem', related_name='orders') class Meta: app_label = 'InventoryApp' db_table = 'order' class Item(models.Model): STATUSES = [ (1, 'Active'), (0, 'Inactive') ] DEFAULT_STATUS = 1 name = models.CharField(max_length=255) quantity = models.IntegerField(null=True) last_bought_price = models.FloatField(null=True) order_by = models.DateTimeField(null=True) file_name = models.CharField(max_length=255, null=True) status = models.CharField(max_length=2, choices=STATUSES) category = models.ForeignKey(ItemCategory, on_delete=models.CASCADE) class Meta: app_label = 'InventoryApp' db_table = 'item' class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField() price = models.FloatField() class Meta: app_label = 'InventoryApp' db_table = 'order_item' unique_together = [['order', 'item']] I wanna know how to make serializers for through model which is writeable. I have written serializers but … -
Nginx not serving static files in production with whitenoise
Everything looks like it should work, but I get a 404 error in console for all static files including css, js and images. What am I doing wrong? Everything else seems to work just fine. nginx.conf server { listen 443 ssl; server_name www.${NGINX_HOST}; ssl_certificate /etc/letsencrypt/live/${NGINX_HOST}/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/${NGINX_HOST}/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/${NGINX_HOST}/chain.pem; location / { proxy_pass http://api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static { autoindex on; alias /myapp/collectedstatic/; } location /media/ { autoindex on; alias /myapp/media/; } } settings.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ... MIDDLEWARE = [ ... 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'collectedstatic') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Is it possible to cycle through django model object fields?
I have a user & user_profile model and I've allowed signup with nullable fields so user can fill profile later but I want the app to check if any profile fields are null after every login. Is it possible to cycle through django model object fields? I tried the below code and got 'uProfile is not iterable' def profile_Populated(usr): for x in usr: if x == 'null': return False return True if profile_Populated(request.user.uProfile) == True: pass else: return redirect("account:profile_edit") -
How to redirecting to a page after registering a user in - Django
After a user successfully registers an account, the webpage redirected to some other locations... I want it to redirect to a specific path, 'products/index' (products is myapp) after successful registration the user logged in automatically. I am here using function based view.. -
Authenticate user if present in the group
I want to authenticate user only if the user in present in a specific group. Can someone tell me how can I do it please ! I am doing this to add user to a group when user signs up but this is also not working def stusignup(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] if not pass1 == pass2: messages.error(request,"Please enter same password!") else: myuser = User.objects.create_user(username=name,password=pass1,email=email) myuser.name = name myuser.email = email myuser.password = pass1 myuser.save() group = Group.objects.get(name='Student') myuser.groups.add(group) return redirect('studentloginpage') return render(request,'stusignup.html') views.py def stuloginpage(request): if request.method == 'POST': user_email = request.POST['email'] pass1 = request.POST['password'] user = User.objects.get(email=user_email,password=pass1) if user.groups.filter(name = 'Student').exists(): if user is not None: login(request,user) return redirect('homepage') #messages.success(request,'Login Succcessful') else: messages.info(request, "Username OR Password is INCORRECT") else: return HttpResponse("You aren't a Student !") I also tried this def is_student(user): return user.groups.filter(name='Student') @user_passes_test(is_student) I need help in adding the user to a group at the time of sign up and then before login checking if the user is in a particular group ! -
How to transfer file from one model to another model?
I have a model in my django app which stores a file. I have made another model in the same app to store the files using foreign key from the 1st model. When a new file arrives in model 1 push the existing file to the model 2, and keep the new file in the model 1 and all the old files in model 2. Does any one have any idea that how can I implement it. -
How can I load media file from js to django's template?
video.js file code here is my js file that has a media file that I want to load in django template. also in the template there is no code for that specific file...the template execute the js file and tries to show the media. After running the server but as I can guess without the {% load static %} tagging django won't show the media and also this {% load static %} tagging is unavailable in django. -
Django: Render text and link from a textfield in database
I am new to web development and currently building a blog. I am trying to render some text that I wrote in a textfield inside the database. The problem is that this text includes a link that redirects to another blog article. This is the textfield from database Some text I want to render in blog with a link <a href="{{ STATIC_URL }}/articles/8-Photogenic-Spiral-Staircases" class="link-within">8 Photogenic Spiral Staircases</a> html <p class="article-redirect">{{ article.redirect|safe|escape }}</p> The HTML is successfully rendered using |safe filter but when I click on the link it displays a 404 error, the requested URL in the error message is Request URL: http://localhost:8000/articles/7-Photogenic-Spiral-Staircases%7B%7B%20STATIC_URL%20%7D%7D/articles/8-Photogenic-Spiral-Staircases In the above requested URL that caused the error, "7-Photogenic-Spiral-Staircases" is the current blog post and "8-Photogenic-Spiral-Staircases" is the blog post that I want to jump to. Can someone help me understand why this is not working and what could be the possible solution? models.py class Articles(models.Model): title = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) summary = models.TextField(blank=True, null=True) redirect = models.TextField(blank=True, null=True) views.py def article(request, slug): article = get_object_or_404(Articles, slug=slug) context = { 'article': article, } return render(request, 'articletemplate.html', context) urls.py urlpatterns = [ path("articles/<str:slug>/", views.article, name="articles") ] -
How do we make a htmx response trigger a form reset?
I am creating a very basic Django messaging application, and would like to use htmx to send and render messages. I am able to post, save the message, and render the partial message without issue. However, I am running into a weird problem where my form textarea is not being reset. So, I would send a message, and after the swap is inserted, my old message would still be in the textarea. This isn't very ideal! I tried to manually clear the textarea by adding an onclick event like so: Html <div id="new-message-div"></div> <form id="message-form" class="chat-form rounded-pill bg-dark" data-emoji-form="" hx-post="{% url "chat:create-message" object.pk %}" hx-target="#new-message-div"> ... {{ message_form }} ... <button class="btn btn-icon btn-primary rounded-circle ms-5" type="submit" onclick="submitForm()"> </button> </form> Script (https://stackoverflow.com/a/14589251/12758446) <script> function submitForm() { var message_form = document.getElementById('message-form'); message_form.submit(); // Submit the form message_form.reset(); // Reset all form data return false; // Prevent page refresh } </script> Despite having the message_form.submit() in the submitForm(), my form is not being submitted, but the textarea is getting reset. Question: How would I go about getting my textarea reset after successfully sending and rendering a message? Django view, based off of https://github.com/legionscript/socialnetwork/blob/84375841429887e394a2a31e1b67919f81a3cb06/social/views.py#L428 def create_message(request, pk): message = None if request.htmx: thread … -
Django login + pasword
[enter image description here][1] [1]: https://i.stack.imgur.com/ECii0.jpg Всем привет уважаемые коллеги! Сразу хочу сказать что, я недавно в IT и только учусь, прошу не употреблять профессиональные выражения, в решении данного вопроса, благодарен заранее! Я развернул проект Django, создал свой проект, хочу свой проект видоизменить, понимаю что основные файлы django лучше не изменять, по этому в корень своего проекта скинул копии файлов: login.html, base.html, base_site.html а так же в папку проекта скопировал файлы стилей: login.css и base.css. Связываю HTML файлы с CSS стилями, но при запуске своего проекта, все равно загружаются CSS файлы django. Подскажите где я ошибся и что делаю не так? Моя задача изменить стандартное отображение ввода окна login + password под свое представление ! -
How to add break to page between parts in django?
I'm creating a page, but for some reason content is not going down but it's going to right. I have tried to use tag br but it's now working. Why is this happening? and... how do I fix it? {% extends "base.html" %} {% load static %} {% block content %} {% include "parts/text_story1.html" %} <br> {% include "parts/text_story2.html" %} <br> <p> <form action="{% url "upload_story" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload Story!"/></p> </form> </p> {% endblock content %} This is how it looks, now it's not important to styling a details but this is a bigger problem. -
Can't see tree when using $tree in django mac terminal
Whenever I try to see my files using $tree, nothing happens. Here is a picture of the code im trying to run. And here is what it is supposed to return. -
Serving Static Files in Heroku
I have a Django and React app hosted on Heroku, the issue is that it does not see my files but everything is completely working in my localhost. It was built successfully on Heroku. Debugging process: Project built successfully Opens App Returns a blank page meaning it is not serving my CSS and js files. Checked Developer tools The Django app requires the CSS and js files to show the template Checked Heroku logs Heroku returns err 404 for those files Check my Deployed files in Heroku I checked to see my files that are deployed in Heroku in my terminal, and they are there. Now, I'm confused, why is it not serving the files, it's not a code problem cos everything is working well in my localhost. Any solutions pls? Thanks. -
How to load part of html page in django?
Before I used to load just part of page in django. Usually it used to be a text that I did not want change often, but I forgot how to do it, now I cannot find it. I have two html docs, in one I want to load other, can you tell me where I made a mistake? Text to load text_story.html <p>Some text!</p> Page where is loaded text about.html {% extends "base.html" %} {% load static %} {% load "parts/text_story.html" %} {% block content %} {% endblock content %} Thanks in advance! -
Django NoReverseMatch error - urls.py path appears to match
In a Django application I am building as a project for an online course, I am expecting a link in one template (entry.html) to direct to a path ("edit") in urls.py with a variable in the url. This should initiate a function called edit in views.py and render the template edit.html. I am getting a NoReverseMatch error ("Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['(?P<entry>[^/]+)/edit$']") after clicking the link in entry.html. If I view page source while on entry.html in the development server, I can see the url matches that in urls.py but I still get this error. In the example below, "maggie" is the value for entryTitle I'm trying to pass. entry.html: {% block title %} {{ entryTitle }} {% endblock %} {% block body %} {{ entry|safe }} <button> <a href="{% url 'edit' entry=entryTitle %}">Edit Entry</a> </button> {% endblock %} urls.py (last path listed is edit) from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry"), path("search", views.search, name="search"), path("new", views.new_page, name="new"), path("wiki/<str:entry>/edit", views.edit, name="edit") ] edit function in views.py from django.http import HttpResponseRedirect from django.urls import reverse class EditPageForm(forms.Form): content = forms.CharField( widget=forms.Textarea(), label="Edit Content:") def … -
how to pass a function in python mock side effect
I want to achieve the following: mocked.side_effect = somefunction and when mocked() gets called I want somefunction() to get executed however, right now when mocked() gets called only the name of the function is returned and not the callable. Note: I don't want to just do mocked.side_effect = somefunction() because that will call the function first and then result in a value. I would like the function to be called when mocked is called -
How do I render {{ STATIC.URL }} from textfield in database django
I am new to web development and currently building a blog. I want to render HTML that I am pulling in from the database. The HTML is successfully rendered by using |safe but I cant seem to render django template tags {{ STATIC_URL }} within the href. Can someone help me understand why this is not working and what could be the possible solution? html <p class="article-redirect">{{ article.redirect|safe|escape }}</p> models.py class Articles(models.Model): redirect = models.TextField(blank=True, null=True) database "redirect" textfield (the string I want to render) <a href="{{ STATIC_URL }}/articles/8-Photogenic-Spiral-Staircases" class="link-within">8 Photogenic Spiral Staircases</a>