Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter False in a list of Booleans
I've five Product objects with 3 product's availability set to True and rest False, I'm trying to set Checkout Status Button to Out of Stock even if one product has availablity set to False. Because cart view cannot use slug, {% if product.availability %} is pointless, and can't use 'for loop' or it would create multiple checkout buttons, what's the way to fix this? Model class Product(models.Model): availablity = models.BooleanField() View def cart(request): products = Product.objects.all() Cart template {% for product in products %} <p>{product.name}</p> <p>{product.price}</p> {% endfor %} <!--Checkout Status Button--> {% if product.availability %} <a href="#">Checkout</a> {% else %} <p>Out of stock</p> {% endif %} -
Dynamic query builder django
I'm working on a project with django, and i would like to use MUI-QueryBuilder (based on react). I would like to have this output: http://tiagofernandez.com/mui-querybuilder/?path=/docs/muiquerybuilder--supported-types. The main objective for me is to make a dynamic query builder. Can someone help me ? Thanks. -
Why does my Django test don't wan't to connect me anymore?
I developped a Django app like 6 month ago and I wan't to use it again. But I ran test and all my tests that need me to log a user fails (while they were succesfull before). For example I have this : class TestViews(TestCase): def setUp(self): self.client = Client() # Setting up user self.user = UserExtension.objects.create(id=1, username="martin", email="martin@internet.net") self.user.set_password('secret') self.user.save() def test_account_detail_authenticated(self): self.client.login(username="martin", password="secret") response = self.client.get('/account/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context["username"], "martin") self.assertEqual(response.context["email"], "martin@internet.net") And it give me this error : AssertionError: 302 != 200 Why ? Because my site want to redirect me on login page, cause i can't access account page if not connected. So the problem is I can't login. For test database I use a local postgreSQL and for test I use pytest (it fail the same way if I use python manage.py test) -
Should I store images on a server or use a CDN?
Q: I'm making a website for a friend in django and I was wondering should I use a CDN (like AWS) to store images or should I just store them on the same server as the website itself? The website in question is a website for his parents' company and I doubt it would have more than a couple of tenths of visits per day. However, there would be quite a few pictures. Homepage would have 3-4 images, a portfolio page would have around 10-15 projects with a main picture and upon clicking on each project a new page would open which would have ~8 pictures of the project itself. Let's say that at any given time there would be about 100 pictures on the website. Since I don't have much experience with web-dev I'm not sure which approach is better or should I say, CDN is a better approach but I'm unsure if it's needed in this case. -
Access key value model in django for dynamic template
the goal is to make texts in static templates like "about us" page dynamic with a model so that it can be edited easily later on. My first approach was to create a static model in which I had to set a field for each data I intend to put on my templates, such as "main_page_intro" or "about_page_company_info" and so on. But a friend of mine suggested that this approach is static itself and is not right. He proposed that I create a model with only two fields, “key” and “value”. “key” to name where the text is supposed to used (e.g. main page introduction) and “value” to write the actual text which should be displayed. So now I have this model: models.py from django.db import models class SiteDataKeyValue(models.Model): key = models.CharField(max_length=200, verbose_name="Text place") value = models.TextField(verbose_name="Text") def __str__(self): return self.key Now I have problems continuing this route and using this model. Suppose that I created an object in this model, with a key = "main page introduction text" and a value of = "some text here". How am I supposed to write a view for this and how should I use these key and values in my template? P.S.: … -
How to select the half last elements in the result record set by using an attribute in django queryset?
I want to select the half last elements in the result record set by using an attribute somethingelse stored in MyModel. I tried without success with: MyModel.objects.filter(something="foobar")[:F("somethingelse") // 2)] -
How can i keep Django summit form and show a message to user?
I want to create a user when an article submit in Django admin form. I want to check a user is existed or not. After it, I want to show a message to user that user is existed, and he can change username to create. Article model fields: family username . . -
checklist not getting value django form
When I try to edit info on my table. Everything works perfectly except for the fact that my checklist does not get value. All other fields get value when the edit modal is loaded. Note that when I tried getting value on a separate page instead of a modal it still did not work. I have cut my code to make it more readable. If you want to see more please let me know. Here is my code. forms.py: class TraineeForm(forms.ModelForm): GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other') ] EDUCATION_CHOICES = [ ('P', 'Primary'), ('J', 'Junior'), ('S', 'Senior') ] TraineePic = forms.ImageField(label="Image :", required=False, widget=forms.ClearableFileInput()) Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :') Course = forms.ChoiceField(widget=forms.Select(attrs={'class':'col-sm-4'}),choices=course_choices, label='Course :') BatchNo = forms.CharField(widget=forms.NumberInput(attrs={'class':'col-sm-4', 'placeholder':'Numbers only'}), label='Batch No :') Gender = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': 'col-sm-4 form-check-inline', 'id':'id_Gender'}),label='Gender :', choices=GENDER_CHOICES) Education = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'col-sm-4 form-check-inline','id':'id_Education'}), label='Education :', choices=EDUCATION_CHOICES) class Meta(): model = Trainee fields = ("Name","Course","BatchNo","Gender","Education",) views.py: def updateTrainee(request, id): trainee = get_object_or_404(Trainee, pk=id) if request.method == "POST": form = TraineeForm(request.POST,request.FILES,instance=trainee) if form.is_valid(): form.save() return HttpResponse(status=204, headers={'HX-Trigger' : 'changeDetected'}) else: form = TraineeForm(instance=trainee) return render(request, 'MyTestApp/save.html', {'form':form}) save/edit.html: <form class="modal-content" enctype="multipart/form-data" hx-post="{{request.path}}" autocomplete="off" > {%csrf_token%} <div class="modal-header"> {% if trainee %} <h5 class="modal-title"> Edit a Trainee </h5> … -
django.db.utils.IntegrityError: UNIQUE constraint failed: When creating a new profile with post_save signal from django.contrib.auth.models.User
Is anything wrong with this code? from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: inst = Profile.objects.create( user=instance ) Any time I try adding a user the profile creation fails with the error below. This is true even if I clear the db django.db.utils.IntegrityError: UNIQUE constraint failed: Accounts_profile.user_id -
JSPdf not loading issue when trying to upload image
I have created a pdf format with JsPdf and I want to add an image in it. When I try to add the same pictures to any blank pdf, the pictures are added correctly, but when I load them into the pdf I am using, there is a problem with the pictures loading. I am attaching the images like this: var logo = document.getElementById("logo").src; console.log(logo); doc.addImage(logo, "PNG", 5, 2, 20, 10); pdf size before adding image: 187 KB after adding : 3.171 KB How can I add these images here? -
I want to upload a xml file into a PostgreSQL using Django
I am new to Django and my current task is to upload a xml file with 16 fields and more than 60000 rows to a database in PostgreSQL. I used Django to connect to the Database and was able to create a table in the database. I also used XML Etree to parse the xml file. I am having trouble storing the data in the table that I created in the sql database. This is the code that I used to parse: import xml.etree.ElementTree as ET def saveXML2db(): my_file = "C:/Users/Adithyas/myproject/scripts/supplier_lookup.xml" tree = ET.parse(my_file) root = tree.getroot() cols = ["organization", "code", "name"] rows = [] for i in root: organization = i.find("organization").text code = i.find("code").text name = i.find("name").text x = rows.append([organization, code, name]) data = """INSERT INTO records(organization,code,name) VALUES(%s,%s,%s)""" x.save() saveXML2db() the code runs without any error, but I am unable to store the data into the table in the SQL database. Please help -
django collectstatic without db connection?
while I am running python manage.py collectstatic --no-input I am getting a DB connection issue. i want to collect statics without a DB connection to dockerize my Django app. with DB connection it's working fine. -
How do I apply a Bootstrap style to all form fields using widgets in Django?
I have a lengthy form so I am rendering it using fields = "__all__" in the class Meta. I was wondering if there is a way to apply a style to all fields without having to express them all individually in widgets? The style I am looking to apply to all fields is attrs={'class': 'form-control'} which is a bootstrap style. forms.py: class CompanyDirectApplication(forms.ModelForm): class Meta: model = Direct fields = "__all__" widgets = { 'completed': forms.HiddenInput(), 'important_persons': Textarea(attrs={'class': 'form-control'}), } labels = { "important_persons": "Please list all Directors, Partners, Associates and Company Secretary:", "trading_name": "Trading Name (if different)", # Many more labels follow this } -
Field 'id' expected a number but got 'pk'
I'm writing some simple unit tests for my class based views. I've completed the tests for urls in which I've used args = ['pk'] for urls that had pks. However, when doing similar tests to views, ones with pks ends with the error Field 'id' expected a number but got 'pk' '. Here's the working URL test: url = reverse('user', args=['pk']) self.assertEquals(resolve(url).func.__name__, GetUser.as_view().__name__) Class based view test that gets the error: class TestViews(TestCase): def setUp(self): self.client = Client() self.single_user_url = reverse('user', args=['pk']) def test_single_user_view(self): response = self.client.get(self.single_user_url) self.assertEquals(response.status_code, 200) -
How to display a different page when user refreshes the current page in Django
I am a beginner in Django and I want to display page-y when the user refreshes the page-x -
Django 'AnonymousUser' object has no attribute '_meta' for login by email
I'm trying to Allow both email and username login in the Django project, So, I have added additional backends in my settings.py file. AUTHENTICATION_BACKENDS = ( "accounts.auth.AuthenticationEmailBackend", "django.contrib.auth.backends.ModelBackend", ) and this is the views file def login_view(request): if request.method == 'POST': email =request.POST['username'] password = request.POST['password'] user = authenticate(username=email, password=password) print(user) #if user is not None: login(request,user,backend="accounts.auth.AuthenticationEmailBackend") return redirect('/') else: pass return render(request,'accounts/login.html') when i use my email, I get this error when i click login button on my form,but when i use my username it works fine and i can log in to my acc 'AnonymousUser' object has no attribute '_meta' -
Taking in input calculating average using django
A person would type a number, django should be able to calculate average after each submission, 10000 estimated people who input a number, how do I achieve this. -
how to make a form field not part of the submitted form
I have an extra field in a django form that triggers javascript to change the fields in other forms: class MyForm(forms.ModelForm): my_extra_form_field = forms.ChoiceField() class Meta: model = MyModel fields = ["field1", "field2"] field_order = ["field1", "my_extra_form_field", "field2"] How can I ensure that my_extra_form_field is not included in the submiteed form? -
Bootsrap cards showing only vertically and not in a tabular format
Heres the code in html [Heres what is showing on the website][1] https://i.stack.imgur.com/5bB78.jpg > {% extends 'base.html' %} > > {% block content %} > <h1>Products</h1> > <div class="row"> > {% for product in products %} > <div class="col"> > <div class="card" style="width: 18rem;"> > <img src="{{ product.image_url }}" class="card-img-top" alt="..." width="300" height="300"> > <div class="card-body"> > <h5 class="card-title">{{ product.name }}</h5> > <p class="card-text">${{ product.price }}</p> > <a href="#" class="btn btn-primary">Add to Cart</a> > </div> > </div>[enter image description here][1] > </div> > {% endfor %} > </div> {% endblock %} -
Django project working fine in local host but making full of issues on hosting in c panel
I developed a website with django its working fine in local host.. but while hosting on c panel..static file issue cant link to another pagesnow only index page is working other pages its showing errer 404 -
Celery periodic task not showing in django table
Using Django 3.2 and celery to configure periodic tasks on AWS ECS. I have many periodic tasks which are running fine and created 2 new periodic tasks, but these tasks are not detected and not showing up in the Periodic Tasks table in Django admin The configuration I have is celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qcg.settings') app = Celery('qcg') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # Celery-beat-configuration CELERY_BEAT_SCHEDULE = { 'authentication-1': { 'task': 'authentication.periodic_task.clear_refresh_token', 'schedule': crontab(hour=23) }, 'authentication-2': { 'task': 'authentication.periodic_task.assistance_email_after_registration_task', 'schedule': crontab(hour=2) }, 'authentication-3': { 'task': 'authentication.periodic_task.send_reminder_email_before_deletion_task', 'schedule': crontab(hour=23) }, 'authentication-4': { 'task': 'authentication.periodic_task.delete_inactive_accounts_task', 'schedule': crontab(hour=23) } } The following two tasks are showing in the Periodic Tasks table authentication-1 authentication-2 While the other two tasks are not showing in the Period Tasks table and also not executing. The celery.py setting is as CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_DEFAULT_QUEUE = 'celery' CELERY_TASK_ACCOUNT_QUEUE = 'qcg-account-queue' CELERY_BROKER_URL = 'sqs://' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_TRACK_STARTED = True CELERY_RESULT_EXTENDED = True CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_BROKER_TRANSPORT_OPTIONS = { 'visibility_timeout': 43200, 'polling_interval': 60 } And running the beat service as ["celery","-A","qcg","beat","-l","info","--pidfile","/tmp/celerybeat.pid"] and celery service as ["celery","-A","qcg","worker","-l","info","--concurrency","4"] -
Memurai not working with Django app in development with SSL
I'm building the Django app chat using Memurai. The app is in the development process, but I'm facing an issue. The issue is when I attach the SSL on development my chat not working. How can I configure Memurai with an SSL certificate? I will appreciate you if you guide me. -
Unable to subscribe to GCP Pub/Sub when running a server of Django application
I have a standalone python file and its subscribe to a topic and able to pull the message from the topic which is created in GCP. Would like to know, How do we initialize the subscription during python manage.py runserver ? Is it possible to avoid standalone file and include that in Django Project ? I am trying to add a subscription code in the manage.py file and getting error. def topic_subscription(): subscriber = pubsub_v1.SubscriberClient() project_id = "XXXXXXXXX" subscription_id = "XXXXXXXXXXXXX" subscription_path = subscriber.subscription_path(project_id, subscription_id) streaming_pull_future = subscriber.subscribe(subscription_path, callback="CallBackMethod in another app for processing") with subscriber: try: streaming_pull_future.result() except TimeoutError: streaming_pull_future.cancel() Error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Djago time widget not showing up
All I want to do is add time widget to my form so I can easily pick the time. Everything is very simple, the page is loading but the widgets don't show up. No error nothing. I am thinking maybe I didn't set up the form widgets correctly but not sure what I did wrong. Here is my Forms.py- from django.contrib.admin import widgets from django.contrib.admin.widgets import AdminDateWidget, AdminTimeWidget, AdminSplitDateTime class WorkOutForm(ModelForm): class Meta: model = WorkOut fields = '__all__' widgets={ 'start':AdminTimeWidget(), 'end':AdminTimeWidget(), } Here is the Models.py. You will notice "start" and "end" fields are timefield- class WorkOut(models.Model): date=models.DateField(auto_now_add=True, auto_now=False, blank=True) day=models.DateField(auto_now_add=True, auto_now=False, blank=True) start=models.TimeField(null=True) name=models.CharField(max_length=100, choices=move) weight=models.CharField(max_length=100, blank=True) rep=models.CharField(max_length=100, blank=True) pedal= models.CharField(max_length=100, blank=True) stretchtype =models.CharField(max_length=100, blank=True) end=models.TimeField(null=True) note=models.TextField(max_length=300, blank=True) def __str__(self): return self.name And here are the views linked to it even though I don't think it has much relevance- def workout(request): form=WorkOutForm() if request.method=="POST": form=WorkOutForm(request.POST) if form.is_valid(): form.save() context={'form':form} return render(request, 'myapp/enter_workout.html', context) def update_workout(request, pk): order=WorkOut.objects.get(id=pk) form=WorkOutForm(instance=order) if request.method=='POST': form=WorkOutForm(request.POST, instance=order) if form.is_valid(): form.save() context={'form':form} return render(request, 'myapp/enter_workout.html', context) And the form on HTML page is also very basic,so don't think there is any issue there either- <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Submit"> … -
Is this the fastest way to create a large list of model instances in Django that require an id lookup for a ForeignKey field?
Models class Foo(models.Model): name = models.CharField # ... class Bar(models.Model): foo = models.ForeignKey(Foo) # ... Is this the fastest way to create new instances of Bar given a list of Foo names? Or is there a way you can use foo's name in the creation of the Bar instance? to_create = [] for name in names: try: foo = Foo.objects.only('id').get(name=name).id except Foo.DoesNotExist: continue to_create.append(Bar(foo=foo, *other_fields)) Bar.objects.bulk_create(to_create)