Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to enable button upon dropdown item selection in js?
What am I doing wrong here? function enableButton() { var all_statuses = document.body.querySelectorAll(".selected > .form-control"); var btnComplete = "complete"; for (var i=0; i<all_statuses.length; i++) { console.log(i + " This will work") if (all_statuses[i].value == btnComplete) { document.getElementById("submit").disabled = false; } else document.getElementById("submit").disabled = true; } } $(document).ready(enableButton); This is a function that gets called on onchange event for select element. In my scenario, it only works for either first item that contains a select element, or the last one in the list. I was sure this is the right way to loop through all items. What am I missing? Here is the select part of the form: <div class="selected"> <select class="form-control" id="###" onchange="enableButton()" > {% for item in STATUS %} <option value="{{ item }}" id="{{li.id}}" {% if li.status_str == item %} selected {% endif %} >{{ item }}</option> {% endfor %} </select> </div> -
How to get Django Graphene ModelForm Mutation to apply
I'm trying to make this mutation create a new record in the database. It returns code 200 but no change to the database plus it returns null. The documentation is not clear on this issue.(ModelForm vs mutate function) Graphql response: { "data": { "addSubjectMark": { "subjectMark": null, "errors": [] } } } According to django-graphene documentation, I'm using DjangoModelForm to handle the input into the db. My schema.py: class SubjectMarkType(DjangoObjectType): id = graphene.ID(required=True) class Meta: model = SubjectMark class AddSubjectMarkMutation(DjangoModelFormMutation): subject_mark = graphene.Field(SubjectMarkType) class Meta: form_class = ReportForm class Mutation(graphene.ObjectType): add_subject_mark = AddSubjectMarkMutation.Field() Do I need to add a save method to the form? Do I need to use the mutate function?(Docs unclear) Thanks! -
convert urls.py url to path
Im trying to follow a tutorial on web application hacking. the instructor has us building a web app using django. I realized that his version of python, django and probably everything else is older than mine and Im running into conversion issues as Im not quite a web developer. :) please look at the two images and help me convert his setup from urls.py url to the django 2.0 version of path. Thank you! this is his screen....and then mine. My version -
How is a ValidationError message tested for in Django REST Framework?
When attempting to test data that is passed to a Serializer, I want to test not just for the ValidationError but the error message itself. The way I have it currently checks for the field name in serializer.errors, but I'm looking to test for "Reformat your question please.". What would be a clean way of doing this? tests.py class TestQuestionSerializer(TestCase): '''Verify that when an invalid question is submitted that a validation error is raised''' @classmethod def setUpTestData(cls): cls.client_data = { "invalid": { "title": "Can I post a question?" }, "valid": { "title": "How can I post a question?" } } def test_question_serializer_fail(self): with self.assertRaises(ValidationError) as e: serializer = QuestionSerializer(data=self.client_data['invalid']) serializer.is_valid(raise_exception=True) self.assertIn("title", serializer.errors) serializers.py class QuestionSerializer(serializers.Serializer): title = serializers.CharField(max_length=50) def validate_title(self, value): regex = r"^[What|When|Where|How|Why]" match = re.search(regex, value) if not match: raise serializers.ValidationError("Reformat your question please.") return value def create(self, validated_data): return Question.objects.create(**validated_data) -
How to import Django models in seperate class
I'm using signals for post processing data. Because a lot need to happen, and later I want to run that logic on the background so the user don't have to wait for this, I want to run this code in a seperate class. I want to run the code in my Post Save event But I get the following error: ImportError: cannot import name 'ActivityDetail' from 'ryf_app.models' The model definitely exists in my models.py file What am I missing here? -
user authentication using async websocket instead of django channels
I have a websocket service previously written using python websocket package which can access django models. Is it possible to check if the messages are coming from an authenticated user without using django channels? -
TypeError: $.ajax is not a function , occurs only if $.ajax() is called inside a function (DJANGO)
Tried this , but same error, works outside a arrow or simple function. code: <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> keyPressed = () => { $.ajax({ type:'POST', url: '/search/', data: { 'search': 'hydroxi', }, headers: { "X-CSRFToken": csrftoken }, success: function (data) { if (data) { console.log(data); } } }); } -
Django change url pattern
My url pattern : path('business/average/turnover/<str:start_date>/<str:end_date>/', views.AverageTurnover.as_view()) when go to the url it shows something like this : http://127.0.0.1:8000/business/average/turnover/2019-01-1/2019-12-12/ but i want it to be like this : http://127.0.0.1:8000/business?start_date=adfadf&end_date=xsdfa How to do this -
Python - Building wheel for lxml (setup.py) ... error
I'm trying to run some code on my new server. It's not my code, but it's 100% working, because it runs smoothly on some other machines. When I try to install required modules from requirements file, I'm getting following error ERROR: Command errored out with exit status 1: command: /srv/usosapi-env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-1g1om26q/lxml/setup.py'"'"'; __file__='"'"'/tmp/pip-install-1g1om26q/lxml/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-drhhibz7 cwd: /tmp/pip-install-1g1om26q/lxml/ Looking down into stacktrace, there is: x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/libxml2 -Isrc/lxml/includes -I/usr/include/python3.7m -I/srv/usosapi-env/include/python3.7m -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-3.7/src/lxml/lxml.etree.o -w src/lxml/lxml.etree.c: In function ‘__Pyx_ExceptionSave’: src/lxml/lxml.etree.c:221049:21: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_type’; did you mean ‘curexc_type’? And some identical errors for other functions. Here's my requirements file: Django >=1.11, < 2.0 mysqlclient == 1.3.13 cx_Oracle == 5.2.1 lxml == 3.6.2 beautifulsoup4 pylibmc == 1.5.1 django-statsd-mozilla == 0.3.16 statsd == 2.1.2 pillow == 3.2.0 wand >= 0.4.4, <0.5 pycurl >= 7.19.5.1, <7.19.6 PyYAML==5.1.2 tornado == 3.2.2 icalendar == 3.6.2 python-dateutil == 2.5.3 contexttimer == 0.3.1 signxml == 2.5.2 sqlparse == 0.2.1 python-magic == 0.4.12 simplejson==3.10.0 firebase-admin>=2.13 oauth2client==4.1.3 SQLAlchemy==1.2.11 Arpeggio==1.9.0 django-oauth-toolkit==1.1.0 typing zeep==3.4.0 pyOpenSSL==17.5.0 And modules installed in virtualenv by … -
Get object as output instead of List in Django
I'm trying to get output result as an object but i'm getting result as a list. My view: def Expense_with_id(request, id): details = ExSerializer(Cat.objects.filter(id=id).all(), many=True).data return JsonResponse(details, safe=False) Output: [{ "id": 1, "category": 1, ...... }] I want my output to be : Expected Output: { "id": 1, "category": 1, ...... } How can I achieve this with the current query. -
i cannot submit form
RuntimeError at /login You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/login/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. -
How To Update A Model With No Form
I can update models with forms in POST no worries, but I have a function which creates a pdf and I need to add the location to my model but I cant figure out how. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') questionnaire = models.FileField(upload_to='pdfs\\questionnaire_pdfs', null=True) views.py def final_question(request): if request.method == 'POST': form = FinalQuestionForm(request.POST, request.FILES, instance=request.user.finalquestion) if form.is_valid(): form.save() # here i generate pdf containing all answers to questionnaire # i then return the file name and need to save it in my users profile/questionnaire field pdf_filename = utils.generate_questionnaire_pdf(request) [..save the file to questionnaire..] return redirect('questionnaire_complete') [..cont..] Thank you. -
not able to fetch images from /media/ folder, it woks fine if i try to access through index of it. for loop inside templates is not working
URLs - urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="ShopHome"), Views - views.py from django.shortcuts import render from . models import Product from math import ceil def index(request): products = Product.objects.all() print(products) n = len(products) nSlides = n//4 + ceil((n/4)-(n//4)) params = {'no_of_slides':nSlides, 'range': range(1, nSlides), 'product': products} return render(request, 'shop/shop.html', params) Template - shop.html {% load static %} <div class="central-meta"> <span class="create-post">Robotic Products <a href="#" title="">See All</a></span> <ul class="suggested-frnd-caro"> <li> <img src="/media/{{product.0.image}}"> <div class="sugtd-frnd-meta"> <a href="#" title="">{{product.0.product_name}}</a> <span>2 mutual friend</span> <ul class="add-remove-frnd"> <li class="add-tofrndlist"><a href="#" title="Add friend"><i class="fa fa-star"></i></a></li> <li class="remove-frnd send-mesg"><a href="#" title="remove friend"><i class="fa fa-comment"></i></a></li> </ul> </div> </li> {% for i in product|slice:"1:"%} <li> <img src="/media/{{product.i.img}}"> <!-- fetching from DB --> <div class="sugtd-frnd-meta"> <a href="#" title="">{{product.i.product_name}}</a> <!-- fetching from DB --> <span>2 mutual friend</span> <ul class="add-remove-frnd"> <li class="add-tofrndlist"><a href="#" title="Add friend"><i class="fa fa-star"></i></a></li> <li class="remove-frnd send-mesg"><a href="#" title="remove friend"><i class="fa fa-comment"></i></a></li> </ul> {% if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last %} </div><div class="carousel-item"> {% endif %} </div> {% endfor %} </li> </ul> --> -
Django filter by extra field on many to many relationship
I have this kind of model definition and I wish to have a list of product that have attribute distance < 40 from the respective product class Product(models.Model): title = models.CharField(max_length=255) near_duplicate_images = models.ManyToManyField("self", through="NearDuplicate") class NearDuplicate(models.Model): first_product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="first_product") second_product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="second_product") distance = models.IntegerField(null=True, blank=True) I've tried doing this to directly access the relation p = Product.objects.filter(near_duplicate_images__distance__lt=40).prefetch_related('near_duplicate_images') But it raise this exception django.core.exceptions.FieldError: Related Field got invalid lookup: distance I've also tried doing this p = Product.objects.all().prefetch_related(Prefetch("near_duplicate_images", queryset=NearDuplicate.objects.filter(distance__lt=40), to_attr="near_duplicate_images_list")) But it raise this exception django.core.exceptions.FieldError: Cannot resolve keyword 'near_duplicate_images_rel_+' into field. Choices are: distance, first_product, first_product_id, id, second_product, second_product_id -
I get a 504 bad gateway error when trying to submit a post request?
my web app which is currently live is having some problems with submitting a post request which is a contact form sending emails, It works fine on my local machine but when I submit it on the live server, It gives me a 504 error, I'm running Nginx as my webserver, Is it because Nginx is not able to connect with smtp.gmail or something else? Most importantly How can I fix this? Here's my nginx configuration server { server_name woke-agency.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/ubaid/woke/static_root; } location /media { alias /home/ubaid/woke/media_root; } location / { include uwsgi_params; uwsgi_pass unix:/var/uwsgi/woke.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/woke-agency.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/woke-agency.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = woke-agency.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name woke-agency.com; listen 80; return 404; # managed by Certbot } -
How to get absolute path with select_related?
I am using fileField to save an image as follows, store_logo = models.FileField(upload_to=content_file_name, blank=True, default='', null=True) and I am retrieving the mentioned field as follows, def getpaymentpage(request, store_identifier): uniqueurl_form = UniqueUrlForm(request.POST or None, request.FILES or None) store = PaymentModesConfigurations.objects. \ filter(unique_url=store_identifier). \ select_related("payment_page_display_details_id"). \ values("payment_page_display_details_id__store_logo") store_object = get_object_or_404(store) if uniqueurl_form.is_valid(): print("sent to gateway") context = { 'form': { uniqueurl_form, }, "page": store_object, } return render(request, 'unique_url.html', context) But when I do following in my template i dont get the value, <img src="{{ page.payment_page_display_details_id__store_logo.url }}" class="img-responsive"> even though I am getting value in page.payment_page_display_details_id__store_logo , .url() doesnt seem to work on it. Is it because I am using values() in queryset? What am I doing wrong here? Thank you for your suggestions. -
Html <video> tag controls not working properly
I have created a video player with playlist. The problem is that the forward control is not working properly as I cannot forward the video. What can be the problem cause it is working fine when working with static video files. here is my html code. I have used 3 tabs which loads iframe video, normal video and iframe powerpoint. is this creating the problem by overlapping. <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab"> <div class="row" id="video_player"> <div class="col-lg-4 col-sm-12 playlist"> {% for slides in tutorial.lecture_set.all %} {% if slides.lecture_content %} <a href="{{slides.lecture_content.url}}"> <div class="row mt-2"> <div class="col-lg-3"> <img src="{{slides.course.poster.url}}" class="img-fluid" alt="lecture slides"> </div> <div class="col-lg-9"> <p>{{slides.lecture_title}}</p> </div> </div> </a> <hr> {% else %} <p> There are no slides uploaded.</p> {% endif %} {% endfor %} </div> <div class="col-lg-8 col-sm-12"> <video class="frame" controls="controls" poster="{{ tutorial.poster.url }}" id="videoarea"> <source src="" type="video/mp4"> <source src="" type="video/webm"> </div> Js code: var video_player = document.getElementById("video_player"), links = video_player.getElementsByTagName('a'); for (var i=0; i<links.length; i++) { links[i].onclick = handler; } function handler(e) { e.preventDefault(); videotarget = this.getAttribute("href"); filename = videotarget.substr(0, videotarget.lastIndexOf('.')) || videotarget; video = document.querySelector("#video_player video"); video.removeAttribute("poster"); source = document.querySelectorAll("#video_player video source"); source[0].src = filename + ".mp4"; source[1].src = filename + ".webm"; video.load(); video.play(); } -
How does ForeignKey decides for the reference?
Here is my django model class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name = 'students',on_delete=models.CASCADE) def __str__(self): return self.name In the above code, ForeignKey of Student class is referencing to name of School class.How is it deciding for the reference ? -
AttributeError: 'str' object has no attribute 'get' (django view)
This is communication between ajax operation and django view. There is a form, and if I click submit button of the form, the Ajax code excuted. But it consistently makes error, written below. I can't figure out the reason of it. I suppose this is related to how form is conveyed to a view, but I don't know how to fix it. Internal Server Error: /makeevent Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/workspace/CalendarProject/cencal/views.py", line 42, in makeevent if form.is_valid(): File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 185, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 180, in errors self.full_clean() File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 381, in full_clean self._clean_fields() File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 393, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "/usr/local/lib/python3.7/site-packages/django/forms/widgets.py", line 258, in value_from_datadict return data.get(name) AttributeError: 'str' object has no attribute 'get' Javascript code: function makeEvent(event){ event.preventDefault(); var year = event.target.childNodes[3].children[0].value.slice(0,4); var month = event.target.childNodes[3].children[0].value.slice(5,7); var day = event.target.childNodes[3].children[0].value.slice(8,10); $.ajax({ type: "POST", url: "{% url 'makeevent' %}", data: {'form': $("#makeEventForm").serialize(), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response){ console.log(response); refreshCalendarAjax(year, month); listevent(year, … -
filter a column with a multiple keywords, in django
I am trying to filter a column in DB with a multiple keywords but having a problem. When I try to apply __contains= on an array it's doesn't work. def get_tasks_by_filters(request): datas = json.loads(request.body) tasks = Task.objects.filter(task_name__contains=datas["keywords"]) serializer = TasksPricesSerializers(tasks, many=True) return JsonResponse(serializer.data, safe=False) And __contains= of course working with a single value Task.objects.filter(task_name__contains=datas["keywords"][0]) But how can apply __contains= on multiple keywords/array. What is the possible way to achieve this? -
Django orm convert to without loop
I am fetching data from url.And while inserting data i have to run query again and again. Data from url [{'Date': '22-Aug-2019', 'Open': 10905.3, 'High': 10908.25, 'Low': 10718.3, 'Close': 10741.35, 'Shares Traded': 668193449, 'Turnover (Rs. Cr)': 18764.38}, {'Date': '23-Aug-2019', 'Open': 10699.6, 'High': 10862.55, 'Low': 10637.15, 'Close': 10829.35, 'Shares Traded': 667079625, 'Turnover (Rs. Cr)': 20983.75}, {'Date': '26-Aug-2019', 'Open': 11000.3, 'High': 11070.3, 'Low': 10756.55, 'Close': 11057.85, 'Shares Traded': 684141923, 'Turnover (Rs. Cr)': 22375.99}] models.py class BusinessShareInfo(models.Model) : Date = models.DateField(default=timezone.now) Opens = models.DecimalField(decimal_places=2,max_digits=20) High = models.DecimalField(decimal_places=2,max_digits=20) Low = models.DecimalField(decimal_places=2,max_digits=20) Close = models.DecimalField(decimal_places=2,max_digits=20) Shares_Traded = models.IntegerField() Turnover = models.DecimalField(decimal_places=2,max_digits=20) views.py As you can see here date in json is comming like "Date: 22-Aug-2019" so i am converting it into YYYY-MM-DD format and than storing in database. def insert_api_data(request): ''' Inserting data from api''' dataset = requests.get(config['url']['API_FETCH_URL']).json() for data in dataset : monthword = data['Date'][3:6] newWord = monthword[0].upper() + monthword[1:3].lower() x = strptime(newWord,'%b').tm_mon l = data['Date'] date = l[7:] + '-' + str(x) + '-' + l[:2] info = BusinessShareInfo.objects.create(Date = date,Opens=data['Open'],High=data['High'],Low=data['Low'],Close=data['Close'],Shares_Traded=data['Shares Traded'],Turnover=data['Turnover (Rs. Cr)']) info.save() return render(request,'BusinessShareInfo.html') There are 1000s of records in dataset fetched from json.I am looping for each and then inserting.How can i bulk insert with dateformant yyyy-mm-dd ? -
What should be the uwsgi's ExecStart exactly be?
I'm trying to deploy my project with django+uwsgi+nginx on ubuntu 18.04.2 and I've been doing things by following many of the examples on the internet. But I've got error and the error message says there's something wrong with my ExecStart in uwsgi.service file. Exact error message is as follows: uwsgi.service: Failed to execute command: No such file or directory uwsgi.service: Failed at step EXEC spawning /home/myvenv/bin/uwsgi: No such file And following is part of my uwsgi.service file. [Service] ExecStart=/home/myvenv/bin/uwsgi --ini /home/web_control/conf/uwsgi.ini This is where I'm totally lost, because the directory /home/myvenv/bin/uwsgi doesn't exists. And many other directories I could find on examples on internet wasn't there, too. I've referenced so many examples, so I'm actually lost which one was the original example of that part. What should be ExecStart? -
Identify the part where the video was viewed
I was creating an online movie portal in Django. If the user who is seeing the movie leaves the site, he is seeing the movie again from the beginning. I want to solve this problem and record the part of the video I saw in the base. How can I do that? -
put condition on distance of user
i have two model shop1 and shop2 shop1 it can share its location and define the distance under which its id print it can share shop category shop1 CATEGORY = ( ('BookShop', 'Bookshop'), ('Bakery', 'Bakery'), ('Dairy', 'Dairy'), Shop_category = models.CharField(max_length=200, null=True, choices=CATEGORY) Distance = models.PositiveIntegerField(null=True,) Shop_location = models.PointField() sho2 CATEGORY = ( ('BookShop', 'Bookshop'), ('Bakery', 'Bakery'), ('Dairy', 'Dairy'), Shop_category = models.CharField(max_length=200, null=True, choices=CATEGORY) Your_location = models.PointField() shop2 shop2 chose shop category and share its location 2.the list of shop1 print which have the distance less then or equal to the distance define by shop1 and shop1 category = shop2 category -
Generating reports with dynamic field filters in django
I am displaying a list of model fields and related fields to the user. Users can set the filter on one or multiple fields. I need to return results according to those filters. Here is my Employee Model employeeID = models.AutoField(primary_key=True, db_index=True) joiningDate = models.DateField(null=True, blank=True) department = models.IntegerField() designation = models.IntegerField() qualification = models.CharField() highestDegree = models.CharField() name = models.CharField(max_length=50) fatherName = models.CharField(max_length=50, null=True, blank=True) motherName = models.CharField(max_length=50, null=True, blank=True) dob = models.DateField(null=True, blank=True) gender = models.IntegerField(choices=GenderTypes.choices(), null=True, blank=True) religion = models.IntegerField(choices=ReligionChoices.choices()) category = models.IntegerField(choices=CategoryChoices.choices()) address = models.TextField(null=True, blank=True) Other than these model fields, Users can apply a filter on some connected fields as well like salary which is stored in another table with employeeID as a foreign key. Filters can be particular values as well as range, as in the case of salary (10000 - 20000). I am just looking for a right direction to implement something like this. Thanks in advance for your time and help