Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error when launching the site on django, how to solve it?
enter image description here enter image description here this is the error I get when I run the site on django Here is the code in urls.py Any help would be welcome !! -
Page not found (404) Raised by: views.product_in_category
Good morning. while implementing element_detail Page not found (404) Request method: POST Request URL: http://127.0.0.1:8000/element_detail/ By: zeronine.views.product_in_category There are no categories matching the given search term. ' An error has occurred. The category continued to show up well, but it's not an error about element_detail, but an error about a category, so I'm confused. views.py from django.shortcuts import get_object_or_404 from django.shortcuts import render from zeronine.forms import ElementForm from zeronine.models import * def product_in_category(request, category_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() if category_slug: current_category = get_object_or_404(Category, slug=category_slug) products = products.filter(category_code=current_category) return render(request, 'zeronine/list.html', {'current_category': current_category, 'categories':categories, 'products':products}) def product_detail(request, id, product_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) designated_object = Designated.objects.filter(rep_price='True') element_object = Element.objects.all() value_object = Value.objects.all() return render(request, 'zeronine/detail.html', {'product':product, 'products':products, 'current_category': current_category, 'categories':categories, 'designated_object': designated_object, 'element_object':element_object, 'value_object':value_object}) def element_detail(request, product_code): designated = Designated.objects.all() element_object = Element.objects.all() value_object = Value.objects.all() product = get_object_or_404(Product, id=product_code) if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.value_code = form.cleaned_data['value_code'] element.designated_code = designated element.save() if request.method == "POST": join = Join() join.product_code = Product.objects.get(id=product_code) join.username = request.user join.part_date = request.POST.get('part_date') join.save() return render(request, 'zeronine/list.html', {'form': form}) else: form = ElementForm() return … -
create sub catgeory inside category with add ,edit and delete option
Guys I'm not using default admin panel as I have created my own . Now I want to add category , sub category and Sub sub category options in my self created admin panel Want to implement something like below: Models.py class Category(models.Model): name=models.CharField(max_length=265) active=models.BooleanField(default=False) #13 class Sub_Category(models.Model): category=models.ForeignKey(Category, on_delete=models.CASCADE) name=models.CharField(max_length=265) active=models.BooleanField(default=False) views.py my views.py has function for both category and sub category redirect for category is easy but where shall i redirect sub category to as each particular category accessed has different url def category(request): #context={} if request.method=='POST': post=Category() post.name= request.POST.get('category') #if request.POST.get('status')=='' post.active=request.POST.get('status') post.save() return redirect('/category') else: approval=Category.objects.all().values() queryset=Category.objects.all() check=queryset.exists() a=list(approval) # print(a[0]['name']) if(check ==True): context={ 'sr.no':a[0]['id'], 'name':a[0]['name'], 'active':a[0]['active'], 'check':check, 'query':queryset, } else: context={ 'query':queryset, 'check':check } return render(request,'category.html',context) return render(request,'category.html') @login_required def category_deactivate(request, user_id): user =Category.objects.get(pk=user_id) user.active = False user.save() messages.success(request, "Category has been successfully deactivated!") return redirect('/category') @login_required def category_activate(request, user_id): user =Category.objects.get(pk=user_id) print(user.active) user.active = True user.save() messages.success(request, "Category has been successfully activated!") return redirect('/category') @login_required def category_delete(request,user_id): t=Category.objects.get(pk=user_id).delete() #status=request.POST.get('status') #t=Service_providers.objects.get(id=oid) #t.status=status #t.save() return redirect('/category') @login_required def category_edit(request, user_id): if request.method=='POST': post=Category.objects.get(pk=user_id) post.name=request.POST.get('category') #if request.POST.get('status')=='' post.save() return redirect('/category') else: post=Category.objects.get(pk=user_id) # print(a[0]['name']) if post.active==False: active='Inactive' else: active='Active' context={ 'name':post.name, 'active':active, } return render(request,'category_edit.html',context) return render(request,'category.html') … -
Installed pyocclient got AttributeError: module 'owncloud' has no attribute 'Client'
I am trying to integrate owncloud in my django website using pyocclient package. I installed it using pip install pyocclient then I tried this example code from their documentation but got the error that owncloud has no attr Client This is my code from django.contrib.auth.decorators import login_required import owncloud @login_required def index(request): if request.method == "GET": return render(request, 'home.html') else: f = request.POST['file'] # a txt file public_link = 'https://lblostenzexxx.owncloud.online/index.php/x/3' oc.login('uid', 'password') oc.mkdir('testdir') oc.put_file(f, 'localfile.txt') link_info = oc.share_file_with_link(f) print(link_info.get_link()) return render(request, 'home.html', {'msg':"return"}) Below is console error: System check identified no issues (0 silenced). May 30, 2021 - 03:30:14 Django version 3.1.5, using settings 'owncloud.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [30/May/2021 03:30:14] "GET / HTTP/1.1" 200 1084 [30/May/2021 03:30:14] "GET /static/css/login_signup.css HTTP/1.1" 200 2813 Internal Server Error: / Traceback (most recent call last): File "C:\Users\mhashirhassan22\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mhashirhassan22\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mhashirhassan22\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Work\Others\Upwork\owncloud\owncloud\users\views.py", line 13, in index oc = owncloud.Client.from_public_link(public_link) AttributeError: module 'owncloud' has no attribute 'Client' This is the github link for pyocclient https://github.com/owncloud/pyocclient If there is any alternative to upload, share … -
I am Unable to extend the User Model in the Django
I am unable to extend the User Model with the custom fields so anyone can help me out to solve the problem I tried to extend the user but I unable to do that it shows an error. An error part is also given below to the veiws.py files so please me out to resolve this problem. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class register(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) dob=models.DateField() user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.fname class candidate(models.Model): full_name = models.CharField(max_length=30) position = models.CharField(max_length=30) total_vote = models.IntegerField(default=0) def __str__(self): return (self.full_name,"---------",self.position) views.py def register(request): if request.method == "POST": # Get the post parameters username = request.POST['username'] email = request.POST['email'] fname = request.POST['fname'] lname = request.POST['lname'] dob = request.POST['dob'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check for errorneous input if User.objects.filter(username=username).exists(): messages.error(request, 'This Aadhaar is Already Used') return redirect('home') if User.objects.filter(email=email).exists(): messages.error(request, 'This Email is already Used') return redirect('home') if (pass1 != pass2): messages.error(request, " Passwords do not match") return redirect('home') # Create the user myuser = User.objects.create_user(username, email, pass1) regs = register(fname=first_name,lname=last_name,dob=dob,myuser=myuser) regs.save() messages.success(request, "You are successfully registered") return redirect('home') else: return HttpResponse("404 - Not found") … -
How do you apply design patterns to a framework like django
They say "whoever uses design patterns, writes better code"! I was wondering how can you apply design patterns like Facade, Adapter, Singleton etc to a framework like django. -
How to use Nginx as GRIP compatible proxy
I have an API get_alerts that returns list of alerts stored in a DB collection. I need to convert that into real time API(real time in sense that whenever alert gets added to a DB collection, that new alert should be sent to open connections, there's an API for post_alert too). For that, I have two options, websockets and server sent events. I decided to go with server sent events because I didn't need full duplex communication provided by web sockets and server sent events seemed comparatively simple. Django has a external package Django EventStream. I am following this link . It requires me to use GRIP compatible server. I am using Nginx. I searched but didn't find anything on how to make Nginx a GRIP compatible proxy. Isn't any other package that does it in Django? Do real time APIs require GRIP compatible proxies in other ecosystems too like NodeJS or etc? -
Unable to host two domain on same server with certbot (ssl certificate ) , though both my domain are working with ssl indivisually
I am hosting 2 domains on one server(droplet) in digital ocean using apache - django setup. Have created 2 virtual environment. Both website works without ssl certificate. I have used certbot to install ssl certificate individually . Both the website works with ssl individually .But when i enable both .conf file . I get "500 internal server error" domain1.com.conf file is : WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess domain1 python-home= /var/www/domain1.com/virtualdomain1 python-path= /var/www/domain1.com/domain1 WSGIProcessGroup domain1 <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName domain1.com ServerAlias www.domain1.com ServerAdmin abhayrobotics1908@gmail.com #DocumentRoot /var/www/html Alias /static /var/www/domain1.com/domain1/static <Directory /var/www/domain1.com/domain1/static> Require all granted </Directory> <Directory /var/www/domain1.com/domain1/domain1> <Files wsgi.py> Require all granted </Files> </Directory> # WSGIDaemonProcess domain1 python-home= /var/www/domain1.com/virtualdomain1 python-path= /var/www/domain1.com/domain1> # WSGIProcessGroup domain1 WSGIScriptAlias / /var/www/domain1.com/domain1/domain1/wsgi.py … -
Django user auth across sub domains is not work
I can not seem to get this to work. I would like my users to sign in to the website in the auth subdomain and the session to be recognized across the other domains. The auth subdomain to handle sign-in, sign-up, forgotten passwords... auth.mydomain.com I then have my main domain and the www. subdomain mydomain.com www.mydomain.com settings.py INSTALLED_APPS = [ ... 'django.contrib.sessions', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', #'middleware.ShareSessionMiddleware', See custom middleware below....it didn't help me ... ] SESSION_COOKIE_DOMAIN = ".mydomain.com" my cookie looks like this Name sessionid Content xxx..bux4qn44k.xxx...ofb9q9q9srgdch....xxxx Domain .mydomain.com Path / Send for Same-site connections only Accessible to script No (HttpOnly) Created Sunday, 30 May 2021 at 09:18:29 Logging in works well @ auth.mydomain.com but the session is not recgonised in www.mydomain and mydomain.com. I have tried extending session middleware and changing the COOKIE_SESSION_NAME to example_name from importlib import import_module from django.contrib.sessions import middleware from django.conf import settings class ShareSessionMiddleware(middleware.SessionMiddleware): def process_request(self, request): engine = import_module(settings.SESSION_ENGINE) session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) if session_key is None: # Look for old cookie in request for auth purposes. session_key = request.COOKIES.get('sessionid', None) request.session = engine.SessionStore(session_key) Nothing seems to work. Can anyone help? I'm sure it's something simple. -
Run view on button click
I have a model called Car which has an attribute for view_count. On my analytics page I want to have a button which will reset the view count of all cars. What is the best way to do this? I've made forms before but I'm wondering if I need to do that or if I can call a view in a template. Note: I don't want non-authenticated users running this view. template <button>Reset View Counts</button> views.py @login_required def reset_view_counts(): cars = Car.objects.all().update(view_count=0).save() -
Extend the background div to fill the whole page
I am trying to build a forum. I want to extend the background div to the sides. Currently, the background fills the page by leaving margin-left and margin right unfilled. Here is my home.html: {% extends 'base.html' %} {% load static %} {% block content %} <style type="text/css"> @media (max-width: 768px) { .right-column{ margin-left: 0px; } } @media (min-width: 768px) { .right-column{ margin-left: 20px; } } .blog-post-container{ margin-bottom: 20px; width: 100%; } .create-post-bar{ background-color: #fff; margin-bottom:20px; } .left-column{ padding:0px; } .right-column{ padding:0px; } .lead{ font-size: 17px; color: #000220; text-align: center; } </style> <!-- main content --> <div class="container"> <div class="row"> <div id="particles-js"></div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', "{% static 'particles.json' %}", function(){ console.log('particles.json loaded...'); }); </script> <!-- blog feed --> <div class="left-column col-lg-7 offset-lg-1"> <!-- Top 'create post' bar --> <div class="d-lg-none mb-3"> <div class="card m-auto d-flex flex-column p-3"> <img class="img-fluid d-block m-auto pb-2" src="{% static 'covalent.png' %}" width="72" height="72"> <p class="m-auto"><a class="btn btn-primary" href="{% url 'blog:create' %}">Create post</a></p> </div> </div> <!-- end Top 'create post' bar --> <!-- Blog posts--> {% if blog_posts %} {% for post in blog_posts %} <div class="blog-post-container"> {% include 'blog/snippets/blog_post_snippet.html' with blog_post=post %} </div> {% endfor %} {% else %} <div class="blog-post-container"> {% include 'blog/snippets/blog_post_snippet.html' … -
Django-allauth: Store custom user model column e.g. full_name
I would like to store the combination of first_name and last_name as full_name when a user signs in using Google with django-allauth package. How can I achieve this? Do I need to customize the adapter? Or how can I do this? Thank you. -
Parameter ID from Input to Django url parameter - possible?
I want redirect id="track" from input to parameter "a" in href like you see in below code. But it doesnt return anything. How Can i put value from input to parameter a using django url? -
How to make Django-select2 styling to work
With the details below, I'm not able to get my form details displayed properly. The items display side by side instead of each below each other. I can't see where I went wrong. <form class="add_new container" method="post"> {% csrf_token %} {% for field in form %} <p>{{ field }}</p> {% endfor %}<hr><br> <input type="submit" value="Issue" class="btn btn-outline-primary" class="text-right"> </form> This is the model form class TeacherIssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(TeacherIssueForm, self).__init__(*args, **kwargs) self.fields['issuer'].initial = issuer self.fields['book_id'].queryset = Books.objects.filter(school=school,no_of_books=1) self.fields['borrower_teacher'].initial = pk #Sets the field with the pk and it's hidden again class Meta: model = TeacherIssue fields = ['issuer','book_id','borrower_teacher'] widgets = { 'borrower_teacher':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'book_id':Select2Widget(attrs={'data-placeholder': 'Select Book','data-width': '100%'},) } -
Displaying a python list's values in HTML dropdown using AJAX
I am using Django and AJAX to implement a chained-dropdown. The user will first be prompted to select a brand_name from a dropdown, and depending upon the brand_name selected, all the names of the products that are made by that brand will be displayed in the second dropdown. views.py def chained_dropdown(request): if request.method == "POST": brand = request.POST['brand'] print(brand) sort_by_brand = list(models.Product.objects.filter(brand=brand).order_by('product_id').values('product_id', 'product_name')) data = { 'SortByBrand': sort_by_brand } return JsonResponse(data) AJAX request: var brand = $('#brand').val() $.ajax({ type: "POST", url: "/changeddropdown", data:{ "brand": brand, }, success: function (data){ // What should I do here? console.log(data) }, }) templates snippet: This is where I want the product names to be displayed, and the option value should be their corresponding product_id. <label for="product_id"> Product ID</label> <select name="product_id" id="product_id"> <option disabled selected="true"> --Select -- </option> <option value=""> </option> </select> For your reference, this is what console.log(data) prints: {SortByBrand: [{product_id: 31, product_name: "Lotion"}, {product_id: 32, product_name: "Deo"}]} I am having trouble displaying this information in the template, any help would be greatly appreciated. -
How do i set attributes on a single option of a CheckboxSelectMultiple ChoiceWidget in django?
I have a django app with multiple choice questions and answers. The unanswered answers are stored as BooleanFields in a database table and rendered as a form to be answered by the user. When the user has answered the multiple choice question, the question with the given answers is to be displayed again to show if each single multiple choice option was correct or incorrect answered. Thus, we need to tag each single generated CheckboxWidget widget with a special css attribute so the correctness of the answer can be properly styled in the output html to give visual feedback to the user. models.py from django.db import models ... class SchulungsEinheitTestergebnis(models.Model): """ Schattentabelle eines Testergebnisses einer Frage eines Schulungseinheittestes """ id = models.AutoField('ID', primary_key=True, db_column='sete_id') schulungseinheittest = models.ForeignKey(SchulungsEinheitTest, db_column='set_id', on_delete=models.CASCADE, null=True, default=None, blank=True) frage = models.ForeignKey(Frage, db_column='frg_id', on_delete=models.SET_NULL, null=True, default=None, blank=True) antworten = models.ManyToManyField(Antwort, blank=True, help_text='Gegebene Antworten', related_name='set_set', forms.py from django import forms from django.forms.widgets import CheckboxSelectMultiple class TestErgebnisFormMehrfach(forms.ModelForm): class Meta: model = SchulungsEinheitTestergebnis fields = ('id', 'frage', 'antworten') widgets = { 'frage': FrageWidget, 'antworten': CheckboxSelectMultiple } def __init__(self, *args, **kwargs): super(TestErgebnisFormMehrfach, self).__init__(*args, **kwargs) if self.instance: if self.instance.frage: self.fields['antworten'].queryset = self.instance.frage.antwort_set.all() class TestErgebnisFormMehrfachErgebnis(TestErgebnisFormMehrfach): def __init__(self, *args, **kwargs): super(TestErgebnisFormMehrfachErgebnis, self).__init__(*args, **kwargs) self.fields['antworten'].disabled … -
IntegrityError at /join/join_create/ NOT NULL constraint failed: zeronine_join.product_code
I am a student who is studying Django for the first time. I am currently experiencing the same error as the title. How do I resolve these errors? If I press the join button, I want to save the product information in the DB, is there anything wrong with my code? I'd appreciate it if you could give me an answer. join/views.py def join_create(request): product = Product.objects.all() categories = Category.objects.all() if request.method == "POST": join = Join() join.product_code = request.GET.get('product_code') join.username = request.user join.part_date = request.GET.get('part_date') join.save() return render(request, 'zeronine/detail.html', {'product': product, 'categories':categories}) zeronine/views.py def product_in_category(request, category_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() designated_object = Designated.objects.filter(rep_price='True') if category_slug: current_category = get_object_or_404(Category, slug=category_slug) products = products.filter(category_code=current_category) return render(request, 'zeronine/list.html', {'current_category': current_category, 'categories':categories, 'products':products, 'designated_object': designated_object}) def product_detail(request, id, product_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) options = Option.objects.all() values = Value.objects.all() designated_object = Designated.objects.filter(rep_price='True') return render(request, 'zeronine/detail.html', {'product':product, 'products':products, 'current_category': current_category, 'categories':categories, 'designated_object': designated_object, 'options':options, 'values':values}) join/urls.py from django.urls import path from .views import * urlpatterns = [ path('join_create/', join_create, name='join_create'), ] models.py class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = … -
Django Oscar Image saved in cache folder but not showing
Could anyone point me the direction to solve the image not displaying properly, since the image was saved in cache folder with 500 error. I am not sure if it is to due to permission or something deeper? This is what I had configure but not sure if I doing it right. URLS.py: from django.apps import apps from django.urls import include, path from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from oscar.views import handler403, handler404, handler500 urlpatterns = [ path('admin/', admin.site.urls), path('', include(apps.get_app_config('oscar').urls[0])), ] if settings.DEBUG: import debug_toolbar # Server statics and uploaded media urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Allow error pages to be tested urlpatterns += [ path('403', handler403, {'exception': Exception()}), path('404', handler404, {'exception': Exception()}), path('500', handler500), path('__debug__/', include(debug_toolbar.urls)), ] Setting.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = '/media/' MEDIA_URL = '/media/' THUMBNAIL_DEBUG = DEBUG THUMBNAIL_KEY_PREFIX = 'oscar-sandbox' THUMBNAIL_KVSTORE = env( 'THUMBNAIL_KVSTORE', default='sorl.thumbnail.kvstores.cached_db_kvstore.KVStore') THUMBNAIL_REDIS_URL = env('THUMBNAIL_REDIS_URL', default=None) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) -
I am working on python django and have a registration form there are fields like username email password want to check if exists
I have a html form where there are fields like username, email, password I want to check individually if username exists or not by entering username also email exists or not by entering email in the html form also check both at same time if both exists or not the code I have written for this is not working for single field what I meant is if I enter only username it says username is taken also email is taken But I don't want that I want individually they exists or not and if I enter both existing email and username it should say email is taken and username is taken by displaying message. How can I modify the code to work like that This is my views.py code def Register(request): try: if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') try: email_taken = User.objects.filter(email=email).exists() username_taken = User.objects.filter(username=username).exists() if email_taken: messages.error(request,"Email is taken.") if username_taken: messages.error(request,"Username is taken.") if email_taken or username_taken: return redirect('/register/') user_obj = User(username = username , email = email) user_obj.set_password(password) user_obj.save() profile_obj = Profile.objects.create(user = user_obj ) profile_obj.save() return redirect('/login/') except Exception as e: print(e) except Exception as e: print(e) return render(request … -
How to use div for background in html
Hi I am trying to build a website, and I am trying to use particles.js as my background and display the content in overlaying manner. However, it is displaying it on top of the page instead of the background. When I set its position as absolute, its changes the format of my website. How can I set that div as the background? I have my background div id set as particles-js here is my code for base.html: <!DOCTYPE html> <html lang=en> {% load static %} {% static 'style.css' %} {% static 'particles.json' %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> {% include 'snippets/base_css.html' %} {% include 'snippets/header.html' %} <!-- Body --> <style type="text/css"> .main{ min-height: 100vh; height: 100%; } </style> <div class="main"> <div id="particles-js"></div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', "{% static 'particles.json' %}", function(){ console.log('particles.json loaded...'); }); </script> {% block content %} {% endblock content %} </div> <!-- End Body --> {% include 'snippets/footer.html' %} </body> </html> this is my home.html: {% extends 'base.html' %} {% block content %} <style type="text/css"> @media (max-width: 768px) { .right-column{ margin-left: 0px; } } @media (min-width: 768px) { .right-column{ margin-left: 20px; } … -
labels are not showing in views cleaned_data
I am building a PollApp and I am stuck on a Problem. I am trying to add labels in cleaned_data in views.py BUT labels are not showing in browser. forms.py class PollAddForm(forms.ModelForm): choice1 = forms.CharField(label='Choice 1', max_length=100, min_length=2, widget=forms.TextInput(attrs={'class': 'form-control'})) choice2 = forms.CharField(label='Choice 2', max_length=100, min_length=2, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Poll fields = [ 'choice1', 'choice2'] labels = { 'choice1': "First Choice", 'choice2': "Second Choice", } views.py def polls_add(request): if request.user.has_perm('polls.add_poll'): if request.method == 'POST': form = PollAddForm(request.POST) if form.is_valid: poll = form.save(commit=False) poll.owner = request.user poll.save() new_choice1 = Choice(poll=poll,labels='First Choice', choice_text=form.cleaned_data['choice1']).save() new_choice2 = Choice(poll=poll,labels='Second Choice', choice_text=form.cleaned_data['choice2']).save() return redirect('home') else: form = PollAddForm() context = { 'form': form, } return render(request, 'add.html', context) else: return HttpResponse("Sorry") I have tried many times by adding labels forms and views but still not showing browser. Any help would be really Appreciated. Thank You in Advance. -
Get error messages in django_rest_framework in a json format
I want to get an error message { "phone": [ "user with this phone already exists." ] } in a JSON format like {"error": "user with this phone already exists."} from the response HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "phone": [ "user with this phone already exists." ] } but what I am getting is just VM8:1 POST http://127.0.0.1:8000/users/ 400 (Bad Request) Here is my code: Serializers.py class UserCreateSerializer(UserCreateSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'email', 'phone', 'stream', 'school', "password", ) -
Update or create does not update and only creates
@require_http_methods(["POST"]) @login_required def edit_question(request): req = json.loads(request.body) question_no = req["question_no"] guided_answers=req["guided_answer"] for guided_answer in guided_answers: obj, created= models.ModelAnswer.objects.update_or_create( question_id=models.Questions.objects.get(pk=question_no), model_ans= guided_answer["model_ans"], answer_mark=guided_answer["answer_mark"], defaults={ 'answer_mark':guided_answer["answer_mark"], 'model_ans':guided_answer["model_ans"], } ) return success({"res": True}) What i am trying to do is update or create based off checking whether the model answer already exist or not in the database however everytime i try to update an existing model answer it creates it into a new one, i do not understand why it does not filter out if it exists or not,i do not know whether it is my filter or my defaults that is wrong -
How to solve POST http://127.0.0.1:8000/bkash/payment/create 403 (Forbidden) ?(Django + ajax)
I used "django-bkash-integration 0.3" https://pypi.org/project/django-bkash-integration/ with my project to integrate bkash payment gateway. Bkash also provide me BKASH_APP_KEY = // bkash app key BKASH_APP_SECRET = // bkash app secret BKASH_APP_USERNAME = // bkash app username BKASH_APP_PASSWORD = // bkash app password BKASH_APP_VERSION = // bkash app version BKASH_APP_BASE_URL = // bkash app base url According bKash Checkout Script https://developer.bka.sh/docs/bkash-checkout-script connect it from the frontend. template link: https://github.com/MdNazmul9/bkash-front-end-problem/blob/main/templates/bkash_index.html I always get POST http://127.0.0.1:8000/bkash/payment/create 403 (Forbidden). How can I solve it ? -
django argon2password hasher behaves weird
screenshot of pip list and error I have already installed argon2password hash in virtual environment and by pipenv list it shows that already there, also while re-installing it shows already have met the requirements. But while giving password for login it shows ValueError at /login/ Couldn't load 'Argon2PasswordHasher' algorithm library: No module named 'argon2' what's the actual problem?? I couldn't resolve it.