Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best practice in avoid page reload issue during payment
I have been coding a Django ecommerce project and there is a issue with page reload during payment that causes my program to crash. When the customer uses their mobile device the workflow is: Customer fills in a form with: name email some comments The form is being sent to the backend via a post. A new html page is rendered together with the payment UI embebbed in the same page. The payment UI is rendered by payment vendor's javascript code Customer enters a mobile phone number in the payment UI to allow MobilePay payment option and clicks Pay. Now another app installed on client's phone the MobilePay app opens, and the customer confirms the payment there. Immediately as the client is being diverted to this app my website generates a new page with error This web page requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. Press the reload button to resubmit the data needed to load the page ERR_CACHE_MISS Then at MobilePay app once the payment is complete the client is directed back to their browser … -
build a school grade tracking mobile app for parents in flutter and django
I hope you are doing well. I need to build a school grade tracking mobile app for parents in flutter and django. I don't know much about flutter. Has anyone worked on this project before? Could you help me? Could I have a source code to get inspiration from it ? -
What is the difference between a path and a url?
profile.image.url profile.image.path These are the two ways in usage...What's it working? -
No Output from views.py file after getting POST from template file (Django)
I have been trying to get details filled in a form,back in a python file using django. Everything seems fine but the form details are not getting displayed in the terminal. views.py file: from django.shortcuts import render from basicapp import forms # Create your views here. def index(request): return render(request,'basicapp/index.html') def form_name_view(request): form = forms.FormName() if request == "POST": form = forms.FormName(request.POST) if form.is_valid(): #DO SOMETHING print("Validation SUCCESS") print("NAME: " + form.cleaned_data['name']) print("EMAIL: " + form.cleaned_data['email']) print("AVANODA KARUTHTHU: " + form.cleaned_data['text']) return render(request,'basicapp/form_page.html', {'form' : form } ) form_page.html file : ( I have removed the Bootstrap CDNs ) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Forms</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, shrink-to-fit=no"> </head> <body> <div class="container"> <div class = "jumbotron"> <h2> Fill out the form </h2> <form method="POST" action = ""> {{ form.as_p }} {% csrf_token %} <input type="submit" class = "btn btn-primary" value = "Submit"> </form> </div> </div> </body> </html> Please help. Thanks in advance . -
Django Form BidForm(request.POST or None) sometime load form data otherwsie null
I have following BidForm Class... class BidForm(ModelForm): # listing = forms.CharField(widget=forms.HiddenInput()) class Meta: model = Bids fields = ('listing', 'bid_price') # def clean_bid_price(self): # data = self.cleaned_data["bid_price"] # listing = self.instance.listing # if listing.last_high_bid: # if data <= listing.last_high_bid.bid_price: # raise forms.ValidationError('bid price less than last bid price') # else: # if data < listing.starting_bid_price: # raise forms.ValidationError('bid price less than starting price') # return data The moment I uncomment either listing field or clean_bid_price validation method, the form can not load the form data and I get form instance with instance object set to None type. However if I leave it as it is as well then I debugged full init method and could not see form loaded with post data till the last line of init is done. However somehow magically the instance object of form has post data. Already spent quite a lot of time trying to debug simple function but not sure why it's failing. -
could not import CSV file to database in pgadmin
I got a CSV file and I want to import it to the created table in pgadmin a part of my CSV file is: Bernard,http://dummyimage.com/151x100.png/dddddd/000000,"",664-411-7541,bdhenin0@pagesperso- orange.fr,true,2020-09-06 Rafaellle,http://dummyimage.com/142x100.png/ff4444/ffffff,"",354-258- 6044,rephson1@ed.gov,true,2021-05-11 Erminia,http://dummyimage.com/241x100.png/5fa2dd/ffffff,"",802-987- 7344,eklimpke2@sourceforge.net,true,2021-05-10 and my model is: class Realtor(models.Model): name=models.CharField(max_length=200) photo=models.ImageField(upload_to='photos/%y/%m/%d/') description=models.TextField(blank=True) phone=models.CharField(max_length=50) email=models.CharField(max_length=50) is_mvp=models.BooleanField(default=False) hire_date=models.DateTimeField(default=datetime.now(),blank=True) and here is the screen of pgadmin: enter image description here -
Django how to show all child objects under their parent in html?
I want to show my all child objects under it's parent in my html template. How to do it in Django? #html {%for i in contact %} {% if not i.parent %}#shwing only parent objects ticket #parent_id{{i.message}} #here I want to list all child object of my parent {%endif%} {%endfor%} here is my models.py: class Contact(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='contact_user') name = models.CharField(max_length=250) email = models.EmailField(max_length=500) message = models.CharField(max_length=2000,blank=True,null=True) parent =models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') sno = models.AutoField(primary_key=True,) -
Maximum size of payload sent as POST request (Django)
Say I have a Django project (not Django REST) and I have an API endpoint. I have my payload structured as data = `{"cred":"averystrongpassword","books":"['book1','book2'...]", "prices":"['100','150',...]"}` request.post("http://myapp.com/api/, data = data) right now books and prices are a length of max, say, 30 each - but this might grow to thousands. Is there a limit of byte-size a payload can contain (both from the sender i.e the requests module) and the API (Django) or does it all boil down to performance? -
how to show file in a template - django
I want to show an uploaded file : <iframe src="{{example.file.url}}" width="100%" height="500px"></iframe> but it doesn't work it works for imagefield {{example.image.url}}, this is the attribute in my model file = models.FileField(null=True, blank=True,upload_to="sources") thanks for your help and suggestions -
Play audio in Django
I want to play an audio file on my pc with the help of django. please guide me. url.py from . import view urlpatterns = [ path('speaking/', view.speaking), ] view.py def speaking(request): return render(request, "audio_list.html") html <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <audio controls> <source src="F:\djangoProject2\templates/1.mp3" > </audio> </body> </html> Unfortunately, nothing worked this way. -
Buy one get one feature in django
I am trying to making an e-commerce website. -Now I want to add BOGO(buy one get one) feature for selected products. I am trying to find a way to implement this in code. But I am not getting any idea how I will do this. Please give me some idea how I should do this in a good way. I am adding the necessary code below, it will be helpful for you to solve my issue. Thanks Product Model class Products(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(blank=True, null=True, unique=True) category = models.CharField( max_length=200, blank=True, null=True, choices=CATEGORY_CHOICES) thumbnail = models.ImageField(blank=True, null=True, upload_to="thumbnail") short_desc = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) country_made = models.CharField(max_length=200, blank=True, null=True) benifits = models.CharField(max_length=200, blank=True, null=True) price = models.PositiveIntegerField(null=True) discount_price = models.PositiveIntegerField(null=True) timestamp = models.DateTimeField(auto_now_add=True) best_selling = models.BooleanField(default=False) featured = models.BooleanField(default=False) trending = models.BooleanField(default=False) quantity_in_stock = models.PositiveIntegerField(null=True, blank=True) out_of_stock = models.BooleanField(default=False) # size s_size = models.BooleanField(default=True) m_size = models.BooleanField(default=True) buy_one_get_one = models.BooleanField(default = False) product_delivery_time = models.IntegerField(default=2) Add to cart View class AddProductToCart(views.APIView): def post(self, request, *args, **kwargs): slug = request.data.get('slug', None) quantity = request.data.get('quantity', None) size = request.data.get('size', None) if size is None: return Response({"msg": "Please specify size"}, status=status.HTTP_400_BAD_REQUEST) if slug … -
Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive. django
I am using an abstractbase user. When I run python manage.py createsuperuser, it successfully created it but always gets that error and I don't know where is the problem. And also I put in the required fields the username and the birth date as I want normal users to register with them besides the email. however, I don't want the admin to enter these fields when I use createsuperuser command, Is there a way to do it? class UserManager(BaseUserManager): def create_user(self,email,password, birth_date,username): if not email: raise ValueError("Email must be set") email = self.normalize_email(email) user = self.model(email=email,birth_date=birth_date, username=username) user.set_password(password) user.save() #user.save(using=self._db) return user def create_superuser(self,email,password,birth_date,username,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff set to True') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser set to True') return self.create_user(email,password,birth_date,username) class User(AbstractUser): username = models.CharField(max_length=20, null=True, blank=True) email = models.EmailField(verbose_name='email address',max_length=255,unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) birth_date = models.CharField(max_length=10) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['birth_date','username',] objects = UserManager() def __str__(self): return self.username -
Is there anyone who can help me abaut virtualenv?
I want install virtualenv. I type pip install virtualenv and the response is Requirement already satisfied: virtualenv in c:\users\novin\appdata\roaming\python\python38\site-packages (20.6.0) Requirement already satisfied: platformdirs<3,>=2 in c:\users\novin\appdata\roaming\python\python38\site-packages (from virtualenv) (2.2.0) Requirement already satisfied: distlib<1,>=0.3.1 in c:\users\novin\appdata\roaming\python\python38\site-packages (from virtualenv) (0.3.2) Requirement already satisfied: filelock<4,>=3.0.0 in c:\programdata\anaconda3\lib\site-packages (from virtualenv) (3.0.12) Requirement already satisfied: backports.entry-points-selectable>=1.0.4 in c:\users\novin\appdata\roaming\python\python38\site-packages (from virtualenv) (1.1.0) Requirement already satisfied: six<2,>=1.9.0 in c:\programdata\anaconda3\lib\site-packages (from virtualenv) (1.15.0) And when I want active it, type it "source bin/activate", and the response is "source : The term 'source' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + source bin/activate + ~~~~~~ + CategoryInfo : ObjectNotFound: (source:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException" -
How to show foreign key field value instead of id in Django admin?
class Country(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=100) class Info(models.Model) country_name = models.ForeignKey(Country, on_delete=models.CASCADE) country_code = models.ForeignKey(Country, on_delete=models.CASCADE) info = models.CharField(max_length=100) In admin interface, while adding object in 'Info' model, 'country_name' field show IDs of countries by default. But I want to show names of countries instead of IDs. And similarly, 'country_code' field of 'Info' model also show IDs of countries by default. But I want to show codes of countries instead of IDs. How to do this? -
how to fetch product size in cart session in django
i am using dictionary to fetch product item and show it into the cart the product has three values its id quantity & and its size but i don't understand hw to fetch size in cart here is my views.py class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.all() print(item) return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('size') cart = request.session.get('cart') if cart: cart[item] = 1 else: cart = {} cart[item] = +1 request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my html code in which the form is <form method="POST" action="#{{ item.id }}"> {% csrf_token %} <input type="text" hidden value="{{item.id}}" name="item"> <label class="size" for="size">Size:</label> <p class="input"><input type="radio" name="size" value="S"> <span>S</span> <input type="radio" name="size" value="M"> <span>M</span> <input type="radio" name="size" value="L"> <span>L</span> <input type="radio" name="size" value="XL"> <span>XL</span> <input type="radio" name="size" value="2XL"> <span>2XL</span></p> <button type="submit" class="cart btn btn-outline-primary">Add to cart</button> </form> any idea how i can fetch that in the session thank you for your time -
Hamburger getting outside of mobile width due to ckeditor form . What to do?
I am new to django. I am trying to build blog website. On laptop create new post is perfectly visible like below. On laptop create new post But when i view it with mobile view hamburger got extended outside the mobile width no hamburger visible at first view hamburger visible after dragging page towards right i figured out this is due to ckeditor form which i have used for writing 'Text' in form. I don't know what should i do as i tried to set margin but it is only affecting other form fields not the 'Text' one. Note:hamburger visible on other pages of website -
URL Serialization Performance Issue in Sorl-Thumbnail
I'm having a bit of a difficult time with performance using sorl-thumbnail. I'm hosting images on S3 with the S3Boto3Storage storage backend, I'm using Redis as my Key-Value Store and all queries have been cached inside it already. I'm using the following dependencies: boto3==1.17.103 botocore==1.20.105 Django==3.2.4 django-redis==4.10.0 django-storages==1.11.1 redis==3.3.11 sorl-thumbnail==12.7.0 Now I run & time the following script: from sorl.thumbnail import get_thumbnail images = Image.objects.all() # 7 images for image in images: x = image.file y = x.url # 1 x = get_thumbnail(x, '800x600', crop='center') # 2 x = x.url # 3 Step 1: When I comment out #2 & #3, the script takes 0.193s Step 2: When I comment out #1 & #3, the script takes 0.0153s Step 3: When I comment out #1, the script takes 0.669s (!) The odd thing is that when I debug the 3rd step, x seems to already have the attribute "url", so I don't know why it is taking so long to access it. The connection to Redis is working and the query towards it is already activated in the 2nd step. Like I said earlier, the thumbnails have already been generated, the lookups are cached in Redis, so it is (I … -
Connecting React to Django File content error
I have a react front-end that sends the contents of a file to my python django script the connection is working well, but i cant seem to return the contents back to react. The issue seems to be the below code any idea on how i can fix this to send back the content to react please Python Script: @api_view(["POST"]) def testfunc(data): return JsonResponse(data,safe=False) -
models don't register in django admin
I have 2 models which is Listing and Realtor class Listing(models.Model): #somethings class Realtor(models.Model): #somethings and in admin.py in listing package: from django.contrib import admin from .models import Listing admin.site.register(Listing) and admin.py in realtors package: from django.contrib import admin from .models import Listing admin.site.register(Realtor) and the setting of project is: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', ] but in admin panel there aren't registeredand there is no error while runing server -
how to store some extra information with one to ne relation with the user
I am trying to store some extra information about the user that has just logged in. Actually I have a different form that the looged in user need to fill up once the page is loaded. I want the extra information to be stored against the User that has logged in. I have assigned a one to one relationship but I am getting this error. Cannot assign "'username'": "PersonalDetail.user" must be a "User" instance models class PersonalDetail(models.Model): user= models.OneToOneField(User, null=True, on_delete=models.CASCADE) age= models.IntegerField( null=True) phone= models.CharField(max_length=10,null=True ) pan= models.CharField(max_length=10, null=True) enrollment_no= models.CharField(max_length=30, null=True) state= models.CharField(max_length=40 , null=True) views if request.method =='POST': user= request.POST.get("user") age= request.POST.get("age") phone= request.POST.get("phone") pan= request.POST.get("pan") enrollment_no= request.POST.get("enrollment_no") state = request.POST.get("state") details=PersonalDetail(user=user ,age=age, phone= phone, pan= pan, enrollment_no=enrollment_no, state=state ) details.save() return render(request, 'consult.html') I am beginner please correct my code since I am not able to store these information against the logged in userID or username. This form is recived the logged in user in side the page that he emters so this has to be stored in a different table. -
Execute external script on HTML button using Django
So I'm implementing a Django web page that contains different HTML buttons and each HTML button executes a different Python script. The button that executes external script would display this error : TypeError at /external/ expected str, bytes or os.PathLike object, not NoneType Here is the html code <form action="/external/" method="POST"> {% csrf_token %} {{data_external}}<br><br> {{data1}} <br><br> <input type="submit" value="Execute External Python Script"> </form> and here is views.py : def external(request): inp= request.POST.get('param') out= run([sys.executable,'/scripts/test.py',inp],shell=False,stdout=PIPE) print(out) return render(request,'web_app/home.html',{'data1':out.stdout}) How should I fix this ? -
Limit the user to give the test only once
I want to limit the student to attempt specific test once. There can be multiple quizzes but each student should be giving test once only. The student field is one to one field with user @login_required(login_url='studentlogin') @user_passes_test(is_student) def calculate_marks_view(request): if request.COOKIES.get('course_id') is not None: course_id = request.COOKIES.get('course_id') course=QMODEL.Course.objects.get(id=course_id) total_marks=0 questions=QMODEL.Question.objects.all().filter(course=course) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks student = models.Student.objects.get(user_id=request.user.id) result = QMODEL.Result() result.marks=total_marks result.exam=course result.student=student result.save() return HttpResponseRedirect('view-result') The template for exam that I used is given as follows: <div class="container"> <div class="panel panel-primary"> <div class="panel-heading"> <h6 class="panel-title">Courses</h6> </div> <table class="table table-hover" id="dev-table"> <thead> <tr> <th>Exam Name</th> <th>Take Exam</th> </tr> </thead> {% for t in courses %} <tr> <td> {{t.course_name}}</td> <td><a class="btn btn-danger btn-xs" href="{% url 'take-exam' t.id %}"><span class="glyphicon glyphicon-circle-arrow-right"></span></a></td> </tr> {% endfor %} </table> </div> </div> I want to show the button only to new user <td><a class="btn btn-danger btn-xs" href="{% url 'take-exam' t.id %}"><span class="glyphicon glyphicon-circle-arrow-right"></span></a></td> -
unable to view address information and name on checkout page.. please do help me out in solving my error
<div class="col-sm-4 offset-sm-1"> <h4>Select Shipping Address</h4> <hr> <form action=""> {% for ad in add %} <div class="card"> <div class="card-body"> <h5>{{ad.name}}</h5> <p>{{ad.locality}}, {{ad.city}}, {{ad.state}}, {{ad.zipcode}}</p> </div> </div> <div class="form-check mt-2 mb-5"> <input class="form-check-input" type="radio" value=""> <label class="form-check-label fw-bold" for=""> Address: {{forloop.counter}} </label> </div> {% endfor %} <div class="text-end"> <button type="submit" class="btn btn-warning mt-3 px-5 fw-bold">Continue</button> </div> </form> </div> views.py ''' def checkout(request): user = request.user add = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) amount = 0.0 shipping_amount = 50.0 totalamount = 0.0 cart_product = [p for p in Cart.objects.all() if p.user==request.user] if cart_product: for p in cart_product: tempamount = (p.quantity*p.product.discounted_price) amount += tempamount totalamount = amount +shipping_amount return render(request, 'app/checkout.html', {'add':add , 'totalamount': totalamount,'cart_items': cart_items}) ''' views.py address ''' def address(request): add= Customer.objects.filter(user=request.user) return render(request, 'app/address.html', {'add':add,'active':'btn- primary'}) ''' -
SSE DJANGO REQUEST COUNT
i still new using SSE and i have a question about SSE in Django version 3.2.5, i am using StreamingHttpResponse to send SSE response to EventSource client and it does work fine, my question that why it takes to long to open the connection between backend and EventSource? why it sends only 145 responses/15 seconds ? i tried to open the code of StreamingHttpResponse but i didn't find anything related to the number of response here in the code def sse_movies(request): def event_stream(): while True: sleep(.2) yield f"data: {datetime.time(datetime.now())}\n\n" return StreamingHttpResponse(event_stream(), content_type='text/event-stream') i am using sleep to wait only 2/milliseconds for each iteration. but whenever send the EventSource it waits almost 15/secods to initiate the connection with the back-end, and after it sends 145 requests then waits 2 seconds then sends another 145 requests once more and after the second 145 is sent it waits another 15 seconds here is the code of EventSource client let url = '/test/' +'sse/movies/' let sse_client = new EventSource(url) let movies = document.querySelector('#data-movies') let movies_list = document.querySelector('#messages') sse_client.onopen = function(message_event) { console.log('opened') } console.log(sse_client) sse_client.onmessage = (message_event) => { console.log(message_event.data) console.log(sse_client.readyState) } NOTE: when i remove white: True EventSource doesn't wait and sends requests … -
django moderation and custom model managers
I am using Django 3.2 and django-moderation I want to moderate Foo: class MyCustomManager1(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=True) class MyCustomManager2(MyCustomManager1): def get_queryset(self): return super().get_queryset().filter(/* some criteria */) class Foo(models.Model): # some fields objects = models.Manager() published = MyCustomManager1() live = MyCustomManager() moderation.register(Foo) When I run python manage.py makemigrations, I get the error: Foo has no attribute unmoderated_published I tried to hack around this by adding the fields and creating Managers for moderated objects - but although that got rid of the errors, the object was no longer moderated. The only way I could get created objects to be moderated, was to remove all the model managers - with the exception of the default objects manager. How do I get django-moderation to work with models with custom model managers?