Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError after POST request in Django
I am making a post request to a Django server I am running locally. I am sending the request to http://127.0.0.1/login/. Here is the view @csrf_exempt def login(request): json_data = json.loads(request.body.decode('utf-8')) print(json_data) return request.body I have @csrf_exempt for now only just so that I won't have to make a view to get the csrf token. When I send the POST request it works and prints out the json I sent with the request yet it also prints out this error. Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\Moham\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Moham\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\deprecation.py", line 119, in __call__ response = self.process_response(request, response) File "C:\Users\Moham\AppData\Local\Programs\Python\Python37\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'bytes' object has no attribute 'get' The reason this is confusing me is because I have made no reference to any object called "bytes" or any attribute called "get". Anyone know what is going on here? -
Can't see custom field in Django Admin page
I'm trying to create my own User class called Customer which extends the AbstractUser model and has an additional field called address. When I register, I see the user has been created in Django admin and all the fields (username,first name, last name and email) are seen in the django admin scrren but I see no value in the "address" field. How do I know if the address is being saved and how can I display it in the admin site? Below is my code for the models.py class Customer(AbstractUser): username = models.CharField(unique=True, max_length=20) deladdress = models.CharField(max_length=100) views.py def signupPage(request): signForm = CreateCustomer() if request.method=='POST': signForm = CreateCustomer(request.POST) if signForm.is_valid(): signForm.save() return render(request, 'trial_app/signup.html', {'signForm':signForm}) forms.py class CreateCustomer(UserCreationForm): address = forms.CharField(widget=forms.Textarea) class Meta: model = Customer fields = ['username','first_name','last_name','email','address','password1','password2'] def save(self, commit=True): user = super(CreateCustomer, self).save(commit=False) user.address = self.cleaned_data["address"] if commit: user.save() return user Here are some pictures that are the input to my html form and the value in the admin site -
How can i get username insted of userid?
model.py class Review(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) review = models.CharField(max_length=500) date_reviewed = models.DateTimeField(auto_now_add=True) views.py def review(request): if request.method=="POST": if request.user.is_authenticated: sender = request.user review=request.POST['review'] pid = request.POST['pid'] product=Product.objects.get(id=pid) print(user) rev = Review(user=sender,product=product,review=review) rev.save() reviews = Review.objects.filter(product=pid).values() da=list(reviews) print(da) return JsonResponse({'reviews':da}) Expected output: [{'id': 6, 'user_name': sandeep, 'product_id': 2, 'review': 'lknkk', 'date_reviewed': datetime.datetime(2021, 5, 1, 13, 2, 12, 404779, tzinfo=<UTC>)}] I am trying send this data to my frontend using jsonresponse to create a product review table but in the output i am getting user_id insted of user_name .is there any way to pass user_name? Here is actual output: [{'id': 6, 'user_id': 2, 'product_id': 2, 'review': 'lknkk', 'date_reviewed': datetime.datetime(2021, 5, 1, 13, 2, 12, 404779, tzinfo=<UTC>)}] -
Django:django.db.utils.IntegrityError: FOREIGN KEY constraint failed
What I m trying to do is when a user return cylinder then the record of that user in the issue cylinder will be deleted and if the availability of the return cylinder is yes then update the cylinder Availability will be updated as "available" else the cylinder entry will be deleted. But when I try to do so it displays the following error : Traceback (most recent call last): File "C:\python3.9\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\python3.9\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed It was working fine until unless I have set the return Availability "no". here is models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId class IssueCylinder(models.Model): cylinder=models.OneToOneField('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName class ReturnCylinder(models.Model): rechoice=[ ('fill','Fill'), ('empty','Empty') ] reav=[ ('Yes','yes'), ('No','no') ] Cylinder=models.OneToOneField('CylinderEntry',on_delete=models.CASCADE) user=models.ForeignKey('IssueCylinder',on_delete=models.CASCADE) status=models.CharField(max_length=20,choices=rechoice) returnDate=models.DateTimeField(default=timezone.now) Availability=models.CharField(max_length=5,choices=reav) def save(self,*args,**kwargs): if not self.pk: IssueCylinder.objects.filter(userName=self.user.userName).delete() if self.status=='yes'or self.status=='Yes': CylinderEntry.objects.filter(cylinderId=self.Cylinder.cylinderId).update(Availability=('available')) else: CylinderEntry.objects.filter(cylinderId=self.Cylinder.cylinderId).delete() super().save(*args,**kwargs) def __str__(self): return self.user.userName+" returned "+self.cylinder.cylinderId … -
How to write Case query in raw sql
I want to write a view using raw sql(I know that it's better to use ORM, I just need to use only SQL in my work). However, CASE does not work in a query. Does RAW support case or no? Here is my view: def profile(request): cursor = connection.cursor() cursor.execute('SELECT * from Lesson ' 'WHERE CASE WHEN(LName = %s) THEN (LName = %s) END', ['Algebra', 'English']) objects = dictfetchall(cursor) return render(request,'personal.html', {'objects':objects}) It returns the following error Invalid syntax around '=' -
Django: extra_content for class based view not displaying any data
I am trying to make a site that displays all of the items in a "case", and at the top I want to display the total value of all of the items in the "case". To get this number you would get all of the items in the case, multiply their value and quantity and add them all up. However when I pass this to my extra_content nothing is displayed.Any help would be awesome! My View: class CaseHome(ListView): model = CaseItem template_name = 'mycase/casehome.html' total = CaseItem.objects.all().aggregate(total=Sum(F('Item_Price')*F('Item_Quantity')))['total'] extra_content = {'my_total': total} My Model: class CaseItem(models.Model): Item_Title = models.CharField(max_length=200) Item_Price = models.DecimalField(default=0, max_digits=10, decimal_places=2) Item_Quantity = models.DecimalField(default=0, max_digits=10, decimal_places=2) def __str__(self): return self.Item_Title + ' | ' + str(self.Item_Quantity) + ' * $' + str(self.Item_Price) def get_absolute_url(self): return reverse('home') My Template: {% block content %} <p>{{my_total}}</p> {% for item in object_list %} <div class="container"> <div class="item" style="border: 2px solid black; margin: 3px; padding: 3px"> <a href="{% url 'item-editor' item.pk %} "><h3 style="display: inline-block">{{ item.Item_Title }}</h3><h5 style="float: right"><span class="badge bg-info text-dark">Quantity:{{ item.Item_Quantity}}</span> <span class="badge bg-info text-dark" style="margin-left: 15px;"> Price: ${{item.Item_Price}} </span> </div> </h5></a> <hr> </div> {% endfor %} {% endblock %} -
which of the framework is good for a dating website?
I want to find out which of this frame work is good for a dating website, Node.js, Laravel ,flask and Django. This adult dating does not have video feature for now but will be added in the feature. Note, I will start in a shared hosting before dedicated IP -
Django Channels: How to pass incoming messages to external script which is running outside of django?
I have started a private project with Django and Channels to build a web-based UI to control the music player daemon (mpd) on raspberry pi. I know that there are other projects like Volumio or moode audio etc. out of the box that is doing the same, but my intension is to learn something new! Up to now I have managed to setup a nginx server on the pi that communicates with my devices like mobile phone or pc. In the background nginx communicates with an uWSGI server for http requests to Django and a daphne server as asgi for ws connection to Django Channels. As well there is a redis server installed as backend because the Channels Layer needs this. So, on client request a simple html page as UI is served and a websocket connection is established so far. In parallel I have a separate script as a mpd handler which is wrapped in a while loop to keep it alive, and which does all the stuff with mpd using the python module python-mpd2. The mpd handler shall get its commands via websocket from the clients/consumers like play, stop etc. and reacts on that. At the same time, … -
i can't load DOM elements in multiple html files in the same js file
I am working with Django and using base.html, I have tried putting js file in base.html it didn't worked and after that one in main.html file, still its not working ,I am trying to implement a darkmode functionality in my webapp but this hinders the process.the darkmode button is in navbar in base.html, let darkmodebtn=document.querySelector(".darkmodebtn") let cardark=document.querySelectorAll(".cardtotoggle") console.log(cardark) darkmodebtn.addEventListener('click', function(e) { e.preventDefault() body=document.body body.classList.toggle("dark"); cardark.forEach(function(node){ var superToggle = function(element, class0, class1,class2) { element.classList.toggle(class0); element.classList.toggle(class1); element.classList.toggle(class2); } superToggle(node,'bg-dark','text-light'); console.log(node.className); }); }); this is the JavaScript code I am trying to implement, i was using bootstrap and was to able to implement bg-color to the card background so used foreach and the cards are formed using {%for%} template tag. Can someone explain what is the proper method to use JavaScript to include multiple html-files DOM elements -
apply a css class to all fields and one more class to two different fields
I have this __init__ inside a ModelForm class that I am using to apply CSS to all fields but want to apply another class to two different fields. So, I want all fields to have class-a but, field1 and field2 should also have class-b def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) for i, f in self.fields.items(): f.widget.attrs['class'] = "class-a" if f in ['field1', 'field2']: f.widget.attrs['class'] = "class-a class-b" class-a is added to all input fields, but class-b is not added to field1 and field2 -
Why I am getting 500 internal error on django-template?
I am trying this view on ubuntu v20.04 and apache2 with Django WSGI. I have an ajax post function on my Django template. $.post({ method: 'POST', url: "{% url 'Bot:retroactive' %}", data: {'market': market_name, 'date' : date.value, 'deletecheck':deletecheck.checked, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { toastr.success( market_name+" botu "+date.value+" tarihli veriyi başarıyla çalıştırdı.", { onHidden: function () { window.location.reload(); } } ); }, error: function (data) { console.log(data) console.log('error') } }); And my view is : if request.POST: market = request.POST.get('market') date = request.POST.get('date') deletecheck = request.POST.get('deletecheck') print(market,date,deletecheck) return HttpResponse(status=200) There is no problem when I run this view on localhost or on a server with manuel port (0.0.0.0:3939) When I run on the apache2 ubuntu server I am getting the following error: POST https://xxx.xxx.com/xxx/xxx/ 500 (Internal Server Error) send @ vendor-all.min.js:3 ajax @ vendor-all.min.js:3 xe.<computed> @ vendor-all.min.js:3 (anonymous) @ (index):379 Do you have any suggestion to fix it? -
problems when installing django-inventory
that's what shows when i'm trying to install django-inventory {python version 3.9} {pillow version 8.2.0} at the beginning of the Error : Running setup.py install for Pillow ... error ERROR: Command errored out with exit status 1: at the end of the Error : Rolling back uninstall of pillow because of the length of the Error i couldn't write it all. so please can anybody help me :( -
How do I reorder a list of objects manually using Django, Python, (and possibly Javascript)?
Here is my code. models.py from django.db import models class Photo(models.Model): file = models.ImageField(upload_to='media/images') class Album(models.Model): title = models.CharField(max_length=100) photos = models.ManyToManyField(Photo,related_name="photos",blank=True) admin.py from django.contrib import admin from .models import Photo, Album # Register your models here. class AlbumAdmin(admin.ModelAdmin): list_display = ("title","published") filter_horizontal = ("photos",) def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "photos": kwargs["queryset"] = Photo.objects.order_by("-id") return super(AlbumAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Photo) admin.site.register(Album, AlbumAdmin) views.py from django.shortcuts import render from django.conf import settings from .models import Photo, Album # Create your views here. def album(request, album_title): album = Album.objects.get(title=album_title) context = { "album":album, } return render(request, "photos/album.html", context) I am trying to achieve a page that shows the photos in each album and has a drag-and-drop function that allows a manual re-ordering of the photos in each album. Then I wish to save the order of the album. The only problem is, I have no clue to how to do this. -
trying to implement stripe "AttributeError: sources"
i am getting an error when submiting Credit Card information Saying ("AttributeError at /API/CheckOut/" sources) i think it's comming from here but i don't know what the problem is views.py class PaymentView(APIView): def post(self, request, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) userprofile = UserProfile.objects.get(user=self.request.user) token = request.data.get('stripeToken') if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: customer = stripe.Customer.retrieve( userprofile.stripe_customer_id) customer.sources.create(source=token) else: customer = stripe.Customer.create( email=self.request.user.email, ) customer.sources.create(source=token) userprofile.stripe_customer_id = customer['id'] userprofile.one_click_purchasing = True userprofile.save() i am using React on the frontend and Posting the Token like this const {error, paymentMethod} = await stripe.createPaymentMethod({ type: 'card', card: cardElement, }); const stoken=paymentMethod.id if (error) { seterror(error) setloading(false); } else { seterror(null) axios .post(checkoutURL, { stoken, selectedBillingAddress, selectedShippingAddress }) -
PyCharm - Django shell/shell_plus in Debug mode - autocomplete
I've created a configuration in PyCharm that allows me to debug Django shell/shell_plus. It works correctly but I would like it also to autocomplete methods and attributes like it does when executed this way: python manage.py shell_plus It probably needs to use iPython which I installed but I don't know where to set this up. Do you know what to do? -
Why does not date input does not return None if nothing is passed?
Here is my html code <form method="GET" class="container mb-5"> <label for="inputDate">Enter the date:</label> <div class="row"> <div class="col-3"> <div class="row"> <div class="col-1 mr-2">С:</div> <input class="col-10" type="date" class="form-control" name="searchdate" value="{{ value1 }}"> </div> </div> <div class="col-3 ml-3"> <div class="row"> <div class="col-1 mr-3">До:</div> <input class="col-10" type="date" class="form-control" name="searchto" value="{{ value_3 }}"> </div> </div> </div> <button type="submit" class="btn btn-outline-primary px-5" >Search</button> </form> {{ value1 }} {{ value_3 }} and here is my views: def profile(request): value_one = request.GET.get("searchdate", None) value_three = request.GET.get("searchto", None) return render(request,'personal.html',{'value1':value_one,'value3':value_three}) The date appears in html only if I input something, but when I don't set any date it is just blank page, however on the website should be displyed 'None None', shouldn't it? -
Reorder django core functionality
I faced with the problem of Django multi site project. Each site can handle multiple languages. Project handle languages by url and we don’t use default language prefix. For example Site one: root / specify russian language and /en specify english version of site (default language is russian) Site two: root / specify english language and /ru specify russian version of site (default language is english) Django has a problem. Framework cache resolver and store prefixes for some sites. When I begin to use different default languages for different domains I was confuse with wrong prefixes. I must change behavior of django get_resolver() function becouse of hist @functools.lru_cache decorator (this is django file): def get_resolver(urlconf=None): if urlconf is None: urlconf = settings.ROOT_URLCONF return _get_cached_resolver(urlconf) @functools.lru_cache(maxsize=None) def _get_cached_resolver(urlconf=None): return URLResolver(RegexPattern(r'^/'), urlconf) Can I do something to disable cache? Or make cache depend of site? I tried to reorder function in django core module My solution is: from django.urls.resolvers import URLResolver, RegexPattern @functools.lru_cache(maxsize=None) def get_resolver_for_site(site_id, urlconf): return URLResolver(RegexPattern(r'^/'), urlconf) def _get_cached_resolver_for_site(urlconf=None): return get_resolver_for_site(get_site().id, urlconf) @receiver(post_save, sender=SiteSettings) def clear_url_resolver_cache(sender, **kwargs): get_resolver_for_site.cache_clear() resolvers._get_cached_resolver = _get_cached_resolver_for_site So I defined custom function, that return url resolver and cache it depend of site. I think this is … -
Django Template - If both IF statements are empty
I know how to use an if statement in django, and if the if is empty. Like this: {% if results %} <!-- True --> {% else %} <!-- False --> {% endif %} Now how do I do this if I have more than on if statement like this: {% if users %} <!-- Users is true --> {% endif %} {% if results %} <!-- Results is true --> {% endif %} <!-- Problem: --> {% if results and users %} <!-- Both are true --> {% else %} <!-- Do only if both are false --> {% endif %} So I tried using if and but it didn't work, even if one existed it still ran the stuff in the else. So how do I make sure it checks if both statements are false, and only if they are both false, to run the else. Any suggestions? -
improperly configured database, django+python+postgres
I was working on a login page and it worked, abandoned the project for a couple of months and when I got back to it I was getting this error: settings.DATABASES is improperly configured. Please supply the NAME value. Full Traceback Traceback (most recent call last): File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\sites.py", line 410, in login return LoginView.as_view(**defaults)(request) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\views.py", line 63, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\edit.py", line 141, in post if form.is_valid(): File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 177, in is_valid return self.is_bound and not self.errors File "C:\Users\Zeyad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 172, in errors self.full_clean() … -
FOREIGN KEY constraint failed - Django
So I'm trying to make a delete route for my API but I'm encountering a problem. Whenever I hit the delete route I get an error which is django.db.utils.IntegrityError: FOREIGN KEY constraint failed. I'm trying to delete a model if the delete route is hit. I have done makemigrations and migrate but there were no changes. Example of my code is like this: class RandomAPIView(APIView): def delete(self, request, id, format=None): product = Product.objects.get(pk=id) product.delete() return Response({'Success':'Product has been deleted'}) product in models.py class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name -
Django Iterating through Queryset and taking user input
have a query on Django. I have a model as follows - class FileSheetData(models.Model): file = models.ForeignKey(File,related_name='sheet',on_delete=models.CASCADE) var_2 = models.BooleanField(blank=False,default=False) var_3 = models.PositiveIntegerField(blank=False,default=0) I want to create a view which iterates through a filtered queryset within this model and allows the user to update the var_2 and var_3 for each instance in the model? What's the best way to do this? -
Method that count minutes from post publishing
I'm writing small social web application using Django. So I need to count minutes from post publishing (e.g like it looks in Twitter) I tried to do something like this: class Post(models.Model): # post model fields @property def publish_date(self): if self.date >= (timezone.now() - datetime.timedelta(hours=1)): return f'{timezone.now().minute - self.date.minute} minutes ago' else: return self.date And use it into HTML like this: <span id="post_date">{{ p.publish_date }}</span>, where p is post instance But sometimes it's returns negative values (like in example below) So how can I correctly realize this? -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/Profile_pics/itachi.jpg
i am trying to load profile picture for each user default profile picture for user is default.jpg But Happning is i am unable to load profile picture Page Not found Error occurs. after running my program the media directory created in my project file with Profile_picture directory and i saved my default.jpg in media and uploaded profile picture are saved in Profile_picture Model i created for profile picture is : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(default='default.jpg',upload_to='Profile_pics') settings i changed in my project are: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Settings i changed what said in documentation are from django.contrib import admin from django.urls import path,include from users import views as user_view from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('CovidHelp.urls')), path('profile/',include('users.urls')), path('register/',user_view.register,name='register'), path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ERROR I AM GETTING IS: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/Profile_pics/itachi.jpg Using the URLconf defined in MyCovidHelp.urls, Django tried these URL patterns, in this order: [name='Home'] about/ [name='About'] profile/ register/ [name='register'] login/ [name='login'] logout/ [name='logout'] admin/ ^static/(?P<path>.*)$ The current path, media/Profile_pics/itachi.jpg, didn't match any of these. -
When trying to set a django session value, I have Type Error "Object of type Decimal is not JSON serializable" while it is a string value. Why?
I would like to record a discount code from input users. I have set up a UserDiscountForm(forms.Form) (in forms.py). In the view, I would like to record in the session, the data that a user inputs. But when I try to set the value (after checking that the form is valid), it raises a TypeError: "Object of type Decimal is not JSON serializable". I don't understand because the data I am trying to save is a string value. In addition, I am able to save other data in the session (a shopping cart and a shipping address) the similar way and it works perfectly. forms.py (user_input is a string) from django import forms class UserDiscountForm(forms.Form): user_discount = forms.CharField(label='discount code ?', label_suffix="-->", help_text="Entrez discount code", required=False) def clean_user_discount(self, *args, **kwargs): user_input = self.cleaned_data['user_discount'] if len(user_input) > 4: raise forms.ValidationError("longueur > 4") else: print(type(user_input)) return user_input views.py (form.cleaned_data['user_discount'] is a string) from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from . basket import Basket from store.models import Product from discount.forms import UserDiscountForm def basket_summary(request): basket = Basket(request) form = UserDiscountForm(request.POST or None) context = {'basket':basket, 'form':form} if request.method == 'POST': if form.is_valid(): print(form.cleaned_data['user_discount']) print(type(form.cleaned_data['user_discount'])) request.session['discount_code'] = form.cleaned_data['user_discount'] form = UserDiscountForm() context … -
Django Country State City Chained Dropdown
Configuration: I have created 2 apps csc and members. CSC: contains country, state, city and Users contains a custom user model. The users model using foreign keys to access country, state and city from CSC app. The CSC database contains all the countries, states, cities. And i am displaying user list in fronend and also an option to filter the content by country, state, city by django-filter. I am using django smart_selects to chain them in admin. Question: I wanted to show only those countries, states and cities, which has the members not all my country database. and also i wanted to link those 3 dropdowns. CSC - Models.py class Country(models.Model): name = models.CharField(_('Country'), max_length=255, null=True) country_code = models.CharField(_('Code'), max_length=10, null=True) iso_code_short = models.CharField(_('ISO Code Short'), max_length=2, null=True) iso_code_long = models.CharField(_('ISO Code Long'), max_length=3, null=True) def __str__(self): return self.name class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(_('State'), max_length=255, null=True) def __str__(self): return str(self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) state = ChainedForeignKey('State', chained_field="country", chained_model_field="country", show_all=False, auto_choose=True) name = models.CharField(_('City'), max_length=255, null=True) def __str__(self): return str(self.name) Members - models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('Email'), max_length=255, unique=True) first_name = models.CharField(_('First Name'), max_length=100, null=True, blank=True) last_name = models.CharField(_('Last Name'), …