Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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!! -
I'm unable to save data to db in Django
Views.py I was trying to save this data that I'm getting from form but I'm unable to save it..it is going for the exception. I think the error is in the following line q = Query(sender=s, subject=subject, message=message, receiver=receiver) class SendQuery(View): def get(self, request): user=request.user if user.is_authenticated: try: s = Student.objects.get(user=user) ###Common code for students op = Staff.objects.filter(stype="1") return render(request,'students/send_query.html',{'s':s,'op':op}) ###Common code for students except: return redirect('home') return redirect('logout') def post(self, request): user=request.user if user.is_authenticated: try: s = Student.objects.get(user=user) ###Common code for students receiver = request.POST.get('receiver') subject = request.POST.get('subject') message = request.POST.get('message') print(receiver,subject,message) if receiver != "None": print("Hello") q = Query(sender=s, subject=subject, message=message, receiver=receiver) q.save() # if t: msg="Query raised successfully" return render(request,'students/msg.html',{'msg':msg}) else: msg="Failed to raise issue. Try again and mention all fields." return render(request,'students/msg.html',{'msg':msg}) ###Common code for students except: return redirect('home') return redirect('logout') -
How to implimanet backend of a Quiz Webiste?
I am planning to make a Quiz app using Django as a backend. Users would be able to make their own quizzes (mostly MCQ questions) and I needed help in figuring out the backend for it. So far my plan was to Have Users, Quiz, and Questions table. And use foreign Keys to connect Users to Their Quizzes and Quizzes to the Question. But this would result in way too many rows in the question table as Number of quizzes increases. Currently, I plan to use Django to make tables. I wanted to know if there is a way to probably make Tables dynamically or some other way to store quizzes data like JASON or some other way? If yes how would I be able to do so using django. I am open to any other suggestions. (not sure if required but I plan to use React for frontend) -
Why am I unable to migrate when other files use my models in Heroku?
For context, I have an application that works perfectly fine locally, after some fiddling with the database. It uses a react frontend, with a django backend for internal api calls. However, on a new, fresh download, with a new, fresh database, I always get an error saying relation "claims" does not exist, where Claims is the name of a table in my database, in the form of a model. I have been able to bypass this error by commenting out all code that uses the model, then slowly migrating every single table, one at a time, then uncommenting out the code that uses the model. This is incredibly tedious, but it works in a local environment. However, as I attempt to push this into production, I am using Heroku, and I am unable to make multiple commits in the same way, as it seems the database gets reset everytime there is a new update. Am I missing something? I feel as though there must be something I am doing incorrectly here, but I have not been able to find anything other than posts saying to reset all my migrations, and redoing the makemigrations command. This method hasn't worked for me … -
Django 3.2.5 é possível ter um app dentro de outro app?
exemplo: tenho um app chamado aplicativo1 na raiz do projeto, mas quero criar o app chamado aplicativo2 dentro do aplicativo1. mas quando faço isso eu não consigo registrar ele no settings e nem chamar as views do aplicativo2 dentro do arquivo urls.py do aplicativo1. como posso fazer isso ? -
How to confirm popup in django test?
I have been writing django tests for a django project, and I encountered a problem. I don't know how to confirm a popup in django test like below in code. [![enter image description here][1]][1] # in tests.py class Tests(TestCase): def test_delete_admin(self): self.client.login(username=self.admin.username, password=self.admin_password) id = self.admin.id path = reverse("accounts:user_delete", args=[id]) response = self.client.post(path) self.assertEqual(200, response.status_code) After I ran this code, I got 302 status code. like this↓ FAIL: test_delete_admin (PBSystem.tests.PBSystemTests) delete admin ---------------------------------------------------------------------- Traceback (most recent call last): File "/src/project/app/tests.py", line 321, in test_delete_admin self.assertEqual(200, response.status_code) AssertionError: 200 != 302 Thank you in advance. -
django live videos and real time chat with node js integration
I plan to build a web application that supports live, video, and real-time chatting Since I've never done anything like this before, I had to understand it well But with studying the topic, the situation became very complicated about what technique to use. I usually work with Django and React But with the research, people say this is very difficult. It is necessary to use Node I went to search for the integration of Node with Django and here I found a greater complexity. People say that you must use redis Pub/sub or that you work with the same database in both sides. Now I'm so distracted I don't see any document on what I want to reach The main question is: how can I integrate Node with Django to implement these functions You can help even with an untested idea or article, literally anything Thanks in advance -
Writing a Django Form while keeping HTML styling
I have a Django form that I have created manually in order to keep the format of the styling, but I realized that the form is compromised of several inputs and manually is taking too long to change each. I am also able to generate the form automatically using {{ form.as_p }} but I lose the HTML style format that I have below. Is there an easy way to make it instead of manually changing each input? This is the original HTML template that I am trying to keep </button> <div class="form-outline mb-4"> <input type="text" id="businessName" class="form-control" name="businessName" /> <label class="form-label" for="typeText" >Legal Business Name</label> </div> Here is the working Django form: {% if submitted %} Your forms has been submitted {% else %} <form method="post"> {% csrf_token %} {{ form.as_p }} <!-- Submit button --> <button type="submit" class="btn btn-primary btn-block mb-4" id="btn" > Submit </button> </form> Here is the views.py def add_form(request): submitted=False if request.method == 'POST': form = infoForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/?submitted=True') else: form = infoForm() if 'submitted' in request.GET: submitted=True return render(request, 'template/template.html',{'form':form, 'submitted':submitted}) Here is the form class infoForm(ModelForm): class Meta: model = Info fields = ['businessName'] Here is what I have tried: <div … -
Django running in kubernetes does not load jquery files
I have a django application which I am running using docker container inside kubernetes cluster. When I load it using docker, I can see the proper UI however when I try to load using kubernetes and port-forwarding to local, I see UI like this. I did further investigation and found that inside docker jquery.js file exists however when I run it through k8s only jquery.min exists but no jquery.js Please advise what could be the reason.