Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Immediately require credentials on landing page for access to entire site
I want to require credentials on the landing page for access to the entire website for a django app. I googled some stuff but can't find answers. Please point me in the right direction. Thanks -
Time residual function in Python
I have 2 fields in the database: confirmed_at and preparation_time I would like to get two simple functions that should return (a) the time residual and (b) the % of time remaining. This is my logic which I am trying to acheive: - when order is confirmed_at I update the database with datetime.now() and preparation_time is indicated in minutes and stored as integer (for example 5 min is stored as 5) - completed_time is confirmed_at + preparation_time - time_remaining is completed_time - now() - order status is completed_time / now() * 100 This are my functions but I cannot make it works def get_remaining_time(self): start_time = datetime(self.confirmed_at) end_time = (start_time + datetime.timedelta(0,self.preparation_time*60)).time() # days, seconds. return end_time - datetime.now() def get_order_status(self): end_time = (datetime(self.confirmed_at) + datetime.timedelta(0,self.preparation_time*60)).time() return end_time / datetime.now() * 100 Thank you for any help -
How to loop through a form and add same form in django if we click add more button and store that in django
What I really want to do is , if a user click on "ADD more" button then a same form repeat itself and the values should store in database, if he/she doesn't click of that button then only the values from first form should be stored. I am not able to get this, I just created a form , and a table in database for those details but can't loop though the form neither in data. please help. This is the form and the button: This is the model.py code: from django.db import models class experience(models.Model): company_name = models.CharField(max_length=100) address = models.CharField(max_length=100) startdate = models.Datefield(default = 01-01-2020) lastdate = models.DateField(default = 01-01-2020) profile = models.CharField(max_length=100) description = models.TextField(max_length = 250) This is the views.py code: from django.shortcuts import render, redirect import requests from django.contrib.auth.models import User, auth # Create your views here. def profile(request): return render(request, 'profile.html') -
Django Query on parent from child
I am new to Python Django and I want to make a query class A(models.Model): foo = models.IntegerField(default=0) from_time = models.DateTimeField('start time') to_time = models.DateTimeField('end time') class B(models.Model): model_a = models.ForeignKey(A, on_delete=models.PROTECT, related_name='model_a') model_c = models.ForeignKey(C, on_delete=models.PROTECT, related_name='model_c') class C(models.Model): id = models.IntegerField(default=0) name = models.CharField(max_length = 20) I want to make a query on class B where the current time is in between model_a.from_time and model_a.to_time. for that, I tried B.objects.filter(model_c=model_c_id, model_a.to_time__gte=start_date, model_a.to_time__lte=end_date) it gives me syntax error SyntaxError: expression cannot contain assignment, perhaps you meant "=="? -
How do I change language code slug shown in URLs with django-CMS?
In django-CMS, I would like to change the language slugs shown in URLs, like following: https://example.com/ja/ ==> https://example.com/jp/ https://example.com/zh-hans/ ==> https://example.com/cn/ Is it possible? Or I have to use default LANGUAGE_CODE? -
relation "django_migrations" already exists
I am using Django-tenant-schemas for assigning tenants to their own schema. I had a migration issue awhile back and now there is something residual left from the failed creation of a tenant on it's own schema. This schema is called tiger. To give an idea how it is set up; there is some data which is public and exists on the public schema (such as users and companies) but everything else is tenant specific and on its own schema. This is how I run migrations: (venv) david@clearpath:~/clearpath_project$ python manage.py migrate_schemas [standard:public] === Starting migration [standard:public] Operations to perform: [standard:public] Apply all migrations: admin, auth, categories, companies, contenttypes, employees, invite, memos, notifications, phone_verify, quiz, sessions, videos [standard:public] Running migrations: [standard:public] No migrations to apply. [1/5 (20%) standard:clearpath] === Starting migration [1/5 (20%) standard:clearpath] Operations to perform: [1/5 (20%) standard:clearpath] Apply all migrations: admin, auth, categories, companies, contenttypes, employees, invite, memos, notifications, phone_verify, quiz, sessions, videos [1/5 (20%) standard:clearpath] Running migrations: [1/5 (20%) standard:clearpath] No migrations to apply. [2/5 (40%) standard:c1] === Starting migration [2/5 (40%) standard:c1] Operations to perform: [2/5 (40%) standard:c1] Apply all migrations: admin, auth, categories, companies, contenttypes, employees, invite, memos, notifications, phone_verify, quiz, sessions, videos [2/5 (40%) standard:c1] … -
Django admin site: how to get formfield_overrides to override models.CharField with choices
In models.py class AnnualReport(models.Model): SCRAPED = 'scraped' CHECKED = 'checked' CHECKED_AND_RESTATED = 'restated' STATUS_CHOICE = ( (SCRAPED, 'Scraped'), (CHECKED, 'Checked'), (CHECKED_AND_RESTATED, 'Restated'), ) status = models.CharField(max_length=20, choices=STATUS_CHOICE, default=CHECKED) I want to override the style in status's form field in admin site. But I couldn't find the right selector for CharField with choices. As below, models.CharField didn't render custom effects. formfield_overrides = { models.CharField: { ... }, } Moreover, I have tried TypedChoiceField and ChoiceField which didn't work either. So my question is which is the right selector? Thank you! -
Upload an Excel file as a background task in celery? - Celery Redis Python Django
Problem for upload_subscribers.delay parameters can only be integers or strings, I would not be able to pass request or your_file as a parameter into the function. How can I fix the below code so it can be run as a background task in celery? import pandas as pd from .models import Subscriber def upload_subscribers(request): template = "audiences/upload.html" if request.method == "POST": your_file = request.FILES['file'] if your_file.name.endswith('.xlsx'): df = pd.read_excel(your_file) for index, row in df.iterrows(): created = Subscriber.objects.update_or_create( email= row[2], defaults = { "first_name": row[0], "last_name": row[1], }) return None -
Django POST request Ajax cannot get data on server-side
I am trying to get a subscription form working on my site. I am using Stripe. I can send data to Stripe using their API. However, I'm not able to save the data on the server-side after receiving it from Stripe: // In subscription.js: $( function() { var customerEmail = document.querySelector("[data-email]").getAttribute('data-email'); var submissionURL = document.querySelector("[data-redirect]").getAttribute('data-redirect'); var stripeSubscriptionForm = document.getElementById('subscriptionId'); var cardElement = elements.create("card", { style: style }); // Mounting the card element in the template cardElement.mount("#card-element"); stripeSubscriptionForm.addEventListener('submit', function(event){ event.preventDefault(); // Before submitting, we need to send the data to our database too theForm = event.target; // getting the form; same as using getElementById, but using the event only theFormData = new FormData(theForm); stripe.createPaymentMethod( { type : 'card', // this is what's sent to stripe card : cardElement, billing_details : { email : customerEmail, } }, ) .then( (result) => { // Once stripe returns the result // Building the data theFormData.append('card', cardElement); theFormData.append('billing_details', customerEmail); theFormData.append('payement_method', result.paymentMethod.id); // Setting up the request const xhr = new XMLHttpRequest() // Creating an XHR request object xhr.open(method, url); // Creating a GET request // Setting up the header xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); // Ajax header xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // Ajax header xhr.setRequestHeader("X-CSRF-TOKEN", "{{ csrf_token }}"); // csrf_token … -
Django Model *** IndexError: list index out of range
Whenever I create an object, ModelName.objects.create(image = image, owner = user, cordinate_Y=cordinate_Y, cordinate_X=cordinate_X, agency=agency) *** IndexError: list index out of range here is model.py class ModelName(models.Model): image = models.ImageField(upload_to=image_file_name_before, blank=False) name = models.CharField(max_length=300, null=True, blank=False, default='None') owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False ) ... extra_fields = models.CharField(max_length=100, null=True, blank=True, default='None') ... cordinate_X = models.FloatField(blank=False) cordinate_Y = models.FloatField(blank=False) agency = models.CharField(max_length = 50, default = 'GENERAL', blank=False) I have tried almost everything but actually not able to understand why I am getting stuck at this. it's working fine if I create from Django admin though. Thank you for reviewing. -
NameError: name 'six' is not defined. six in not working with django and leaflet
i need some help with my leaflet config. i'm getting this error when running the server since i added leaflet to my django-3.04 project. File "/Library/Frameworks/Python.framework/Versions/3.8/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 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/marcusbey/.local/share/virtualenvs/rb-website-fKSjEdfu/src/django-leaflet/leaflet/__init__.py", line 80, in <module> if DEFAULT_PRECISION is not None and not (isinstance(DEFAULT_PRECISION, six.integer_types) and (4 <= DEFAULT_PRECISION <= 12)): NameError: name 'six' is not defined I installed six and add it to the settings.py file but still getting that same error. i don't know where else to look and what to do. :/ -
Writing Unit Test for my Class based views which also require LoginRequiredMixin
I have one ListView and one DetailView and both requires LoginRequiredMixin. Now i want to write unit test for these class based views. Can somebody help me with this. I want to test the template, context as well as right view is called. My Tests.py Looks like this:- from django.test import TestCase, Client from django.urls import reverse,resolve from django.test.client import RequestFactory from django.contrib.auth import get_user_model from teams.models import Teams from teams.views import TeamListView, TeamDetailView class TestTeamsView(TestCase): def setUp(self): self.factory = RequestFactory() def test_list_view(self): request = self.factory.get(reverse('teams:team_list')) response = TeamListView.as_view()(request) self.assertEqual(response.status_code, 200) print(response.status_code) I am getting Response: if not request.user.is_authenticated: AttributeError: 'WSGIRequest' object has no attribute 'user' -
how to use class based views for a single page blog with pagination in django
someone should please help me solve this problem i have been on it for the past 3days, i have a single blog which is handled by multiple author or admin,so i decided to use class based views and when i create a new post gives an error saying i need blog_detail.html,since i dont have detail blog so i created a Detailview then adding my template_name = 'mymainblogpage.html' so once i create new post it will get posted but wont show the post but will only show the pagination,besides i cant search by post id for example http://127.0.0.1:8000/pages/blog/49/ i just get nothing i cant show picture i would have shown you, here is my code. views.py def blog(request): blog_post = Blog.objects.all() ordering = ['-timestamp'] paginator = Paginator(blog_post, 2) page_request_var = 'page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(2) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) context = { 'queryset': paginated_queryset, 'page_request_var': page_request_var } return render(request, 'pages/blog.html', context) class BlogDetailView(DetailView): model = Blog template_name = 'pages/blog.html' context_object_name = 'blog' urls.py path('blog/', BlogDetailView.as_view(), name='blog'), path('blog/<int:pk>/', BlogDetailView.as_view(), name='blog-detail'), models.py def get_absolute_url(self): return reverse('blog-detail', kwargs={'pk': self.pk}) -
Django: When form is submitted, auto-fill a field
I'm looking to auto-fill a field when I submit a form so it is identical to another field. I have a createView with a modelForm. The idea is the user writes his/hers name, which then when submitted fills out the display_name field as well. I know it's weird "why have two of the same", but it has a purpose. Here's my code - I'm guessing I need to create a context that gets the display_name and sets it to be equal to the name? views.py class CreateIdentity(CreateView): template_name = 'admin/CreateIdentity.html' model = Identity form_class = CreateIdentityForm queryset = Identity.objects.all() def get_context_data(self, **kwargs): context = super(CreateIdentity, self).get_context_data(**kwargs) context["user_id"] = User.objects.get(username=self.request.user) return context def form_valid(self, form): form.instance.user_id = self.request.user return super().form_valid(form) def get_success_url(self): return reverse_lazy("view_identity_created_with_slug", kwargs={'slug': self.object.slug}) models.py class Identity(models.Model): name = models.CharField(max_length=200, null=False) display_name = models.CharField(max_length=200) slug = models.SlugField(max_length=100) user_id = models.ForeignKey(User, db_column="username", on_delete=models.CASCADE, null=False) -
How to get Twilio worker for incoming calls using TaskRouter? - Django
I'm building a simple Django contact center app using Twilio, TaskRouter, Client JS SDK. I'm using the status_callback to save the calls log for each customer in db by listening to the request with complete status_callback_event. (not sure this is the best way but it does the job) How would you go about saving the worker who received the incoming call? For outgoing calls I'm passing the request.user in the url as a costume parameter and I'm getting it in the status_callback. For incoming calls I'm getting the ParentCallSid in the status_callback, I assume I can use it to fetch the client who handled the call through the Rest API. Am I doing the right thing here? is there a simpler way to get this done? -
Can't get CKEditor field to display in django template
I'm trying to install CKEditor for a simple blog app but the form isn't appearing in my form template although it does appear in the admin form. Models.py: from ckeditor.fields import RichTextField class Post(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) title = models.CharField(max_length=100, blank=False) content_text = RichTextField(blank=True, null=True, max_length=3000) Forms.py: class PostForm(ModelForm): class Meta: model = Post widgets = {'content_text': forms.Textarea(attrs={'cols': 80, 'rows': 80}), 'tags': TagWidget(), } fields = ['title', 'video_URL', 'content_text', 'score', 'tags',] HTML template with form: <form method="POST"> {% csrf_token %} {{ form.media }} <div class="input-wrap"> <label for="title">Title</label> <input type="text" name="title" class="form-control" id="title" style="color: #FFFFFF" required> </div> <div class="input-wrap"> <label for="content_text">Content Text</label> <textarea name="content_text" class="form-control" style="color: #FFFFFF" id="content_text" required></textarea> </div> -
Can I use {% static %} outside the base.html in Django?
I am a beginner in Django and i have setup a project with a base.html file along with the folder static/images/img.jpg. base.html is setup correctly. Everything works inside this file but i have another file called index.html in the templates folder. So, in other words in the base.html i can use the command {% static '/images/img. jpg' %} but in my index.html Django does not recognise the command. In the index.html I have already provided the required commands {% extends 'base.html' %} and {% load static %} Does this command work only in the base html? Do i need another command for files outside the base.html Thank You -
Unit Test Case of redirection after successful Login of auth login view in Django
I have used django auth login view and mentioned LOGIN_REDIRECT_URL = '/team/' in my settings.py. Now i want to write the unit test case if user successfully login then it should redirect to /team/. Can anybody help me. Thanks in advance.. My Login Url is: path('login/', auth_views.LoginView.as_view(template_name = 'accounts/login.html'), name="login"), My Test Case is : class TestTeamsListView(TestCase): def setUp(self): obj1 = User.objects.create(username='test',email= 'abc@gmail.com', first_name='t', last_name='u', password="password") self.login_url = reverse('accounts:login') def test_on_successful_login(self): client = Client() response = client.post(self.login_url,{'username':'test','password':'password'},format='text/html') self.assertEqual(response.status_code, 302) When i run test then i am getting this result: AssertionError: 200 != 302 -
The included URLconf '…\blog\urls.py'>' does not appear to have any patterns.If you see valid patterns then the issue is caused by a circular import
enter image description hereenter image description here pls help to find the solution. The detail error are as follow, (base) C:\Users\USER\Documents\Django Tutorial\django_blog>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 586, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Anaconda3\lib\threading.py", line 914, in _bootstrap_inner self.run() File "C:\Anaconda3\lib\threading.py", line 862, in run self._target(*self._args, self._kwargs) File "C:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Anaconda3\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Anaconda3\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "C:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Anaconda3\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 593, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: **The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a … -
Django 3 ModelForm NameError? I'm sure there's a glaring error but I just cannot see it?
Hoping for a bit of help, I've been trying to deal with this error for about 3hrs and I'm going around in circles. Django 3 project. It's a simple app for leaving a review for a product and I keep getting a NameError and I just can't figure out what it is? models.py from django.db import models from django.forms import ModelForm, Textarea, CharField from django.conf import settings from django.contrib.auth.models import User from products.models import Product SCORE_CHOICES = [ ('1', 'One'), ('2', 'Two'), ('3', 'Three'), ('4', 'Four'), ('5', 'Five'), ] class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date = models.DateField() review_title = models.CharField(max_length=100, blank=False) review_text = models.TextField(default='') score = models.CharField(max_length=3, choices=SCORE_CHOICES) def __str__(self): return f'Review for user {self.user.username}' class ReviewForm(ModelForm): class Meta: model = Review fields = ['user', 'product', 'date', 'review_title', 'review_text', 'score'] widgets = { 'review_text': Textarea(attrs={'cols': 100, 'rows': 20}), } forms.py from django import forms from django.forms import ModelForm from products.models import Product from review.models import Review, ReviewForm class ReviewForm(forms.Form): product = forms.ModelMultipleChoiceField(queryset=Product.objects.all()) review_title = forms.CharField(max_length=100) review_text = forms.CharField(max_length=100, widget=forms.Textarea) score = forms.CharField( max_length=3, widget=forms.Select(choices=SCORE_CHOICES), ) date = forms.DateField(auto_now=True, editable=False, null=False, blank=False) user = forms.CharField(max_length=100) views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http … -
limitaion for editing profile in Django
how can I set limitaion times for users to edit their profile ? for example, they should have only 2 chances to edit username or email. and if they edit username 2 times, this field would be disabled next time they open the edit page. -
How to remove required from Django-Widget-Tweaks form field
I am trying to remove the required attribute from a django-widget-tweaks form. I tried: {% render_field form.legal_entity|attr:'required:false' placeholder=form.legal_entity.label class+="form-control" %} and {% render_field form.legal_entity|remove_attr:"required" placeholder=form.legal_entity.label class+="form-control" %} No matter what I do, the result is always: <input type="text" name="legal_entity" maxlength="120" class="form-control" placeholder="Firmenname" required id="id_legal_entity"> -
how to learn data from html by views in django
i create a html login.html function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } body {font-family: Arial;} /* Style the tab */ .tab { overflow: hidden; border: 1px solid #ccc; background-color: #f1f1f1; } /* Style the buttons inside the tab */ .tab button { background-color: inherit; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; transition: 0.3s; font-size: 17px; } /* Change background color of buttons on hover */ .tab button:hover { background-color: #ddd; } /* Create an active/current tablink class */ .tab button.active { background-color: #ccc; } /* Style the tab content */ .tabcontent { display: none; padding: 6px 12px; border: 1px solid #ccc; border-top: none; } /* Full-width inputs */ input[type=text], input[type=password] { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; box-sizing: border-box; } /* Set a style for all buttons */ .tabcontent button { background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; … -
pass a choice value by default to a form before saving it in django
so the idea is thrt you can make a user able to create new services after activating is_staff in django admin panel for it's user acccount then he will become a distributor this is the linked models for the service and the distributor: models.py class Distributor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True, blank=True) service_ch =[('credit','credit'),('games','games')] name = models.CharField(max_length=200,null=True,blank=False) phone = PhoneNumberField(null=True,blank=False) address = models.CharField(max_length=200,null=True,blank=False) facebook = models.CharField(max_length=200,null=True,blank=False) ccp = models.BigIntegerField(null=True,blank=False) key = models.IntegerField(null=True,blank=False) def __str__(self): return self.name class Service(models.Model): type_ch = [('credit','credit'),('game','game')] currency_ch = [('€','€'),('$','$'),('DZD','DZD'),('Unit','Unit')] distributor = models.ForeignKey(Distributor,on_delete=models.SET_NULL,null=True,blank=False) model = models.CharField(choices=type_ch,max_length=20,null=True,blank=False) name = models.CharField(max_length=200,null=True,blank=False) price = models.FloatField(default=0.00) currency = models.CharField(choices=currency_ch,max_length=20,null=True,blank=False) available = models.FloatField(null=True,blank=False) image = models.ImageField(default='defser.png') def __str__(self): return self.name the ServiceForm for creating a new service works fine if i choose the distributor manually forms.py class ServiceForm(forms.ModelForm): class Meta(): model = Service fields = ['distributor','model','name','price','currency','available','image'] def __init__(self, *args, **kwargs): super(ServiceForm, self).__init__(*args, **kwargs) self.fields['model'].widget.attrs['class'] = 'form-control-account' self.fields['name'].widget.attrs['class'] = 'form-control-account' self.fields['distributor'].widget.attrs['class'] = 'form-control-account' self.fields['price'].widget.attrs['class'] = 'form-control-account' self.fields['currency'].widget.attrs['class'] = 'form-control-account' self.fields['available'].widget.attrs['class'] = 'form-control-account' views.py def service_create(request): user = request.user if user.is_staff: if request.method == "POST": form = ServiceForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request,'Service has been added successfully.') return HttpResponseRedirect(reverse('saller')) else: raise PermissionDenied() form = ServiceForm() return render(request, 'app/service_form.html', {'form': form}) the problem is the user … -
How can I handle PUT requests in django? (not drf)
I tried to get data from PUT requests in this way name = request.PUT["name"] but it cause error : 'WSGIRequest' object has no attribute 'PUT'