Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I think my django view is making 16 forms instead of 15
Frist of all sorry for my bad english but i'm french ! So my problem is that i've written a django view to configure my CompactRIO from a web page. I have written a form to display things like baudrate and stop bit and i have created a formset to display multiple forms at once ( so i can configure multiple connections at once ). But when i run configure it, it stops right after the configuration of the last connection. So i am able to configure all 15 connections, the code runs fine, and then it stops working and i crashes. I think that maybe it comes from the fact that i create 16 forms instead of the 15 i want but the web page prints 15 forms so i dont know. Anyway thank you for taking the time to read my problem ! So this is my view : def config(request): if request.method == 'POST': ConfigFormSet = formset_factory(ConfigForm) formset = ConfigFormSet(request.POST) if formset.is_valid(): for form in formset: if form.is_valid(): entete = form.cleaned_data['Entete'] liaison = form.cleaned_data['Liaison'] baudrate = form.cleaned_data['Baudrate'] dataBit = form.cleaned_data['choixDataBit'] parityBit = form.cleaned_data['choixParityBit'] stopBit = form.cleaned_data['choixStopBit'] activate = form.cleaned_data['activate'] print(liaison) print(baudrate) print(dataBit) print(parityBit) print(stopBit) print(activate) # ------------------ … -
Dynamically filter queryset with AJAX and Django Rest Framework
models.py from django.db import models from django.utils import timezone import datetime from django.core.validators import RegexValidator, MinLengthValidator from .validator import validate_gearshift class Coche(models.Model): matricula = models.CharField(max_length=7,primary_key=True,validators=[RegexValidator(regex='^[1-9]{4}[A-Z]{3}$',message="La matr> concesionario = models.ForeignKey('Concesionario', on_delete=models.CASCADE) brand = models.ForeignKey('CocheBrand', on_delete=models.CASCADE) model_name= models.ForeignKey('CocheModel', on_delete=models.CASCADE) type_car = models.ForeignKey('CocheType', on_delete=models.CASCADE) location = models.ForeignKey('Localidad', on_delete=models.CASCADE) warranty = models.ForeignKey('CocheWarranty', on_delete=models.CASCADE) doors = models.ForeignKey('CocheDoors', on_delete=models.CASCADE) gearshift = models.ForeignKey('CocheGearshift', on_delete=models.CASCADE) precio = models.DecimalField(verbose_name="Precio",max_digits=10, decimal_places=5, validators=[RegexValidator(regex='^[1-9][0-9]> rebaja = models.DecimalField(verbose_name="Rebaja",max_digits=10, decimal_places=5, validators=[RegexValidator(regex='^[0-9]$|^[1> precio_final = models.DecimalField(verbose_name="Precio Final",max_digits=10, decimal_places=5, null=True, blank=True) #se calcul> kilometres = models.IntegerField(verbose_name="Kilometros", validators=[RegexValidator(regex='^[0-9]$|^[0-9][0-9]$|^[0-9][0-9][0-> years = models.IntegerField(verbose_name="Años", validators=[RegexValidator(regex='^[0-9]$|^[12][0-9]$|^(30)$',message="La antigu> horsepower = models.IntegerField(verbose_name="Caballos", validators=[RegexValidator(regex='^[6789][0-9]$|^[12][0-9][0-9]$|^(300)> description = models.CharField(verbose_name="Descripcion", max_length=512) reserved = models.BooleanField(verbose_name="Reservado") sold = models.BooleanField(verbose_name="Vendido") create_at = models.DateTimeField(auto_now_add=True,verbose_name="Fecha Creacion") def __str__(self): return self.matricula def FormatoFecha(self): return self.fecha.strftime('%d - %b -%y') views.py from .models import Coche, CocheGearshift, CocheDoors, CocheWarranty, Localidad, CocheType, CocheModel, CocheBrand, Concesionario, Co>from django.views.generic import ListView from django.shortcuts import render from .forms import IndexSearch from django.http import JsonResponse from rest_framework.generics import ListAPIView from .serializers import CocheSerializers from .pagination import StandardResultsSetPagination def CocheList(request): return render(request,'wallacar_app/prueba.html', {}) class CochesListing(ListAPIView): pagination_class = StandardResultsSetPagination serializer_class = CocheSerializers def get_queryset(self): queryList = Coche.objects.all() brand = self.request.query_params.get('brand',None) model_name = self.request.query_params.get('model_name',None) type_car = self.request.query_params.get('type_car',None) location = self.request.query_params.get('location',None) doors = self.request.query_params.get('doors',None) gearshift = self.request.query_params.get('gearshift',None) sort_by = self.request.query_params.get('sort_by',None) horsepower = self.request.query_params.get('horsepower',None) if brand: queryList … -
Django Flashing/Flickering on each Render on CRUD function and also Displaying data from API URL
I'm working on a Django REST Framework task. Every time I perform a Create, Retrieve, Update, and Delete function the list item item of div is flashing every time. How can I stop this flashing/flickering. From API URL I have to display the paginated data. If I click the next page then also flickering is occurred. How can I get rid of this flickering/flashing issue. main.html {% extends 'todo/index.html' %} {% block content %} <div class="center-column" id="center-column"> <h5 class="card-title" id="welcome" data-id={{ request.user.id }}> Hello {{ request.user.username }}, Create your todo list </h5> <div id="addTodoForm"> <form action="" method=""> <div class="input-group-append"> <input type="text" class="title-input" required name="title" placeholder="e.g. Chemistry"> <button type="submit" class="form-control btn btn-primary mr-sm-2" id="addTodobtn"> Add Todo </button> </div> </form> </div> </div> <div class="row" id="row"> <div class="col-sm-5"> <div class="card"> <div class="card-body"> <h5 class="card-title"> Incomplete Todo Items </h5> <hr /> <div class="list-group" id="incompleteTodo"> </div> <hr> <nav aria-label="..." id="incompletePagination"> <ul class="pagination justify-content-center"> <li class="page-item"> <button class="page-link" tabindex="-1" id="prevPageI">&laquo</button> </li> <li class="page-item"><button class="page-link" id="currPageI">1</button></li> <li class="page-item"><button class="page-link" id="nextPageI">&raquo</button></li> </ul> </nav> </div> </div> </div> <div class="col-sm-5"> <div class="card"> <div class="card-body"> <h5 class="card-title"> Completed Todo Items </h5> <hr> <div class="list-group" id="completedTodo"> </div> <hr> <nav aria-label="..." id="completedPagination"> <ul class="pagination justify-content-center"> <li class="page-item"> <button class="page-link" tabindex="-1" id="prevPageC">&laquo</button> </li> <li … -
How I can flatten many to many relationship using djnago serializer
I am new to Django. While I am try to implement serializer for many to many relationship I got problem.I want to serialize a many to many field and need to create a dictionary based on the nested object. models.py class ClassRoom(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name serializers.py class Student(models.Model): name = models.CharField(max_length=50) class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE) teacher = models.ManyToManyField(Teacher) def __str__(self): return self.name class TeacherSerializer(serializers.Serializer): teacher_name = serializers.CharField(source="name", label="Teacher") class Meta: model = Teacher fields = ['name'] class StudentSerializer(serializers.Serializer): class_room = serializers.CharField(source="class_room.name") teacher = TeacherSerializer(many=True) student_name = serializers.CharField(source='name', label="Student") class Meta: model = Student fields = ['student_name', 'teacher', 'class_room'] views.py class HomeclassView(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer I got the response like this: { results: [ { "class_room": "Class 1", "teacher": [ { "teacher_name": "Maria" }, { "teacher_name": "sara" } ], "student_name": "John" } ] } But I am expecting the result in : { results: [ { "class_room": "Class 1", "teacher_name": "Maria", "student_name": "John" }, { "class_room": "Class 1", "teacher_name": "sara", "student_name": "John" }, ] } Please help me to achieve this. Thanks in advance -
Can't access Django's login page using Ingress. NodePort and LoadBalancer work fine
I have a django app which has been migrated to Kubernetes. Exposing the service with NodePort or LoadBalancer (AWS) works just fine, however when I'm using Ingress (nginx), it's not redirecting to the login page, and I always get an "authentication credentials were not provided" message. I had never used Ingress before, so maybe I'm missing something. apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - http: paths: - path: /app pathType: Exact backend: service: name: django port: number: {{ .Values.service.port }} the idea is that if I visit localhost/app/admin, it should go to localhost/app/login and back to localhost/app/admin. But such redirection is not done by Ingress. As I said, it's working with NodePort and LoadBalancer. For example, localhost:30000/admin will redirect to localhost:30000/admin/login and then upon signing in, the form will go back to localhost:30000/admin Any idea about what might be missing? -
Django filter().first() returning different result than get()
I can't figure out how to debug this. I have this Django model: from django.db import models from django.utils.translation import ugettext_lazy as _ # ... class AbstractPhrase(models.Model): term2_past_tense = models.TextField(_('term 2 past tense')) # ... other simple fields and methods class Meta: abstract = True class CommentPhrase(AbstractPhrase, models.Model): """A phrase that comprises part of a report card comment""" skill = models.ForeignKey(Skill, null=True, on_delete=models.SET_NULL) question = models.ForeignKey( Question, null=True, on_delete=models.SET_NULL, related_name='phrases') old_id = models.CharField( _('old ID'), max_length=10, blank=True, null=True) # ... Other simple fields class Meta: ordering = ('skill', 'question_number') verbose_name = _('comment phrase') verbose_name_plural = _('comment phrases') An administrator reported that the model couldn't be updated in the Django admin. After saving, the Django admin would report that the model updated successfully, but when they refreshed the page the data was still out of date. I opened up a Django shell and investigate: In [3]: cp = CommentPhrase.objects.get(pk=10280) In [4]: cp Out[4]: <CommentPhrase: lorem ipsum> In [5]: cp.term2_past_tense Out[5]: '' In [6]: cp.term2_past_tense = "Test" In [7]: cp.save() In [8]: cp.term2_past_tense Out[8]: 'Test' In [9]: cp.refresh_from_db() In [10]: cp.term2_past_tense Out[10]: '' I further tried doing a queryset update(), and this had the same result. It got weirder when I looked … -
Is it possible to choose between multiple tables from the database (POSTGRES) in the Dash Plotly drop down menu?
I have a database connected to my project. Now I would like to have a selection from the tables that are available in my database in my dropdown. So I want to be able to select my tables from the database in the drop-down menu. i am working with django plotly dash. if you nedd my code i can upload it also. thanks -
Access local dockerized django project via ip without port
I got a small django project wich runs within a docker container and it is locally only (no need to expose it to the whole internet, just my office), but since it's a coporate project I want to give the persons who use it the possibility to access it via the ip address of host machine instead ip address:port (wich in my opinion is less readable). Being honest, I have no experience configuring nginx. This is my nginx config file (see it's a very simple configuration): client_max_body_size 10M; upstream web{ ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /src/static/; } location /media/ { autoindex on; alias /src/media/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } And my django image entry point: CMD ["sh", "-c", "python manage.py collectstatic --no-input; python manage.py migrate; gunicorn project.wsgi -b 0.0.0.0:8000"] Both containers expose to same port. -
ModelForm instance doesn't store primary key
Upon trying to save a Model instance as a result of saving a ModelForm, I'm getting the following error: ValueError: "<Question: NameError: 'x' is not defined>" needs to have a value for field "id" before this many-to-many relationship can be used. The question instance is being created to an extent, yet the primary key is not being generated. What needs to be fixed in order for the primary key to be attached so it can be stored in the database? class PostQuestionPage(QuestionPage): template_name="questions/create_question.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['question_form'] = QuestionForm(self.request.POST or None) con return context def get(self, request): context = self.get_context_data() return self.render_to_response(context) def post(self, request): context = self.get_context_data() form = context['question_form'] import pdb; pdb.set_trace() if form.is_valid(): question = form.save(commit=False) question.user_account = request.user.account question.save() form.save_m2m() return HttpResponseRedirect( reverse("questions:question", kwargs={'id': question.id}) ) return self.render_to_response(context) class Question(models.Model): title = models.CharField(max_length=50) body = models.TextField() dated = models.DateField(default=date.today) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() status = QuestionStatusQuerySet.as_manager() class Meta: ordering = ['-dated'] default_manager_name = "objects" def __str__(self): return self.title class TestPostQuestionPageAdded(TestCase): '''Verify that a User has succesfully added a question''' @classmethod def setUpTestData(cls): cls.user … -
Django: How to use data from a function as a field in Meta class
I've created a function in my serializers.py that call an external API and give me a dict back. How can I use the output from return downloads in the get_all_files as a field in class Meta? With my solution I've got the following error: Field name get_all_files.downloads is not valid for model Application. serializers.py class OsdSerializer(serializers.ModelSerializer): bands = BandSerializer(source='indice_to_use.needed_bands', many=True) satellite = SatelliteSerializer(source='indice_to_use.satellite_to_use') indice = IndiceSerializer(source='indice_to_use') # configuration url = 'https://earth-search.aws.element84.com/v0' # URL to Sentinel 2 AWS catalog collection = 'sentinel-s2-l2a-cogs' # search parameter startDate = '2021-04-10' endDate = '2021-04-12' location = [ 13.6677, 43.7232, 16.2605, 45.4522 ] def get_all_files(*bandss): bbox_search = Search( bbox=location, datetime=startDate+"/"+endDate, query={'eo:cloud_cover': {'lt': 50}}, collections=[collection], url=url, sort={'field': 'eo:cloud_cover', 'direction': 'desc'}, ) items = bbox_search.items() downloads = {} for i, item in enumerate(items): data = {} data['Product ID']= item.properties["sentinel:product_id"] data['Preview']= item.asset("thumbnail")["href"] data['Date']= item.properties["datetime"] data['Cloud cover']= item.properties["eo:cloud_cover"] for band in bandss: data[band] = item.asset(band)["href"] downloads[i] = data return downloads class Meta: model = Application fields = ['machine_name', 'name', 'description', 'indice', 'satellite', 'bands', 'get_all_files.downloads', ] -
How to join 2 routers in DRF. Not extend, join
I need to join 2 routers like that I got router that generates /course/<course_id> i got router that generates /lesson/<lesson_id> i need to combine this two urls to /course/<course_id>/lesson/<lesson_id> this is what i tried router = routers.SimpleRouter() router.register(r'courses', CourseViewSet) lesson_router = routers.SimpleRouter() lesson_router.register('courses/<int:id>/lessons', LessonViewSet) it does't work correctly. It works but only if the url is /courses/<int:id>/lesson/1 where <int:id> is string not mock -
Reverse for 'like' not found. 'like' is not a valid view function or pattern name
I'm trying to create a like button using ajax in my project. But it gives error : Reverse for 'like' not found. 'like' is not a valid view function or pattern name. Here's my code. View.py def like(request): blog = get_object_or_404(Blogs, sno = request.POST.get('blog_id')) is_liked = False if blog.likes.filter(username = request.user).exists(): blog.likes.remove(request.user) is_liked = False else: blog.likes.add(request.user) is_liked = True context = { 'is_liked' : is_liked, 'blog' : blog, 'total_like': blog.total_like(), } if request.is_ajax(): html = render_to_string('like_section.html',context,request=request) return JsonResponse({'form':html}) urls.py urlpatterns = [ path('',views.blogs, name='blogs'), path('blog/<int:id>/<str:slug>',views.showblog, name='showblog'), path('writeblog/',views.writeblog, name='writeblog'), path('publish',views.publishBlog, name='publishblog'), path('like',views.like, name='like'),] template <p> Likes : {{total_likes}} Like{{total_likes| pluralize}} </p> {% if is_liked %} <button type="button" class="btn" id="like" name="blog_id" value="{{blog.sno}}"><i class="fa fa-thumbs-up">Dislike </i></button> {% else %} <button type="button" class="btn" id="like" name="blog_id" value="{{blog.sno}}"><i class="fa fa-thumbs-up"> Like </i></button> {% endif %} <script> $(document).ready(function (event) { $('#like').click(function(){ var pk = $(this).attr('value'); const path = '{% url "like" %}'; $.ajax({ type: "POST", url: path, data : {'id':pk, 'csrfmiddlewaretoken':'{{ csrf_token }}'}, dataType:'json', success:function(event){ $('#like-section').html(resopnse['form']); console.log($('#like-section').html(resopnse['form'])); } }); }); }); </script> -
Nginx passes the websocket request to Gunicorn instead of Daphne
I am setting up a production server with nginx and Gunicorn+Daphne. Everything is working well except the ws proxy_pass. I followed this two tutorials. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04 https://github.com/mitchtabian/HOWTO-django-channels-daphne etc/nginx/sites-aviable/multichats.conf server { listen 80; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/vagrant/multichat; } location /ws/ { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } For some reason the websocket request is passed to Gunicorn instaed of Daphne: Apr 26 01:55:08 multichats gunicorn[16099]: Not Found: /chat/stream/ Apr 26 01:55:08 multichats gunicorn[16099]: - - [25/Apr/2021:23:55:08 +0000] "GET /chat/stream/ HTTP/1.0" 404 2307 "-" "Mozilla/5.0 (Windows NT 10.0; nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip … -
Lock web page in Django admin if another user in that page
I'm new to Django. I'm looking for a way to lock a custom template in the Django admin for accessing more than 1 user at a time. Is there a way to do it with Sessions? Or do it with javascript? Thanks in advance! -
How To Migrate IntegerField To ForeignKey
I have a legacy database I am migrating towards Django. I have model like this: class MyModel(models.Model): other_id = models.IntegerField() This is an existing table filled with valid data. I want to migrate to class MyModel(models.Model): newbie = models.ForeignKey( OtherModel, on_delete=models.CASCADE, db_constraint=False, db_column="other_id", ) However, the generated migration keeps insisting on adding the already existing field and than dropping it: python manage.py sqlmigrate app 0069 BEGIN; -- -- Add field -- ALTER TABLE `mymodel` ADD COLUMN `other_id` integer DEFAULT 1 NOT NULL; ALTER TABLE `mymodel` ALTER COLUMN `other_id` DROP DEFAULT; -- -- Remove field -- ALTER TABLE `mymodel` DROP COLUMN `other_id`; Is there a way to convince Django to treat the field as ForeignKey without this exercise? I'd like to avoid a need to --fake the migration. -
Strange issue when calling same piece of code in multiple places in one template
I am facing a strange issue. I have two method in a model. get_delivery_taxes and get_subtotal_taxes as shown below: def get_delivery_taxes(self): delivery_tax_list = [] if self.modifiers: if self.modifiers.get('Taxation', None): for tax in self.modifiers.get('Taxation'): if tax.get('delivery_tax', None): delivery_tax_dict = tax.get('delivery_tax') delivery_tax_amount = delivery_tax_dict['amount'] delivery_tax_dict['amount'] = Money(delivery_tax_amount, settings.DEFAULT_CURRENCY) delivery_tax_list.append(delivery_tax_dict) return delivery_tax_list def get_subtotal_taxes(self): subtotal_tax_list = [] if self.modifiers: if self.modifiers.get('Taxation', None): for tax in self.modifiers.get('Taxation'): subtotal_tax_dict = None if tax.get('subtotal_tax', None): subtotal_tax_dict = tax.get('subtotal_tax') subtotal_tax_amount = subtotal_tax_dict['amount'] subtotal_tax_dict['amount'] = Money(subtotal_tax_amount, settings.DEFAULT_CURRENCY) subtotal_tax_list.append(subtotal_tax_dict) return subtotal_tax_list Those two methods are then used by these below methods to calculate their totals. def get_subtotal_tax_price(self): subtotal_tax_price = 0 for sub_tax_price in self.get_subtotal_taxes(): subtotal_tax_price = subtotal_tax_price + sub_tax_price['amount'] return subtotal_tax_price def get_delivery_tax_price(self): delvry_tax_amount = 0 for del_tax_price in self.get_delivery_taxes(): delvry_tax_amount = delvry_tax_amount + del_tax_price['amount'] return delvry_tax_amount A final total is calculated using above two methods as below. def get_order_final_total(self): subtotal = self.get_order_subtotal_price() subtotal_taxes = self.get_subtotal_tax_price() devilery_charges = self.get_order_delivery_charges_price() devilery_charges_taxes = self.get_delivery_tax_price() order_total = subtotal + subtotal_taxes + devilery_charges + devilery_charges_taxes return order_total In my template, I use them as below: {% for tax_dict in object.get_delivery_taxes %} ... {% endfor %} {% for tax_dict in object.get_subtotal_taxes %} ... {% endfor %} {{object.get_order_final_total}} Doing this was working fine until I … -
How to get file from django-import-export?
I want to use groupby() function from pandas, but dont know how to get file before export. I've tried dehydrate, but I dont think it's what i want. phone = Field() class Meta: model = Phones # exclude = ('id', ) def dehydrate_url(self,phone): -
Django: How do I get referenced objects in a symmetric ManyToMany relationship?
I've created a Many-to-Many relationship for the model UserProfile, to enable users to grant access to a particular feature to one another. The relationship works as expected with the use of symmetrical=False to ensure a user access is one-way. Model from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(blank=True, null=True) image = models.ImageField(upload_to='profile_image', default="default_thumbnail.jpg") department = models.ForeignKey(DepartmentModel, on_delete=models.SET_NULL, null=True) allow_booking_access = models.ManyToManyField("self", blank=True, symmetrical=False) def __str__(self): return self.user.username class UserInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'UserAccounts' class UserAccount(BaseUserAdmin): inlines = (UserInline,) I am able to query the users that a particular user wants to grant access to via: (for example id=1) UserProfile.objects.get(id=1).allow_booking_access.all() However, I would like to retrieve the users that have granted access to the particular user. How would I do this? -
Why is selenium not finding an element on a website
I have the following test that I want to run. A payment request is being made from my application. For the user to complete the payment they have to visit a link on a website that processes payments. I want selenium to enter the email address which is required to complete the payment. I am getting the following error. E ====================================================================== ERROR: test_submit_payment (order.tests.test_views.TestViewsLiveServer) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/patrice/django-apps/dropby/dropby/order/tests/test_views.py", line 222, in test_submit_payment username = self.selenium.find_element_by_id('username') File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element 'value': value})['value'] File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="username"] Below is my code for the test. def test_submit_payment(self): # get the url to goto the payment view submission view url = self.live_server_url + reverse('order:payment', kwargs={'pk': self.order.pk}) self.selenium.get(url) # self.selenium.find_element_by_xpath("//select[@name='method_of_payment']/option[text()='ecocash']").click() phone_number_input = self.selenium.find_element_by_name('phone_number') phone_number_input.send_keys('0777777777') # Submit the form submit_button = self.selenium.find_element_by_id("submit-payment") submit_button.click() # Now find the url that goes to the paynow website to complete a payment complete_payment_url = self.selenium.find_element_by_id('complete-payment-url') complete_payment_url.click() # Now we are on the paynow website, enter in the email address of the user who is going … -
Why is Django API Get working but Post not working?
I'm using Django to develop an API, the GET method works but the post method gives "Failed to Add." error. Following is the model, class Video(models.Model): VideoId = models.AutoField(primary_key=True) VideoName = models.CharField(max_length=100) FPS = models.CharField(max_length=100) TotalFrame = models.CharField(max_length=100) Duration = models.CharField(max_length=100) The API, @csrf_exempt def videoApi(request, id=0): if request.method == 'GET': video = Video.objects.all() video_serializer = VideoSerializer(video, many=True) return JsonResponse(video_serializer.data, safe=False) elif request.method == 'POST': video_data = JSONParser().parse(request) video_serializer = VideoSerializer(data=video_data) if video_serializer.is_valid(): video_serializer.save() return JsonResponse("Added Successfully!!", safe=False) return JsonResponse("Failed to Add.", safe=False) elif request.method == 'PUT': video_data = JSONParser().parse(request) video = Video.objects.get(VideoId=video_data['VideoId']) video_serializer = VideoSerializer(video, data=video_data) if video_serializer.is_valid(): video_serializer.save() return JsonResponse("Updated Successfully!!", safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method == 'DELETE': video = Video.objects.get(VideoId=id) video.delete() return JsonResponse("Deleted Succeffully!!", safe=False) URLs url(r'^video/$',views.videoApi), url(r'^video/([0-9]+)$',views.videoApi), serializers , class VideoSerializer(serializers.ModelSerializer): class Meta: model = Video fields = '__all__' JSON Input [{"VideoId": 2, "VideoName": "lol", "FPS": "1", "TotalFrame": "1", "Duration": "1"}] output , "Failed to Add." -
NoReverseMatch at / Reverse for 'product_detail' with arguments '(1, 'sgm')' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)$']
I'm learning Django framework and I have in the extend templates part, Error during template rendering,i have received this error.When i add slug field we get template error NoReverseMatch at / Reverse for 'product_detail' with arguments '(1, 'sgm')' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)$'] from django.urls import path from shop import views app_name='shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('search', views.product_search, name='product_search'), path('<slug:category_slug>', views.product_list, name='product_list_by_category'), path('<slug:slug>', views.product_detail, name='product_detail'), ] {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>{% block title %}online shop{% endblock %}</title> <link rel="shortcut icon" type="image/png" href="{% static 'img/save.ico' %}"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'vendor/jquery/custom.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- Custom styles for this template --> <link href="{% static 'css/shop-homepage.css' %}" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-default navbar-fixed-top"> <div class="container"> <a href="/"> <img src="{% static "img/logo.png" %}" height="30px"></a> <button class="navbar-toggler" type="button" … -
Retrieve and Manipulate media files in Django
I am making a system, where I will let users upload excel files, and then I am saving the file to the 'media' folder. I am able to do it till this stage. Next, I want to be able to read the excel file, update its values/ add new columns/ add new rows, etc and then save the file and let the user download it. I am new to Django, and not able to do it. Can anyone help Here is the code, I used for uploading the file in the 'views.py' file def index(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] # print(uploaded_file.size) # print(uploaded_file.name) path = settings.MEDIA_ROOT print(path) # print(uploaded_file.content_type) fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'index.html', context) -
Modelserializer related to users model
i have a model serializer which will create a post, and this post should be related to the user posting it, why this dont work ? class PostSerializer(serializers.ModelSerializer): class Meta: model = Posts fields = ('title', 'image') def create(self, validated_data): request = self.context.get('request', None) if request: user = request.user userobj=User.objects.get(username=user) post = Posts.objects.create(user=userobj, **validated_data) post.save() return user error message : AttributeError: 'User' object has no attribute 'title' -
Decoding (and equating) special characters with the Django REST framework SearchFilter?
I have implemented a Django Rest Framework SearchFilter in my backend, which for the most part works correctly. This is the code structure in views.py: class JobsViewSet(viewsets.ModelViewSet): queryset = Jobs.objects.all() serializer_class = JobSerializer filter_backends = [filters.SearchFilter] search_fields = ['^name', '^job_type'] The only remaining problem is that when sending get requests with a special character, for example the Swedish letter å, Django doesn't recognize that å is the same letter as Å only in lower case (as it does with for example a and A). In the GET calls from the front end, å gets converted to %C3%A5 for lowercase and %C3%85 for uppercase. This results in the search box not finding the jobs beginning with the letters åäö if the job title begins in uppercase (as in Återvinning). Does anyone know of a solution that makes the filter understand and equate uppercase and lowercase letters of special characters? Something along the lines of UTF-8 decoding? I have looked for answers both in the REST framework documentation and here on Stack Overflow, without any luck. New to Stack Overflow btw, I hope I'm doing the formatting correctly! -
not able to POST required data in django templates
I want to POST a form from my html to views.py in django, but I am not able do it. This is my html. This form should post the url of the downloaded image to the views.py function. {% for x in photo %} <a class="down" href="{{x.image.url}}" onclick="myfunc()" download="none">get</a> <form action="/image_info/" method="POST" id='dform'> {% csrf_token %} <input name='d_button' type="hidden" value="{{x.image.url}}"> </form> {% endfor %} This is my javascript function to submit form whenever the get link is pressed <script type="text/javascript"> function myfunc() { document.getElementById("dform").submit(); console.log('hello'); } </script> this is my views.py. This should take the image url from the form and display it in the new page. def show_image(): image_url = request.POST.get('d_button', None) return render(request, 'show_image.html', {'image': image_url) but my problem is that the form is not returning the url of the image that is clicked instead it is returning the url of first link. for example link1 link2 link3 link4 if I click on link3, it is downloading the image in link3 but POSTING the url of link1 This is a bit tricky to explain but this is the best I can. Thanks in adavnce.