Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is TechSmith Discount Code work properly?
Yeah, Sure It is real and reliable TechSmith Discount Code with one of the best features and services. In the market that software is at the pick. -
Django template update without refreshing
I am trying to print sensor reading coming from esp8266 to Django's database in a template. I need the data to be shown in the template without refreshing the page to get new values. This the views, urls and the template codes class SensorReading(ListView): model = Sensor template_name = "sensor.html" urlpatterns = [ path("", index, name="index"), path("/reading", SensorReading.as_view(), name="reading"), ] <body> <ul> {%for reading in object_list reversed%} <li><p>{{reading.SensorType}}</p></li> <li><p>{{reading.Reading}}</p></li> <li><p>{{reading.Time}}</p></li> {%endfor%} </ul> -
why Django asks for csrf_token in GET request?
I tried to send a GET request from the HTML form. But I am getting the error "CSRF verification failed.". And When I add csrf token( {% csrf_token %} ), It redirects me to the same page, But it should redirect to confirm.html. here is html code, doctor.html <form method="GET" action="{% url 'confirm' value.name %}"> {% csrf_token %} {% comment %} <h4>Appoint No: {{ value.id }}</h4> {% endcomment %} <div class="appoint_name"> <span class="appoint_spn">Name: </span> <span class="appoint_spn">{{ value.name }}</span> </div> <div class="appoint_name"> <span class="appoint_spn">Email </span> <span class="appoint_spn">{{ value.email }}</span> </div> <div class="appoint_name"> <span class="appoint_spn">Specialites</span> <span class="appoint_spn">{{ value.specialites }}</span> </div> <div class="appoint_name"> <span class="appoint_spn">Duty TIme: </span> <span class="appoint_spn">{{ value.duty_date_start }} - {{ value.duty_date_end }}</span> </div> <div class="appoint_button"> <input class="btn" type="submit" value="Make An Appointment"> </div> </div> </form> My path confiquration in url.py path('confirm/<str:name>/',views.confirmappointment, name='confirm') And here is views.py def confirmappointment(request, name): doctor_name = name userid = request.session['userid'] username = request.session['username'] value = Appointment.objects.create(patient_name=username, patient_id=userid, doctor_name= doctor_name) value.save() return render(request, 'doctor/confirm.html') -
Custom User Register Problem (NOT NULL constraint failed: mainaccount_myuser.password)
I changed the user model for a custom user model. Drop all migrations and deleted db.sqlite3 files. The model was working fine. I can register users through the admin page, but when i go to from creating the user, to change my user and finishing the registration process, this error pops up: (NOT NULL constraint failed: mainaccount_myuser.password) how can i finx this error? admin.py: from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model MyUser = get_user_model() class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = MyUser fields = ('email', 'date_of_birth', 'full_name') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = MyUser fields = ('email', 'password', 'full_name', 'date_of_birth', 'is_active', 'is_admin') class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email', 'full_name', 'date_of_birth', … -
NOT NULL constraint failed: backend_post.created_by_id: logged in user not being registered
I'm getting this error when I try to make a Post. I understand that the issue seems to be that there's no user being registered in the created_by field but I did log in before trying to make a post. So how can I solve this? I don't want to create a post without a registered user writing it so how do I do this if my code is not working? These are the models: from django.db import models, transaction from django.conf import settings from django.contrib.auth.models import BaseUserManager, AbstractUser from django.utils.encoding import force_bytes class UserManager(BaseUserManager): @transaction.atomic def create_user(self, email, username, password=False): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() return user def get_by_natural_key(self, username): return self.get(username=username) def create_superuser(self, username, password, email): user = self.create_user( username=username, email=email, password=password, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name= 'username', max_length= 50, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return str(self.username) class Category(models.Model): """ Category """ name = models.CharField('Name', max_length=200) … -
How to show my pagination bootstrap inside a div in HTML, That acts in JavaScript function?
I want to add pagination bootstrap to my show-posts Div, but because on my JavaScript function I Have document.querySelector('#show-posts').innerHTML = "" - it doesn't show my bootstrap How can I show my bootstrap pagination and also reset the innerHTML of shows-posts every time? index.js function load_posts(){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#load-profile').style.display = 'none'; document.querySelector('#posts-view').style.display = 'block'; document.querySelector('#show-posts').style.display = 'block'; document.querySelector('#post-form').onsubmit = function() { compose_post(); } fetch('/posts/all_posts') // url with that API .then(response => response.json()) .then(all_posts => { // Loop and show all the posts. console.log(all_posts) all_posts.forEach(function(post) { // loop to loop over each object build_post(post) }); }); document.querySelector('#show-posts').innerHTML = "" } HTML <div id ="show-posts"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"><a class="page-link" href="#">Previous</a></li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"><a class="page-link" href="#">Next</a></li> </ul> </nav> </div> views.py def show_posts(request): all_posts = NewPost.objects.all() all_posts = all_posts.order_by("-date_added").all() paginator = Paginator(all_posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return JsonResponse([website_post.serialize() for website_post in page_obj], safe=False) -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about
error is when http://127.0.0.1:8000/about Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: The current path, about, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. projets mysite urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('mainapp.urls')), ] main app urls.py from django.urls import path,include from . import views urlpatterns = [ path('',views.home), path('about',views.about), path('contact',views.contact) ] views.py from django.shortcuts import render,HttpResponse def home(request): return render(request,"index.html") def about(request): return render(request,"about.html") def contact(request): return render(request,"contact.html") templates/about.html <!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>Document1</title> </head> <body> <h1>Mahabir pun</h1> <p>he is a great person he is a doing grat</p> </body> how to solve please help me i am in trouble for 2 days -
Django Api ReadOnlyField [duplicate]
I was wondering what the source part of a ReadOnlyField actually does. Thanks poster = serializers.ReadOnlyField(source = 'poster.username') -
Requiring checking checkbox during in custom Django sign-up form
Im preparing customized Django registration form. I need adding two checkboxes that are required (RODO consent and consent for using images). How to declare in Django that this checkboxes must be checked before form could be send? Form is based on model and it looks like this: Models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'),max_length=50) last_name = models.CharField(_('last name'),max_length=150) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) RODO_consent = models.BooleanField(default=False) image_consent = models.BooleanField(default=False) marketing_consent = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email','password1','first_name','last_name','RODO_consent','image_consent','marketing_consent') -
Why this function has a TypeError?
when I want to print order detail as PDF file it give the following: The error: admin_order_pdf() got an unexpected keyword argument 'order' the function: @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('orders/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order.id}.pdf' weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS( settings.STATIC_ROOT + 'css/pdf.css' )]) return response -
Deploying into App Engine + Cloud SQL + Cloud Storage - How to keep costs low?
Context I'm deploying a website made with Django, to App Engine + Cloud SQL + Cloud Storage. Right now, with the website being used only by me and a few friends, the daily costs are between 0,5-1 dollar. When releasing this i would like to keep the costs within the same range. Also, im still doing use of the free trial. I have like 170 dollars left for 69 days. Question Question 1: If i understand [this][1] correctly, while i don't upgrade my Cloud Billing Account, i won't get any charge to my card? Then it is completely safe to do a deploy while you are using your free credits. Is that right? Worst case scenario: I use all my free credits and my website goes down. I won't get any charge to my card. Current configuration - setup App Engine This is the app.yaml file used by my instance: runtime: python38 env: standard instance_class: F1 handlers: - url: /static/(.*) static_files: static/\1 require_matching_file: false upload: static/.* - url: /.* script: auto secure: always - url: .* script: auto env_variables: DJANGO_SETTINGS_MODULE: project.settings.prd automatic_scaling: min_idle_instances: automatic max_idle_instances: automatic min_pending_latency: automatic max_pending_latency: automatic min_instances: 1 max_instances: 1 network: {} Questions Within the automatic_scaling … -
I need to create html and android app button can run python script (image processing)
I am using framework django my input is only a image and output is the processed image (after using image processing) this is my html. It is ok but I have problem with android app code html Please help me !!! -
Unable to redirect to recently created detailview
I hope you're doing well. I am getting the below error when attempting to redirect to my newly created conversation detail page. The slug works perfectly when I type the url manually so it I think it has to do with the return reverse logic on the StartConversationView view. Please let me know of anything else I could try (I've tried what's commented below). Thanks so much. NoReverseMatch at /conversations/start/ Reverse for 'conversation_detail' with no arguments not found. 1 pattern(s) tried: ['conversations/(?P[-a-zA-Z0-9_]+)/$'] models.py class Conversation(models.Model): conversation = models.CharField(max_length=60, null=True, blank=False, unique=False) detail = models.CharField(max_length=600, null=True, blank=False, unique=False) slug = models.SlugField(max_length=80, null=True, blank=True) def __str__(self): return self.conversation def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.conversation+'-'+str(datetime.now().strftime("%Y-%m-%d-%H%M"))) super(Conversation, self).save(*args, **kwargs) def get_absolute_url(self): #return reverse('conversation_detail', args=[str(self.slug)]) return reverse('conversation_detail', kwargs={'slug': self.slug}) views.py class StartConversationView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): form = StartConversationForm() return render(request, 'conversations/start.html', {'form': form}) def post(self, request, *args, **kwargs): form = StartConversationForm(request.POST) if form.is_valid(): new_conversation = form.save(commit=False) new_conversation.starter = request.user new_conversation.save() messages.success(request, ('You have successfully started a new conversation.')) return redirect(reverse('conversation_detail'), slug=self.kwargs.get('slug')) #return redirect(reverse('conversation_detail'), kwargs = {'slug': self.slug }) #return redirect('conversation_detail'), self.slug=slug) #return HttpResponseRedirect(reverse('conversation_detail', kwargs={'slug': self.slug})) #return HttpResponseRedirect(reverse(self.get_absolute_url())) #return redirect('login') return render(request, 'conversations/start.html' , {'form': form}) class ConversationDetailView(LoginRequiredMixin, DetailView): … -
invalid literal for int() with base 10: b'permit_start'
I created model in Django.After added datefield to my model. models.py: ... date = models.DateField(blank=True, null=True, verbose_name="blablabla") But I got this error in admin panel. invalid literal for int() with base 10: b'date' -
ASGI errors when deploying Django project for production
how are you doing. I have an issue I hope can find a solution from experts. I want to deploy my django project and I used ASGI server I applied all steps from the official django website: https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ but it does not work I tried a lot of ways and solutions, but it all fails. BTW, I want to deploy the project on heroku hosting, it fails on heroku too. BTW, I did try some solutions from stackoverflow answers, but not worked. this is the output I get when trying to run the server using: Daphne Gunicorn Uvicorn Traceback (most recent call last): File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/uvicorn/workers.py", line 63, in init_process super(UvicornWorker, self).init_process() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/home/ibrahim-pc/.pyenv/versions/3.8.9/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File … -
Unable to Filter from database in DJango
this is my models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) this is my view.py def customer_dashboard(request,id): order = Order.objects.filter(customer=id) print(order) return render(request, 'accounts/customer_dashboard.html', {'user':user, 'customer':customer}) I tried to print the results,and I got this <QuerySet []> But I am very sure that the data is available in database, url is also working fine as other datas could be fetched -
How to delete file in minIO storage in Django?
I used the minIO storage in my Django app.I want to delete the object from DB and storage.What can I do? thanks in advance. this is my model: class FileStorage(models.Model): team = models.ForeignKey(Team, related_name = 'storage_team', null = True, on_delete = models.CASCADE) title = models.CharField(unique=True,max_length=255) video = models.FileField(verbose_name="Object Upload", storage=MinioBackend(bucket_name=priv_bucket), upload_to=iso_date_prefix) def __str__(self): return self.title -
How to save multiple objects from a script in django shell
Hello colleagues I would like to know if this list of objects can be saved from a script like the one I show, I want to execute it from the django shell python3 manage.py shell < script.py the following is my script from orders_management.models import Products objects = [ 'Products(name = "destornillador", section = "ferrreteria", price = 35)', 'Products(name = "balon", section = "deportes", price = 25)', 'Products(name = "raqueta", section = "deportes", price = 105)', 'Products(name = "muneca", section = "juguetes", price = 15)', 'Products(name = "tren electrico", section = "jugueteria", price = 135)', ] for object in objects: my_product = object my_product.save() the error it shows me File "<string>", line 15, in <module> AttributeError: 'str' object has no attribute 'save' -
How to make a Django return button point to the correct previous page?
I have a page (a.html) that the user may reach from different other pages in my Django application. And in this page there is a return button to return to the previous page. For instance: Page b.html contains a link to a view that presents a.html Page c.html contains a link to a view that presents a.html I need to implement a way of making the return button point to the correct view (b.html or c.html), depending on how it was reached. Fact 1: I can't simply put an action window.history.back(); because I need to reload the view it came from -
How to handle form with post method in Django?
I'm looking for a way to print my POST form using Django, my post form is multi-dimentional form: { first_name: '', last_name : '', email: '' } i'm sending my request using axios.post, just I want to know how can I handle the form on my backend(Django) i did request.POST['form']['email'] i got an error also i tried request.POST.get('form') and i got an error -
Django ORM queryset
I am learning about the Django ORM and how to make queries, Lets suppose i have two models class Company(models.Model): structure = IntegerField() class Customer(models.Model): created_at = DateTimeField(default=now) company = ForeignKey(Company) friend = BooleanField() I am writing a function where it can get all companies where their most recently created customer is friend=True. def get_companies_with_recent_friend(): """" Returns ------- `list(Company, ...)` """ raise NotImplementedError -
Django -- relation " " does not exist
There is some funny stuff going with my database. I am trying to create a new model but I get this error when trying to load the page: ProgrammingError at /posts/ relation "new_sites_topichome2" does not exist LINE 1: ...te_added", "new_sites_topichome2"."owner_id" FROM "new_sites... Here is the models.py class TopicHome2(models.Model): title = models.CharField(max_length = 200) text = models.TextField() image = models.ImageField(upload_to = 'image/set/', null = True, blank = True) urllink = models.CharField(max_length=5000, null = True, blank = True) date_added = models.DateTimeField(auto_now_add = True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title[:50] forms.py class TopicHomeForm2(forms.ModelForm): class Meta: model = TopicHome2 fields =['title', 'text', 'image','urllink'] def __init__(self, *args, **kwargs): super(TopicHomeForm2, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['placeholder'] = 'Enter title here' self.fields['text'].widget.attrs['placeholder'] = 'Enter text here' views.py def new_topichome2(request): if request.method == "POST": form = TopicHomeForm2(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit = False) new_post.owner = request.user new_post.save() form.save() return redirect('new_sites:index') else: form = TopicHomeForm2() context = {'form':form} return render(request, 'new_sites/new_topichome2.html', context) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I am using heroku and AWS buckets for static files. Is it possible that my database is actually stored in the AWS RDS? I have a model called Books which has many entries/objects … -
Django selected radio button giving only a single value (on) in view.py
I have 4 radio buttons indicating 4 answers for a particular question. How do I get the selected one to store in the boolean field of my model? With the current method, I get only the value on Thank you for your kind help html file for the js script part (Questions are added dynamically) for (var i = 1; i <= num_of_qu; i++) { html += `<div class="row"><div class="form-row"><div class="form-group col-md-6"> <label>Name of question</label><input type="text" class="form-control" name="question_text_${i}" id="question_${i}" placeholder="Question"></div></div></div>`; for (j = 1; j <= 4; j++) { //4 answers html += `<div class="row"> <div class="form-row"> <div class="form-group col-md-4"> <input type="text" class="form-control" name="question_${i}_answer_${j}" id="question_${i}_answer_${j}" placeholder="Answer" ><input type="radio" name="radio_question_${i}_answer" id="radio_question_${i}_answer_${j}" > </div> </div> </div>` views.py def add_test(request, pid): if request.method == 'POST': //i retrieved the variables here try: with transaction.atomic(): test = PsychometricTest.objects.create(internship=internship, name=test_name, description=test_description, number_of_questions=test_num_questions, time=test_duration, threshold=test_threshold, difficulty=test_diff_level, created=date.today(), scheduled_date_time=test_datetime) for i in range(1, int(q_num)+1): //ISSUE IS BELOW radio_check = request.POST.get('radio_question_{}_answer'.format(i)) print(radio_check) question = Question.objects.create(text=request.POST['question_text_{}'.format( i)], psychometric_test=test, created=date.today()) radio_check = request.POST.get( 'radio_question_{}_answer'.format(i)) for j in range(1,5): answer = Answer.objects.create(text=request.POST['question_{}_answer_{}'.format( i, j)], question=question, created=date.today()) for choice in radio_check: if (choice.checked): answer.correct = True answer.save() messages.success(request, "Psychometric test added") return redirect('view_internship') except Exception as e: print(e) messages.error(request, "An error happened!") return … -
How to give labels and title to plotly visuals in django website?
How to give labels and title to plotly visuals in django website? Purpose: Want to show interactive line plot in Django website with labels. views.py from django.shortcuts import render from plotly.offline import plot from plotly.graph_objs import Scatter def index(request): x_data = [0,1,2,3] y_data = [x**2 for x in x_data] plot_div = plot([Scatter(x=x_data, y=y_data, mode='lines', name='test', opacity=0.8, marker_color='green')], output_type='div') return render(request, "index.html", context={'plot_div': plot_div}) index.html <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test</title> </head> <body> {% autoescape off %} {{ plot_div }} {% endautoescape %} </body> </html> -
How to get data from Database with a range?
So i want to make a range from a specific date to current date. I make like this: context_data['newNotifications'] = Notification.objects.filter( emailStudent=request.user).filter(time=request.user.viewedNotifications).count() But i want from request.user.viewedNotifications to current date and hour.