Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why there is a small circle on my django folder
https://images.app.goo.gl/vvJSsYovFXFdtCfK7 Like these on dedo and on migration -
Django.session: how to determine the start of a Django user session?
My site have second level pages. User can get there from first level page with form. Data of the form stored in request.session. It work ok if the user get second level page normally - from first level page . Problems appear if user get the second level page directly - from Google search or his own benchmarks. In that case i need clear the request.session to deafult, but only in that case. Django put request.session data in cookies, and stores form data to user if he coming second time to the site. I don`t need it in the case the user come from external side. Can i determine that the page get by user first time in the session? Or he comes directly on this second level pages, not from first level page? -
How to avoid/eliminate Integrity error on form fields
I have a form that displays details but when I bring in a filter it fails. Where is the mistake?? The error is here File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: libman_issue.book_id_id This is the form class IssueForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(IssueForm, self).__init__(*args, **kwargs) self.fields['book_id'] = forms.ModelChoiceField( queryset=Books.objects.filter(no_of_books=1),label='Available books') class Meta: model = Issue fields = ['borrower_id',] When I have the form as shown below it works. class IssueForm(forms.ModelForm): class Meta: model = Issue fields = ['borrower_id','book_id'] -
'Default' value error after makemigrations command
I am working on a django blog project. Having some issue in models.py file after running 'py manage.py makemigrations' I used this code: publish_date = models.DateTimeField( auto_now_add=True) update_date = models.DateTimeField(auto_now=True) Error I am getting: You are trying to add the field 'publish_date' with 'auto_now_add=True' to blog without a default; the database needs something to populate existing rows. When I used This code: publish_date = models.DateTimeField( auto_now_add=True, default=True) update_date = models.DateTimeField(auto_now=True, default=True) Error Now: App_Blog.Blog.publish_date: (fields.E160) The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present. App_Blog.Blog.update_date: (fields.E160) The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present. WHAT IS THE SOLUTION? -
AssertionError: 403 != 200 in APITestCase
i have this url: path('post/',views.PostListCreateAPIView.as_view(),name='post_lc'), with an app-name : app_name='blog_api' and trying to test it like : class TestPost(APITestCase): def test_view_posts(self): response = self.client.get('blog_api:post_lc') self.assertEqual(response.status_code, status.HTTP_200_OK) and even with url directly : class TestPost(APITestCase): def test_view_posts(self): response = self.client.get('/api/post/') self.assertEqual(response.status_code, status.HTTP_200_OK) the url and the views, are functioning works well, but the test keep giving the error AssertionError: 403 != 200 and i just can't figure out why, thanks for the help Update i forgot that i had IsAuthenticated, which caused the 403 error REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ]} -
using html input type=datetime-local won't insert in Django model having datetime field
I am not using Django forms but instead using the normal ones with html and bootstrap. I have an input field of type datetime-local which the user can select for a particular event to happen. However, I am unable to insert in in my Django model due to timezone error. I get this error message: DateTimeField %s received a naive datetime (%s ) How do I fix this pleaaaase? html code: <label>Scheduled Date and Time<label> <input type="datetime-local" id="test_datetime" name="test_datetime" id="test_datetime"> views.py def add_test(request, pid): if request.method == 'POST': test_datetime = request.POST['test_datetime'] and it continues.... -
My Session is getting auto cleared after i receive a get request from paypal in django
I am using paypalrestsdk for accepting payments def process_subscription(request, subscription_type): print(request.session.load()) # output : {'name': 'Abhay', 'password': 'k2jk2332k'} # code to process payment if payment.success() return redirect(redirect_url) return redirect(reverse('error_page')) @csrf_exempt def success(request): print(request.session.load()) # here output is {} blank return render(request, 'success.html') It don't works even if i have removed @csrf_exempt, i have searched on google but did'nt found solution to it... Django Version : 3.2 PaypalRestSdk version : 1.13.1 -
NotWritableError: The current user does not have write permissions to a required path
NotWritableError The current user does not have write permissions to a required path. -
Should I render images from other sites instead of using sevices like AWS storage in my web app?
I am developing a blogging site which has a lot of images. Instead of storing all of the images in the database or AWS etc. should I render the image from another site using the share link? I was thinking of storing the images in Google drive and rendering them using the share link. Will it work? -
unable to see classes in my django admin site
i created 2 classes in my models.py which i can access through shell but cant see it on my /admin page. i used python manage.py migrate and makemigrations my models.py: from django.db import models class Company(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Product: name = models.CharField(max_length=200) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.name my admin.py: from django.contrib import admin from.models import Company, Product admin.register(Company) admin.register(Product) -
Dropdown list always disabled in a bootstrap model?
I have a drop down list inside a model but couldn't make is work properly , It's always disabled I managed to make it work by adding the script: <script> $(document).ready(function() { $("#id_department").select2({ dropdownParent: $("#modalContact") }); }); </script> but when I add the code the drop change to a normal text like the image -
Django DRF best practices to return response headers on every request
I am using Django DRF. What is the best way to add the below response headers as part of every request Cache-control: no-store, max-age=0 Pragma: no-cache Strict-Transport-Security: max-age=7776000; includeSubDomains X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff X-Frame-Options: DENY Ideally I want to configure this in one place. -
Direct assignment to the forward side of a many-to-many set is prohibited. Use item.set() instead
I am having an issue with adding a watchlist using django. models.py: class Listings(models.Model): Name = models.CharField(max_length=64) seller = models.CharField(max_length=64) starting_bid= models.IntegerField() description=models.TextField() time=models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=64) image_link = models.CharField(max_length=200, default=None, blank=True, null=True) class Watchlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(Listings) views.py: @login_required(login_url='/login') def watchlist(request,id): item_to_save=Listings.objects.get(id=id) #query to check if the item already exists in watchlist if Watchlist.objects.filter(user=request.user,item=item_to_save).exists(): return render(request,"auctions/listing.html",{"message":"You already have it in your watchlist"}) else: watchlist_obj=Watchlist() watchlist_obj.user=request.user watchlist_obj.item=item_to_save watchlist_obj.save() return render(request, "auctions/listing.html",{"message":"successfully added to watchlist"}) please help me. I have looked at other stackoverflows regarding similar questions but wasn't able to solve my issue -
how to add google adsens to an django web app
i'm trying to add google adsense to my django webapp but when i try i've got this error "website have no content". if somedbody done this before can you explain to me please. i've seen maybe solution like sekizai or django ads to install in a project but i'm not able to install it because i don't understand everything. maybe i don't put tag at the good place in my template but there's not a lot of informations on the sekizai website and it look to be necesarry to use adsense in django app. thanks for help. -
django how to set value into hidden input
I have script which allows user to select only one div button , if car is selected will be writhed by submit form button, but when its not hided and I write car example in the input it works as I want, also I can active button style, but when its hided cant see it takes or not, so please here is my little script how can I get this div button name into hidden input--- sorry for my ruined english {% block javascript %} <script> function changeClass(id) { if ($('#' + id).hasClass('answerBtnsSelected is-danger')) $('#' + id).removeClass('answerBtnsSelected is-danger'); else { if ($('.answerBtnsSelected').length < 1) { $('#' + id).addClass('answerBtnsSelected is-danger'); } else { alert('Only three buttons can be selected.'); } } $(".subtn").click(function () { $("#subtn").text($(id).text()); $("#subtn").val($(id).text()); $("#id_mtags").val($(id).text()); $("#MainTags").submit(); console.log($('#id_mtags').val()) }); } </script> {% endblock %} <form method="post" action="" enctype="multipart/form-data" role="form" id="MainTags"> {% csrf_token %} <div class="columns is-mobile"> <div class="column"> <div class="button" type="button" id="car" value="car" name="car" onclick="changeClass(this.id);"> car </div> </div> <div class="column"> <div class="button" type="button" id="home" value="home" name="home" onclick="changeClass(this.id);"> home </div> </div> <div class="column"> <div class="button" type="button" id="phone" value="phone" name="phone" onclick="changeClass(this.id);"> phone </div> </div> <div class="column"> <div class="button" type="button" id="apple" value="apple" name="apple" onclick="changeClass(this.id);"> apple </div> </div> </div> <h3 class="title is-1"></h3> {{ form.hiddeninput}} … -
show user different text from database on every login in django
can we do this if user login in a page and gets some text from database and after that user login again and again then user get different text from same database. thanks in advance and yet I am trying right like i get data from database and append it into list and show on html div then next and back button but thats not I want. and this code is wrong which i am showing below <div class="slider"> {% for a,b in text_list2.items %} <div class="div{{a}}" id="p" values="{{a}}"> <p>{{b}}</p> </div> {% endfor %} <button class="btn" onclick="prev()">Prev</button> <button class="btn" onclick="next()">Next</button> </div> <script type="text/javascript"> var slider_img = document.querySelector('.slider-img'); var values = document.getElementById('p').value; var images = []; for (var i = 1; i < 5; i++) { images.push(i); } var i = 0; console.log(values) function prev(){ if(i <= 0) i = images.length; i--; return setImg(); } function next(){ if(i >= images.length-1) i = -1; i++; return setImg(); } function setImg(){ return slider_img.setAttribute('src', images[i]); } </script> -
Django bulk create auto fields
I have two models and want migrate all data from one to another. For simulating problem, suppose the models below: from django.db import models class Book: name = models.CharField(max_length=100) is_archived = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) class BookArchived: name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) The code for migrations is: book_objs = [] for archived_book in BookArchived.objects.all(): book_objs.append(Book(name=archived_book.name, is_archived=True, created_at=archived_book.created_at)) Book.objects.bulk_create(book_objs) The problem with this code is that, although I explicitly set created_at field (created_at=archived_book.created_at), django inserts all of them with current time. I know that if pk field is explicitly set (id=archived_book.id), new objects will preserve original timestamps. But there is already overlapping ids in database, so this approach will create another problem. How can I preserve original created_at values for BookArchived instances? -
Displaying data from models to index.html in django
i want to display the data of models to html template, i've tried every thing but still i'm unable to get what i am look for. App name is Home Here is the code. Home/models.py from django.db import models class message(models.Model): your_message = models.CharField(max_length=50) def __str__(self): return self.your_message Home/views.py from django.shortcuts import render, HttpResponse from .models import message def index(request): return render(request, 'Home/index.html') In my template index.html i am using this code to display the data from models. {% for x in message %} <h2> {{ x.your_message }} </h2> {% endfor %} -
Celery object has no attribute on_after_configure when trying to start the Celery workers
I want to start the Celery server but whenever I try to do so with celery -A app.tasks worker --loglevel=INFO I get AttributeError: 'Celery' object has no attribute 'on_after_configure'. The code below is defined in the root of the Django project, in a file called tasks.py. app = Celery("tasks", broker="redis://localhost") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(hour=23, minute=55), monthly_analytics.s(), ) sender.add_periodic_task( crontab(hour=23, minute=57), calc_average_rating.s(), ) sender.add_periodic_task( crontab(hour=5, day_of_month=1), per_view_payouts.s() ) -
Stripe Checkout - Capturing email and save it in django
My use case requires me to save the users email to a django session. However I don't want them inputting their email twice - in stripe checkout and in my django form. Ideally I want to grab the email they input when making their payment and save that to my django session. Here is my stripe payment.html: <a href="#" id="buy_now_btn" class="btn btn-primary">Buy Now</a> <script src="https://js.stripe.com/v3/"></script> <script> const buy_now_button = document.querySelector('#buy_now_btn') buy_now_button.addEventListener('click', event => { fetch('/checkout/') .then((result) => { return result.json() }) .then((data) => { var stripe = Stripe(data.stripe_public_key); stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as parameter here // instead of the {{CHECKOUT_SESSION_ID}} placeholder. sessionId: data.session_id }).then(function (result) { // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `result.error.message`. }); }) }) </script> here is my view: def payment(request): return render(request, 'main/payment.html') From what I've seen in my attempts to solve this, it seems stripe obfuscates the info put in at checkout, so I am not sure it is even possible. -
Input type datetime-local won't save to database having field type datetime in Django
I have a form which has an input type of datetime-local. However, Im unable to process it in my views for saving to the database. Im not using Django forms. How can I do it please? Error message: "DateTimeField %s received a naive datetime (%s )" Here is my code snippet: html file <label>Scheduled Date and Time<label> <input type="datetime-local" id="test_datetime" name="test_datetime" id="test_datetime"> views.py def add_test(request, pid): if not request.user.is_authenticated: messages.warning(request, "Please login first") return redirect('login') if request.method == 'POST': test_datetime = datetime.strptime(request.POST['test_datetime'],'%Y-%m- %dT%H:%M') and it continues.... -
How can I change my project path on Django?
I have a Django project on an ubuntu server v20.04 with apache2. Whenever I run on local, I have to change the TEMPLATES Dir as follow: 'DIRS': ['templates'], Before deploying to the server I am rechanging again: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/crawl/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] There was no problem when I was using CentOs. After I move to ubuntu I have a path problem. I also add my WSGI and config file. WSGI: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = get_wsgi_application() Here is my config file for apache2: <VirtualHost xx.xxx.xxx.xxx:80> ServerName xxx.xxx.com DocumentRoot /home/crawl redirect permanent / https://xxx.xxx.com RewriteEngine on RewriteCond %{SERVER_NAME} =xxx.xxx.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> <VirtualHost xxx.xxx.xxx.xxx:443> ServerName xxx.xxx.com DocumentRoot /home/crawl <Directory /home/crawl/project/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess project processes=2 threads=12 python-path=/home/crawl:/home/crawl/venv/lib/python3.8/site-packages WSGIProcessGroup project WSGIScriptAlias / /home/crawl/project/wsgi.py #WSGIPythonPath /home/crawl/ <Directory /home/crawl/project > Require all granted </Directory> Alias /media/ /home/crawl/media/ Alias /static/ /home/crawl/staticfiles/ <Directory /home/crawl/staticfiles> Require all granted </Directory> <Directory /home/crawl/media > Require all granted </Directory> SSLEngine on SSLCertificateFile /etc/letsencrypt/live/xxx.xxx.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/xxx.xxx.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf ErrorLog syslog LogLevel emerg </VirtualHost> Do you have any suggestions to fix the path … -
Send Email with Django to contact
I am trying to send a templated email to a contact saved in a database. How can pre enter the email detail of the contact and remove the forms. I have tried to replace recipient = str(sub['Email'].value()) by recipient = str(sub['lead.id'].value()) but it didn`t work. views.py @login_required(login_url="/login/") def subscribe(request, lead_id): lead = Lead.objects.get(pk=lead_id) sub = forms.Subscribe() if request.method == 'POST': sub = forms.Subscribe(request.POST) subject = 'Introduction' message = 'Good morning,' recipient = str(sub['Email'].value()) send_mail(subject, message, EMAIL_HOST_USER, [recipient], fail_silently = False) return render(request, 'subscribe/success.html', {'recipient': recipient, 'lead': lead}) return render(request, 'subscribe/index.html', {'form':sub, 'lead': lead}) forms.py class Subscribe(forms.Form): Email = forms.EmailField() def __str__(self): return self.Email urls.py url(r'^(?P<lead_id>[0-9]+)/subscribe$', views.subscribe, name='subscribe'), Many Thanks -
Not redirecting from createView form to Home
I am learning fresh django development. Working on a blog project I am facing a issue that, while publishing a new blog, that doesn't redirects to home/blogs page. I tried to manually to go home It says, OperationalError at /blog/ no such column: App_Blog_blog.author_id I tried to debug several times, searched in documentation can't get away with this author_id. These are my codes: Views.py class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'App_Blog/create_blog.html' fields = ('blog_title', 'blog_content', 'blog_image',) def form_valid(self, form): blog_obj = form.save(commit=False) blog_obj.author = self.request.user title = blog_obj.blog_title blog_obj.slug = title.replace(" ", "-") + "-" + str(uuid.uuid4()) blog_obj.save() return HttpResponseRedirect(reverse('index')) class BlogList(ListView): context_object_name = 'blogs' model = Blog template_name = 'App_Blog/blog_list.html' Views.py of main project file def index(request): return HttpResponseRedirect(reverse('App_Blog:blog_list')) urls.py from django.urls import path from App_Blog import views app_name = 'App_Blog' urlpatterns = [ path('', views.BlogList.as_view(), name='blog_list'), path('write/', views.CreateBlog.as_view(), name='create_blog'), ] models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name="Put a Title") slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What is on your mind?") blog_image = models.ImageField( upload_to='blog_images', verbose_name="Image") publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title create_blog.html {% … -
django/css - where does the individual form fields like {{form.name}} etc. go in css form
I am trying to create a form using django and css. My Views.py looks like this - //MY VIEWS.PY LOOKS LIKE THIS from django.shortcuts import render from .forms import ContactForm # Create your views here. def home(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): pass else: form = ContactForm() return render(request, 'home.html', {'form':form}) My forms.py looks like this- //MY FORMS.PY LOOKS LIKE THIS from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length = 30) email = forms.EmailField(max_length = 254) message = forms.CharField(max_length = 2000, widget = forms.Textarea(),help_text = "Write Your Message here") def clean(self): cleaned_data = super(ContactForm, self).clean() name = cleaned_data.get('name') email = cleaned_data.get('email') message = cleaned_data.get('message') if not name and not email and not message: raise forms.ValidationError('You have to write something!') When I try to add the form to my html page like the following it doesn't show up. Just the button shows up, no form fields - {% extends 'store/main.html' %} {% load static %} {% block content %} <h3>Store</h3> <form method = "post" novalidate> {% csrf_token %} {{ form }} <button type='submit'>Submit</button> </form> {% endblock content %} If I do css form instead it obviously show up the way it should. {% extends 'store/main.html' %} …