Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, annotate field with id of many-to-many field's element with lowest parameter
I have the following models: from django.db import models class Topping(models.Model): # ... price = models.IntegerField() class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) I need to get following query: my_query = Pizza.objects.all().annotate( topping_with_min_price="get id of topping with the minimal price") So, how to get that? -
Does anyone have idea how to start with cardconnect/cardpointe payment gateway integration?
Cardpointe is payment gateway i need to integration for my django web application. and I am integrating for the first time. https://developer.cardpointe.com/cardconnect-api -
How do celery workers communicate in Heroku
I have some celery workers in a Heroku app. My app is using python3.6and django, these are the relevant dependencies and their versions: celery==3.1.26.post2 redis==2.10.3 django-celery==3.2.2 I do not know if the are useful to this question, but just in case. On Heroku we are running the Heroku-18 stack. As it's usual, we have our workers declared in a Procfile, with the following content: web: ... our django app .... celeryd: python manage.py celery worker -Q celery --loglevel=INFO -O fair one_type_of_worker: python manage.py celery worker -Q ... --maxtasksperchild=3 --loglevel=INFO -O fair another_type: python manage.py celery worker -Q ... --maxtasksperchild=3 --loglevel=INFO -O fair So, my current understanding of this process is the following: Our celery queues run on multiple workers, each worker runs as a dyno on Heroku (not a server, but a “worker process” kind of thing, since servers aren’t a concept on Heroku). We also have multiple dynos running the same celery worker with the same queue, which results in multiple parallel “threads” for that queue to run more tasks simultaneously (scalability). The web workers, celery workers, and celery queues can talk to each other because celery manages the orchestration between them. I think it's specifically the broker that … -
Post Request in NESTED API from the FrontEnd
I have a question regarding a post request to a nested api. Say we have an API looking like this : [ { "id": 2, "name": "John Smith", "age": 34, "dob": "21-06-2021", "image": null, "party_details": [ { "id": 2, "party": 2, "adress": "Oxford Street No1", "date": "22-06-2021", "arrival": "09:30 PM" } ] } ] How do you make a post request from the frontEnd to enter data in both Models at the same time. Must I add that the API is build in DRF and these are two models with a relationship between them and a nested serializer. One is User and the other is party_details. It work's fine in POSTMAN but I just can't find a way to upload data from the frontEnd I tried Axios but I can't find a way to also send data to the party_details model at the same time. I have no ideea how to approach this. Any help will be much apreciated! Thank you for your time -
How can i get the data-value with what statment?
How can i get the data-vale? On html file <form method='get' action='#'> <input type="submit" data-value="1" value="Edit" name="Type" /> <input type="submit" data-value="1" value="Delete" name="Type" /> In django views if request.GET.get('Type') == 'Delete': print (request.GET.get('Delete')) -
Method notify in User Model
Does anybody can explain how can I implement method def notify : in User model django and for What I need it ? Some guy recomend me to set this method to User model.But for what? How it must to work? I have the next code below: users.py class User(AbstractUser): class Roles(models.IntegerChoices): ..... Here must to be this method ? But how it works to notify user? Then in users.py I have Notification model: class Notification(models.Model): user = models.ForeignKey('User', models.CASCADE, related_name='notifications') message = models.TextField('Message') created_at = models.DateTimeField('Seen', auto_now_add=True, editable=False) def __str__(self): return f"{self.message}" class Meta: verbose_name = 'MSG' verbose_name_plural = 'MSG' ordering = ['-created_at',] So in views.py I have class NotificationListView(core.ListView): permission_classes = [AllowAny] model = Notification context_object_name = 'notifications' template_name = 'auth/notifications.html' def get_queryset(self): return super().get_queryset().filter(user=self.request.user) Please do not advice me some library or other settings to set notification.I checked it 2 days. I tried it.But I believe this def notify method in User can help explain my problem without other outside library.It you have some example please help! -
Do we have to transfer the Django Files also while transferring all the Project Files to Ubuntu 20 using FileZilla?
Do we have to transfer the Django files too while transferring Project files which are the Html, python and static files to Ubuntu 20 using FileZilla? And by Django Files I mean the Files that get installed after we run the command pip install django. Thank you -
What are the different programming language used for????? please need help for python code to run to website
It's been 3 years i have been into python , have a very amazing grasp of it and made a very good software . Now i want to build a website(which i don't know how to do) in which it asks user for input and that input goes into my python code and after the code gets run , the output should be shown to the user on the website. Now i was searching how to do it , someone saying you cant run python code someone said use django ,flask , someone said run it on node js. I am very confused how , what to do somenone please help it's been 2 months i am stuck please help!!!!!!! please -
Problem with creating Carousel slider in Django
Recently, I tried to create a Django website and I wanted to add a carousel slider component to it but when I do that, all the images appear on top of each other! What should I do? Best Regards Masoud My Code: {This code is in the base.html file} <div id="demo" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ul class="carousel-indicators"> <li data-target="#demo" data-slide-to="0" class="active"></li> <li data-target="#demo" data-slide-to="1"></li> <li data-target="#demo" data-slide-to="2"></li> </ul> <!-- The slideshow --> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static "images/3.jpg" %}" alt="Los Angeles"> </div> <div class="carousel-item"> <img src="{% static "images/4.jpg" %}" alt="Chicago"> </div> <div class="carousel-item"> <img src="{% static "images/5.jpg" %}" alt="New York"> </div> </div> <!-- Left and right controls --> <a class="carousel-control-prev" href="#demo" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" href="#demo" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> -
Why doesn't request.GET.get("edit") work in my code?
I'm trying to make a view in Django, in where if the edit button is pressed on that page it is passed on to another view as a session. def page(request,user_input): entry = util.get_entry(user_input) name = user_input.capitalize() request.session['name'] = name request.session['entry'] = entry if request.GET.get("edit"): # **<- This is not working for some reason.** request.session['edit'] = True else: request.session['edit'] = False return render(request, "homepage/page.html", { "entry":entry, "title":name, }) Here is my page.html file {% block body %} {% if entry %} <h1>{{title}}</h1> {{ entry }} {% endif %} <form action="{% url 'create' %}" name='edit'> <input type="submit" value='edit' class="button"> </form> {% endblock %} This is the view where I want to use the session def create(request): change =request.session['edit'] if request.GET.get('submit'): title = str(title).lower() if change: util.save_entry(title,content) return HttpResponseRedirect('/index') -
Django Forms Customization
I have a page that displays products that have been ordered and I want to give the user the ability to leave a review on their products which have been ordered. I have a review model as well, but when rendering the form it will list all of the products available on the website when I want only the products the customer has ordered to display. Is this possible? I am unsure how to accomplish this with django. This is the form class ReviewForm(forms.ModelForm): class Meta: model = Review exclude = ['user', 'date'] widgets = { 'product': forms.Select(attrs={ 'class': 'form-control' }), 'rating': forms.NumberInput(attrs={ 'class': 'form-control', 'placeholder': '5.0..' }), 'comment': forms.Textarea(attrs={ 'class': 'form-control' }) } This is the view with the get request only class MyOrdersView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): try: order = ShoppingCartOrder.objects.filter(user=self.request.user, ordered=True) form = ReviewForm() context = { 'object': order, 'form': form } return render(request, 'my_site/my_orders.html', context) except ObjectDoesNotExist: messages.warning(request, 'You do not have any orders') return redirect('all_products') And if needed this is how I am displaying the form on the page <div class="container w-25 mb-5"> <form> {% csrf_token %} {% for field in form %} <div class="form-group px-3 my-3"> {{ field.label_tag }} {{ field }} … -
how to send reset password email at the creation of my user in django API?
I build an API with django and I'm automating the welcome email at creation of one user with Sendinblue. I have no problem at this step. (so we are at the url /add_user/) I have a second url to send a link (uid + token) to a user (thanks to his email). For that I use an external package : djoser. So I use the url of djoser /auth/users/reset_password/ and /auth/users/reset_password_confirm/ My dream would be to combine these 2 functionnalities in the single url /add_user/ My problem is that the logic in /reset_password/ and /reset_password_confirm/ was written by djoser so I can't handle it. Or I don't know how ! Here is what I tried to override djoser views : in urls.py: path('custom_djoser/', ChangeCredentialsView.as_view(), name='customdjoser'), in views.py: class ChangeCredentialsView(UserViewSet): def post(self, *args, **kwargs): print("hello world") return JsonResponse({"helloworld":"success"}) got the following error : The actions argument must be provided when calling .as_view() on a ViewSet. For example .as_view({'get': 'list'}) So I removed the .as_view() in urls.py and got this error : Forbidden (CSRF token missing or incorrect.): /custom_djoser/ For me its incomprehensible because I don't use csrf token, but I tried with @csrf_exempt in a dispatch function inside my class. I … -
How to change base choice in OrderingFilter from django-filter?
I have such filter and i'd like to do one of these things: Change -------- to other label Remove -------- Set From cheaper to expensive as a base choice and remove --------- -
Django: how can i change cat_id to cat_slug without deleting database?
Cat_id in sqlite is int right now. Is there any way to change it to slug without deleting whole database? I've already deleted it while changing men_id to slug and it was pretty long action. from django.db import models from django.urls import reverse class Men(models.Model): title = models.CharField(max_length=50, verbose_name='Заголовок') slug = models.SlugField(max_length=100, unique=True, db_index=True, verbose_name='URL') content = models.TextField(blank=True, verbose_name='Текст Статьи') photo = models.ImageField(upload_to="photos/%Y/%m/%d", verbose_name='Фото') time_create = models.DateTimeField(auto_now_add=True, verbose_name='Время публикаци') time_update = models.DateTimeField(auto_now=True, verbose_name='Время изменения') is_published = models.BooleanField(default=True, verbose_name='Видимость на сайте') cat = models.ForeignKey('Category', on_delete=models.PROTECT, verbose_name='Категория') def __str__(self): return self.title def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) class Meta: verbose_name = 'Известного мужчину' verbose_name_plural = 'Известные мужчины' ordering = ['title'] class Category(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name='Название каатегории') slug = models.SlugField(max_length=100, unique=True, db_index=True, verbose_name='URL') def __str__(self): return self.name def get_absolute_url(self): return reverse('category', kwargs={'cat_slug': self.slug}) class Meta: verbose_name = 'Категорию' verbose_name_plural = 'Категории' -
Saleor git clone issue
Would appreciate some help with this issue: I tried to git clone https://github.com/mirumee/saleor.git. and failed to clone the repository -
Server error on django app hosted using GCP
I got 500 Server Error on my app, which I just hosted using google cloud https://exam-3d397.el.r.appspot.com/ I am not sure how my app.yaml should look like - runtime: python39 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto # This sample incurs costs to run on the App Engine flexible environment. # The settings below are to reduce costs during testing and are not appropriate # for production use. For more information, see: # https://cloud.google.com/appengine/docs/flexible/python/configuring-your-app-with-app-yaml manual_scaling: instances: 1 resources: cpu: 2 memory_gb: 4 disk_size_gb: 10 I added this to my settings.py - ALLOWED_HOSTS = ['.herokuapp.com', '127.0.0.1', '.r.appspot.com'] There were no errors on deploying. and I have earlier deployed on heroku My file structure looks like structure I am a beginner to hosting with google cloud, any help is appreciated. -
How to use the serializer field values inside the serializer
In Django, I have a serializer.Here I need to use the pub_id inside get_book_name.How can I do that? class ABC(serializers.ModelSerializer): pub_id = serializers.ReadOnlyField(source='publication.id', read_only=True) book_name = SerializerMethodField() def get_book_name(self): # here I need to use the pub_id # How can I use it? class Meta: model = xxx fields = ('pub_id', 'book_name') I am a quite newbie in django and can anyone suggest where I can learn the full functionalities of Django as a beginner.Documentation is bit hard Any Answers would be helpful. Thank you -
How can I test unmanaged database in Django?
I'm working on a Django API that connects to an external database using unmanaged models. I want to create some objects in this database in my unit tests so I can test a few endpoints, but I cannot because this database is entirely unmanaged, there are no migrations at all for it. I have tried using the schema_editor to create the tables but it doesn't work because the schema doesn't exist. I have tried to run raw SQL to create the schema but it doesn't work. I have tried so many variations of so many different things that I honestly don't know which ones are worth describing here in detail. In my current setup I have a custom test runner that looks somewhat like this: from django.db import connections from django.test.runner import DiscoverRunner class TestRunner(DiscoverRunner): def setup_test_environment(self, *args, **kwargs): super().setup_test_environment(*args, **kwargs) with connections["unmanaged_db"].cursor() as cursor: cursor.execute( """ CREATE SCHEMA IF NOT EXISTS myschema; CREATE TABLE IF NOT EXISTS myschema.mytable ( ... ); """ ) def teardown_test_environment(self, *args, **kwargs): super().teardown_test_environment(*args, **kwargs) Note that when I don't include "IF NOT EXISTS" in my raw SQL, I get errors because the schema and relation "already exist". Yet, when I run my tests and … -
How to change booleanfields using bootstrap switches?
I want to use the switch button on the bootstrap to operate the model called field, but I don't know how to access it. class NewBlank(models.Model): ... blank_on_off = models.BooleanField(default=False) ... If I have the following booleanfield and can I change the booleanfield by cycling the switch as shown in the picture? -
Heroku Django websocket connection Failed
Heroku / Django / Channels Expert help needed. I am running a web app that uses websockets. Works great locally but fails on Heroku I am using ACM (Automated Cert Management) for SSL, it came with my dyno. Now the web console log says "websocket connection failed and log is saying ssl.SSLCertVerificationError so i tried to deal with it by adding following in my remote settings file: ssl_context = ssl.SSLContext() ssl_context.check_hostname = True CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ({ 'address': 'rediss://some url', # 'ssl': ssl_context # }) } } } any ideas how i can run my code without the websocket failing -
Django test not returning proper status code
I was writing some tests for the authentication of my website to check to see if a user already exists a particular username or not. In my main code, it is supposed to return a status code of 409 and I tried to use that status code to assert the status code that I get from my response from the tests but the tests always give me a status code 200. In short, I can't get the response to have a status code of anything other than 200 while running tests, however when I try using it from the manage.py shell it works as expected. Here's the view: views.py def sign_up(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] password = request.POST["password"] if User.objects.filter(username=username).count() != 0: messages.add_message(request, messages.ERROR, "An account already exists with that username") return render(request, "authentication/sign_up.html", status=409) else: user = User.objects.create( username=username, email=email, password=password) user.save() return render(request, "authentication/sign_up.html") Here's the test file. class SignUpTests(TestCase): def test_account_with_username_already_exists(self): response = self.client.post(reverse("authentication:sign_up"), { "username": "yasa.zaheen", "email": "yasazaheen728@gmail.com", "password": "12345678" }) self.assertEqual(response.status_code, 409) Here is the assertion error: D:\Aurora\aurora>manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .F ====================================================================== FAIL: test_account_with_username_already_exists (authentication.tests.SignUpTests) ---------------------------------------------------------------------- Traceback … -
In the paypal SDK code, can you customize YOUR_CLIENT_ID with two client IDs?
In such a way that payment is made to two paypal accounts rather than one, for example a buyer on click to pay the vendor, like you can make 80% payment to go to vendor and 20% payment go to the web store owner. Please help! and Oooh is there a better way to do the above kindly share! Thanks -
Suggestions or best practices to integrate the variation along with product table
I have created a Model “product” (in Django) now i want to extend this with variations like Size, Color etc. Need some suggestions and best practices for how it can be achieved. -
How to look for each column into another table column in Django/Django Rest Framework?
I have two tables, User: -name -description InterestingUser: -keywords I wish to check if any User's name is in InteretingUser keywords column, so when I do User.objects.all(), I also want to see if it is a interesting user, it is an interesting user if the username appears in InterestingUser table inside keywords column, also, keywords column is list of keywords separated by comma, so how do I figure out if it is a interesting user? -
How to render Buy now view in django?
I am building an e-commerce website. I have checkout feature which will allow a user to buy products. I have done that for cart means, when user will add products in cart only then he will be able to purchase products. But i wanna add a feature that will allow a user to buy a single product from the product_detail page, so without adding the product to cart he will be able to purchase. So the issue is, i wanna do single product stuff in my checkout page. but there are products which coming from cart. How can i add these two features in a single template ? This is views.py file: def checkout(request): user = request.user address = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) amount = 0 shipping_amount = 70 cart_product = [p for p in Cart.objects.all() if p.user == user] if cart_product: for p in cart_product: temp_amount = (p.quantity * p.product.discounted_price) amount += int(temp_amount) total_amount = amount + shipping_amount return render(request, 'app/checkout.html', {'address':address, 'cart_items':cart_items, 'total_amount':total_amount, 'amount':amount}) This is checkout Temaplate: {% extends 'app/base.html' %} {% load static %} {% block title %}Checkout{% endblock title %} {% block main-content %}z {% load humanize %} <div class="container"> <div class="row mt-5"> <div class="col-sm-6"> …