Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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"> … -
How to test Django Querysets are equal using pytest-django
What's the best / most readable way to assert two querysets are equal? I come up with a few solutions: # option 1 assert sorted(qs1.values_list("pk", flat=True)) == sorted(qs2.values_list("pk", flat=True)) # option 2 (need to assert length first because set might remove duplicates) assert len(qs1) == len(qs2) assert set(qs1) == set(qs2) I know Django has a method django.test.TransactionTestCase.assertQuerysetEqual. Does pytest-django have something similar? I don't see it in the documentation. -
Axios patch method not working on Reactjs with DRF Api
It does not work when I use Axios for the patch and gives a forbidden error. this is my Model: class Teacher(models.Model): name=models.CharField(max_length=100) family=models.CharField(max_length=100) this is my serializer: class TeacherSerail(serializers.ModelSerializer): class Meta: model=Teacher fields='__all__' this is my view: class TeacherView(ModelViewSet): queryset=Teacher.objects.all() serializer_class=TeacherSerail and I use Routers for this view in urls: router=routers.DefaultRouter() router.register('tcr',TeacherView) urlpatterns=[ path('',include(router.urls)), .... and in ReactJs I use this code in button click event: update=()=>{ const api= axios.create({ baseURL:'http://127.0.0.1:8000/' }); api.patch('/tcr/1/',{ name:'ammar',family:'salahi' }).then(res=>{ console.log(res.data); }).catch(err=>{ console.log(err) }); } and that show Forbidden: /tcr/1/ in python terminal!!! all packages and libraries import correctly and get and post method in axios working fine but patch not working in Axios and fetch!!! how can solve this problem?! please help me. -
'NoneType' object has no attribute 'keys' in my cart.html in django
i crated add to cart funtionality for my website what problem i am facing right now is when a user logged in add something to cart and then got to the section od add to cart it load the page and show added items but when a user logged out and again signed in to the site and directly go add to cart page whitout adding any item it shows the above mentioned error i guess that every time it logged session got clear but i don't want it to happen any idea what causing the problem? my views.py for cart class Cart(View): def get (self, request): ids = (list(request.session.get('cart').keys())) sections = Section.get_sections_by_id(ids) print(sections) return render(request, 'cart.html', {'sections': sections}) -
Stripe Webhook does not work when I changed it to my domain and https
I'm trying to configure Django App with Stripe. Webhook works well When setting the Endpoint URL using "IP address" and "http". Here is the Endpoint URL. http://3.129.xx.xxx/subscriptions/webhook/ But when I changed it to my domain and add "https", It does not work. Here is the Endpoint URL with my domain. https://mysite12345.com/subscriptions/webhook/ 1.HTTP statas code is "time out". 2.Event type is "checkout.session.completed" 3.The log is "200 OK" but "Webhook event" is failed, it retries again and again but still failed. 4.Of course, the domain is valid(I can access other pages) I wonder why IP address and "http" Endpoint URL works well but a domain name and "https" do not. When I changed "http" to "https" do I need to adjust something or am I missing something? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Unable to delete/edit record from pk
I've got a list of properties in a view and template. On the template I have an edit button and a delete button. Neither are working yet the same code from different projects work just fine. They don't throw any debug error, on the explorer or at the log level. It accepts the click/input, goes to the proper URL but remains on the "rei_properties" page. I am running Django 3.1.6 framework... view to see all records in "Property" model: def rei_properties(request): props = Property.objects.all() return render(request, 'rei/rei_properties.html', {'props': props}) template w/ edit/delete links: <table> <tr> <th>Address</th> <th>City</th> <th>State</th> <th>Zipcode</th> <th colspan=2>Actions</th> </tr> {% for prop in props %} <tr> <td>{{ prop.address }}</a></td> <td>{{ prop.city }}</a></td> <td>{{ prop.state }}</a></td> <td>{{ prop.zipcode }}</a></td> <td> <a href="{% url 'rei_properties' %}edit/{{ prop.pk }}/">Edit</a> </td> <td> <a href="{% url 'rei_properties' %}del/{{ prop.pk }}/" onclick="return confirm('Are you sure you want to delete this?')">Delete</a> </td> </tr> {% endfor %} </table> My urls: url(r'^rei_properties/', views.rei_properties, name='rei_properties'), url(r'^rei_properties/edit/(?P<pk>[0-9]{1,10})/$', views.rei_properties_edit, name='rei_properties_edit'), url(r'^rei_properties/del/(?P<pk>[0-9]{1,10})/$', views.rei_properties_del, name='rei_properties_del'), and finally my delete and edit views: def rei_properties_edit(request, pk): prop = get_object_or_404(Property, pk=pk) if request.method == 'POST': form = PropertyForm(request.POST, instance=prop) if form.is_valid(): prop = form.save(commit=False) prop.save() return redirect('rei_properties') else: form = PropertyForm(instance=prop) return render(request, … -
How to filter based on referencing values? django
My model class MyColumn(models.Modle): name = charfield..... max = intigerfield.... min = intigerfield.... Class MyCell(models.Modle): Value = intigerfield..... Column = Forgenkey (NyColumn) My gial is to get values that greater or equal the max or lesss than or equal the min. But, how to refrence the max or min value from inside MyCell.bojects.filter MyCell.bojects.filter( value__gte=value__MyColumn__max) -
Django static files not serving in Nginx
My first website with Django on hobby production. I'am follow the setting guide this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04#checking-for-the-gunicorn-socket-file my setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') and my nginx config server { listen 80; server_name MYIP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/azhimeblog/needhobby; } location /media/ { root /home/azhimeblog/needhobby; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } This result -
I have question about Django REST Filter ID ForeignKey
How Can filter Org.id in Department simple: { id: 1, name: ITDepart, description: itdeapart, org: 43} {id:2, name: ITDepart, description: itdeapart, org: 42} I have the following models.py: Organization model: class Organization(models.Model): user = models.ForeignKey(User,, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, blank=True) description = models.TextField(max_length=500, blank=True) created_date = models.DateTimeField(auto_now_add=True, null=True) logo = models.ImageField(upload_to=upload_update_image, blank=True, null=True) slug = models.SlugField(blank=True) Department model: class Department(models.Model): org = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True , blank=True) name = models.CharField(max_length=50) description = models.TextField(max_length=300) slug = models.SlugField(max_length=100, null=True, blank=True) I have Serializaer: class OrgSerializer(serializers.ModelSerializer): logo = Base64ImageField(max_length=None, use_url=True) class Meta: model = Organization fields = [ 'id', 'name', 'description','slug', 'user', 'created_date', 'logo'] class DepartmentSerailizer(serializers.ModelSerializer): class Meta: model = Department fields = ['id', 'name', 'description', 'slug' , 'org'] I Have Viewset: class OrgViewset(viewsets.ModelViewSet): authentication_classes = ( TokenAuthentication, ) permission_classes = (IsAuthenticated, ) queryset = Organization.objects.all() serializer_class = OrgSerializer class DepartmentViewset(viewsets.ModelViewSet): authentication_classes = ( TokenAuthentication, ) permission_classes = (IsAuthenticated,) queryset = Department.objects.all() serializer_class = DepartmentSerailizer lookup_field = 'pk' -
My Django test is failing due to csrf_token value?
I Think the two csrf value is not same that is why my test case is failing. How do i test the template is working good? FAIL: test_home_page_can_save_a_POST_request (lists.tests.HomePageTest) Traceback (most recent call last): File "G:\dj_proj\ObeyTheTestingGoat\superlists\lists\tests.py", line 46, in te st_home_page_can_save_a_POST_request self.assertEqual(response.content.decode(), expect_html) AssertionError: '<!DO[178 chars]lue="mksJcHsmmhRKsu96jGJaqz7sh593cCLcG8AEkK5CC[2 13 chars]tml>' != '<!DO[178 chars]lue="kGamofdgnvgVD2MfLaIZKrLQ99WOYjzlEuihwiQwD [213 chars]tml>' Ran 4 tests in 0.015s FAILED (failures=1) Destroying test database for alias 'default'... -
Django - How to exclude a value from a filter using a utility method
I have the following code (truncated): # Utility method to apply all the filters if they are not None or empty def filter_timesheet_if_not_None(qs, **kwargs): return qs.filter( **{key: value for key, value in kwargs.items() if value != None or value != ""} ).distinct().values("project_id", "minutes") ## TIMESHEET FILTERS if comp_time_query == "with_comp": user_timesheet_list = filter_timesheet_if_not_None( TimesheetEntry.objects.all(), timesheet__for_date__gte=start_string, timesheet__for_date__lte=end_string, project__is_visible=True, timesheet__user__is_active=True, created_by_id__exact=i['id'], sub_type2="Visuals", ) else: user_timesheet_list = filter_timesheet_if_not_None( TimesheetEntry.objects.all(), timesheet__for_date__gte=start_string, timesheet__for_date__lte=end_string, project__is_visible=True, timesheet__user__is_active=True, created_by_id__exact=i['id'], #pseudo-code of what I want: sub_type2 != "Visuals", ) How can I implement something like sub_type2 != "Visuals" following the Django standards? What I've done: I tried using Django Q objects for complex lookups, and it works, but I need to integrate everything within the filter_timesheet_if_not_None utility method but I don't know how to do it. -
Django - paginator table i need to show the most recent activity first
i have a table showing data from the database but i need it to show the most recent first Table if u see the picture there is in "monto" a 0.03 thats shown like the last one but it is the most recent in the database, i need the table to show the most recent activity first Views.py def index(request): monto = Transacciones.objects.filter(owner = request.user) paginator = Paginator(monto , 7) page_number = request.GET.get('pagina') page_obj= Paginator.get_page(paginator,page_number) context = { 'page_obj': page_obj , } return render(request, 'Admin/Index.cshtml',context) table html <div class=""> <div class=""> <table class="table h1color bgcolorwhite"> <thead> <tr> <th>FECHA</th> <th>MONTO</th> <th>TIPO</th> <th>MONTO COMPRADO BTC</th> <th>MONTO RETIRADO CLP</th> <th>ESTADO</th> </tr> </thead> <tbody> {% for a in page_obj %} <tr> <td style="">{{a.date}}</td> <td style="font-weight:bold;">{{a.amount}}</td> <td style="text-align:left">{{a.tipo_transaccion}}</td> <td style="font-weight:bold;">{{a.monto_comprado_btc}}</td> <td style="font-weight:bold;">{{a.monto_retirado_clp}}</td> <td style="">{{a.status}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> srry if my english was bad... Thanks a lot!!