Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a total value from two element using JS in Django
I know this question has being done here a lot but I looked and tried a lot of answers, wasn't able to retrieve what i need. First, I pass a value from an item using django forms through the view. In this example, the template receive the value of "900" because I use the default {{form.price}} in HTML . <input type="text" name="price" value="900" readonly="readonly" id="id_price"> Inside the same HTML i have a field to manually insert a quantity: <input type="text" name="quantity" id="quantity"> And the final input to show to multiplication between those two <input type="text" name="total" id="total"> As a script I used this (saw the answer in a question but i wasn't able to recreate the result in my "total" input) SCRIPT <script> $(document).ready(function () { $('').keyup(function () { var multiplyAndShow = function () { var val1 = parseFloat($('#id_price').val()) var val2 = parseFloat($('#quantity').val()) val3 = val1 * val2 || "Some Text" $("#total").html(val3) } $("#id_price").keyup(function () { multiplyAndShow(); }); $("#quantity").keyup(function () { multiplyAndShow(); }); }); }); The script is not been used because when I set a quantity it doesn't make a thing. The price value is readonly so i don't know if that's the problem. I'm a newbie in javascript … -
Django many-to-many add having inconsistent effect in functions, works on console
I'm creating a lesson planning tool. Each lesson covers multiple syllabus points, and has associated resources. When you save a lesson, I want to make sure that the syllabus points for the lesson are also saved to the resources. I've tried using both signals and overiding the save method to make this work, but keep getting weird results. models.py class Lesson(models.Model): lessonslot = models.ForeignKey(TimetabledLesson, on_delete=models.CASCADE) classgroup = models.ForeignKey(ClassGroup, null=True, blank=False, on_delete=models.SET_NULL) status = models.CharField(max_length=20, null=True, blank=True) syllabus_points_covered = models.ManyToManyField(SyllabusPoint, blank=True) lesson_title = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) requirements = models.TextField(null=True, blank=True) sequence = models.IntegerField(null=False, blank=True) date = models.DateField(null=True, blank=True) syllabus = models.ForeignKey(Syllabus, blank=True, null=True, on_delete=models.SET_NULL) class Meta: unique_together = ( ("lessonslot", "date"), ("classgroup", "sequence")) class LessonResources(models.Model): lesson = models.ForeignKey(Lesson, blank=True, null=True, on_delete=models.SET_NULL) resource_type = models.CharField(max_length=100, choices=RESOURCE_TYPES, null=False, blank=False) resource_name = models.CharField(max_length=100, null=True, blank=False) link = models.URLField(blank=True, null=True) students_can_view_before = models.BooleanField() students_can_view_after = models.BooleanField() available_to_all_classgroups = models.BooleanField() syllabus_points = models.ManyToManyField(SyllabusPoint, blank=True) def set_syllabus_points(self): if self.lesson: points = self.lesson.syllabus_points_covered.all().order_by('pk') for point in points: self.syllabus_points.add(point) return self signals.py from timetable.models import LessonResources, Lesson from django.db.models.signals import post_save, m2m_changed from django.dispatch import receiver @receiver(m2m_changed, sender=Lesson.syllabus_points_covered.through) def post_update_lesson_syllabus_pts(sender, instance, **kwargs): """ After adding a syllabus point to a lesson, update its resources""" resources … -
React + Django Axios Issues
I have a react application linked to a Django backend on two separate servers. I am using DRF for django and I allowed cors using django-cors-headers. For some reason when I curl POST the backend, I am able to get the request out. However when I use axios POST the backend, I get and error. The status of the POST request from axios is failed. The request and takes more than 10 seconds to complete. My code was working locally (both react and django codes), but when I deployed to AWS ec2 ubuntu, the axios requests stopped working. Console error logs OPTIONS http://10.0.3.98:8000/token-auth/ net::ERR_CONNECTION_TIMED_OUT { "config": { "transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "headers": { "Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=UTF-8", "Access-Control-Allow-Origin": "*" }, "method": "post", "url": "http://10.0.3.98:8000/token-auth/", "data": "{\"username\":\"testaccount\",\"password\":\"testpassword\"}" }, "request": {} } Here is my request code axios.post('http://10.0.3.98:8000/token-auth/', JSON.stringify(data), {headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", }}, ).then( res => ( console.log(JSON.stringify(res)), ) ).catch( err => ( console.log(JSON.stringify(err)) ) ); my curl code that worked curl -d '{"username":"testaccount", "password":"testpassword"}' -H "Content-Type: application/json" -X POST http://10.0.3.98:8000/token-auth/ -
path('direct/',DirectView.as_view(),name='direct'), AttributeError: type object 'DirectView' has no attribute 'as_view'
here is my views.py code class DirectView(mixins.CreateModelMixin): serializer_class=DirectSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) def post(self,request,*args,**kwargs): return self.create(request,*args,**kwargs) and my urls.py path('direct/',DirectView.as_view(),name='direct'), but whenever i tried to run the server i get an error as AttributeError: type object 'DirectView' has no attribute 'as_view' i don't understand what the issue is ? -
Django override slugify globally
I've encountered a problem with Django's built-in slugify function. I'm building a website using Django framework. The site must have a forum app. After a bit of searching, I've found one. It works great, however, it's using the slugify function heavily on the topic titles to create "human readable" links to its pages. The problem is, we are writing in Russian, so as the result, it generates non-ASCII URLs which look like an unreadable mess of unicode data when trying to copy the link from the browser (and also throws an exception when trying to log them). Is there a way to override the Django's django.utils.text.slugify globally for the whole project so I don't need to include half of the third party library only to change the import statements in their models.py ? -
Image in django admin InlineModel
I have these models and i want to add SampleImage model in to Orderdetail as InlineModel.And want to display images in orderdetail model.I tried lot of answer already posted in stackoverflow but i can't configure my answer. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100, ) class Industry(models.Model): name = models.CharField(max_length=100) class OrderDetail(models.Model): company_name = models.CharField(max_length=100, blank=True, null=True) name_in_logo = models.CharField(max_length=150) slogan = models.CharField(max_length=200) describe_website_and_audience = models.TextField(blank=True) category = models.OneToOneField(Category, on_delete=models.CASCADE, default=None) industry = models.OneToOneField(Industry, on_delete=models.CASCADE, default=None) class SampleImages(models.Model): image = models.ImageField(upload_to='images/tile_images') category = models.ManyToManyField(Category) industry = models.ManyToManyField(Industry) orderdetail = models.ForeignKey(OrderDetail, on_delete=models.CASCADE, default=None) -
pdf file generated using reportlab , getting saved as plain text
this is the first time i'm using reportlab. i copied the exact code from django documentation. https://docs.djangoproject.com/en/2.1/howto/outputting-pdf/. When i save the file its getting saved as plain text document (text/plain), the name remains the same hello.pdf and there is no text. p = canvas.Canvas(buffer) in this line if i write the name of file 'hello.pdf' instead of buffer and remove the buffer from the fileresponse method it works and automatically gets saved as pdf file, but i cannot prompt the user to save the file and there are two pages in the pdf. def some_view(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers # present the option to save the file. return FileResponse(buffer, as_attachment=True, filename='hello.pdf') i tried specifying the content_type='application/pdf' in the code provided by django documentation but it still gets saved as plain text … -
I need a one to many relationship between 3 tables
I need a one to many relationship from Pessoa to Veiculo being registered in Mensalista I'm Brazilian then in the table Veiculo == vehicle and Pessoa == person and Mensalista == parking I need a person to have more than one vehicle, and when you register in the parking lot when you choose one person appears in the other filds only their vehicles. I'm very new, I need detailed explanations, I appreciate the help and patience. Models.py TATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins') ) class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) cpf = models.CharField(max_length=11, unique=True, blank=False) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=10) bairro = models.CharField(max_length=30) telefone = models.CharField(max_length=20, blank=False) cidade = models.CharField(max_length=20) estado = models.CharField(max_length=2, choices=STATE_CHOICES) def __str__(self): return str(self.nome) + ' - ' + str(self.email) class Veiculo(models.Model): marca = … -
'WSGIRequest' object has no attribute 'sessions' (Django 2.1.2)
I am working on a django web app and I need to use sessions and cookies. I wasn't getting this error before while using sessions and cookies but now It is happening again: AttributeError at /dashboard/ 'WSGIRequest' object has no attribute 'sessions' Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/ Django Version: 2.1.2 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'sessions ... def dashboard(request): context = { } request.sessions.set_test_cookie() request.sessions["test"] = "This Is A Test" return HttpResponse(f'<h1>This Is Where The Dashboard is Going To Be :)</h1><br /><h1>Welcome</h1>') I already checked my MIDDLEWARE order and made sure that MIDDLEWARE wasn't supposed to be MIDDLEWARE_CLASSES. Here is the code in my settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'portalhome.apps.PortalhomeConfig', 'Users.apps.UsersConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'airquality.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'airquality.wsgi.application' The wierd thing is is that django is able to set a csrf_token (a cookie) and before this error my sessions were working fine. I also did not change any of the code from when the sessions … -
What does "auth.User" in django do?
I'm trying to learn Django and I came across the following code in the books. from django.db import models class Post(models.Model): title = models.CharField(max_length=) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title Even though I understand the most part of it I don't really understand what does "auth.User" do in the code. Furthermore, I tried searching for it in the documentation without any success (Which I found quite strange). Thank you very much in advance for your help. -
Django Rest Framework - Making a PDF for the front-end.
There is 3 hours I'm following some tutorials, reading old answers for this topic about pdf with Django here on stackoverflow link, link, link, also this one and I'm getting the same error. I tried almost every answer on those topics lol. TemplateDoesNotExist index.html Django tried loading these templates, in this order: I don't have a index.html in the django template folder because I'm just using DRF to provide the API. My intention is to create a pdf file with some data from the models and provide a endpoint for my React application for the user to see/download the file. -
How to set specific faker random string of specific length and using underscores for spaces?
import factory.fuzzy import faker from core.strings import underscore_15 from factory import DjangoModelFactory, SubFactory faker = faker.Factory.create() class SubProjectFactory(DjangoModelFactory): class Meta: model = SubProject django_get_or_create = ("internal_name",) internal_name = factory.Faker('pystr') internal_short_name = factory.Faker('pystr') underscore_15 = factory.fuzzy.FuzzyText(length=15) main_project = SubFactory(MainProjectFactory) I need the field underscore_15 to be a lower-case string of specifically just 15 characters long and no spaces. If there's any space it should be underscore. I tried to put a function around factory.fuzzy.FuzzyText(length=15). Then I realized that I was assuming FuzzyText returns a string but it was a FuzzyText object. What should I do? -
Django: fastest way to update the data that was once sent from template to view
I am working on an data visualisation app that will allow the user to filter the data that he sees by various criteria. I want to keep as much logic as possible on Python/Django side, like this: Data is passed from Django template to the view. On the frontend, user filters the data through various controls: dropdowns, sliders etc. The controls inputs are sent back to Django view (via AJAX post request?), which returns filtered data and sends it back to the template. 4.The template - the visualization - is updated with the filtered data. Is this a good approach? My concern is that a lot of data will be flying around and the app might be unresponsive. Another, possibly faster idea is to filter the data on client's side in JavaScript - but I would really like to leverage the great Python data munching libraries instead. -
I'm getting positional argument in Django rest framework APIView class empty. Why? And how to pass value into it?
I'm playing with DRF just for fun and I'm trying to get single record by its ID. Here is my setup: Django version 2.1.4 DjangoRestFramework 3.9.0 models.py class BoardModel(models.Model): board_title = models.CharField( ... ) board_c_time = models.DateTimeField( ... ) urls.py urlpatterns = [ re_path(r'^get_board(?P<pk>\d*)$', views.GetBoard.as_view(), name="get-board"), ] serializers.py class GetBoardSerializer(serializers.ModelSerializer): """Board serializer.""" class Meta: model = BoardModel fields = ("id", "board_title", "board_c_time") views.py class GetBoard(APIView): """Get single board.""" def get_object(self, pk): """Search for the object.""" try: return models.BoardModel.objects.get(pk=pk) except models.BoardModel.DoesNotExist: raise Http404 def get(self, request, pk, format=None): """GET method.""" pk = int(request.query_params.get('pk')) obj = self.get_object(pk) serializer = GetBoardSerializer(obj) return Response(serializer.data) Sending GET request to my_url.com/api/get_board?pk=123). Positional argument 'pk' in the get method of GetBoard class should take the value from the pk parameter in url (eg pk=123) however it returns an empty string. Because of that I had to access it through request.query_params.get('pk') but it looks weird to me. Did I miss something? How to get value from the URL parameter into positional argument in the get method mentioned above? Thanks a lot in advance! -
x-editable & django: how to pass the model to the server
using django 1.11.7 & x-editable (most recent version) x-editable allows to pass following parameters to the server: "pk" = pk of object "name" = name of the field to be changed "value" = new value What is missing here is a way to identify the Django model. Of course this can be managed in the view (where the POST request is handled) but that is not a generic way to handle things as it would require a view per Django model. How can we manage to get this behaviour, where objects from multiple Django models can be edited from the same HTML page: HTML: <span>Model1/pk123/Field1:</span> <a href="#" class="xed" data-model="django_model1" data-name="field1" data-type="text" data-pk="123">dummy content</a> <span>Model2/pk456/Field2:</span> <a href="#" class="xed" data-model="django_model2" data-name="field2" data-type="text" data-pk="456">another dummy content</a> JAVASCRIPT: $(document).ready(function () { $.fn.editable.defaults.mode = 'inline'; $('.xed').editable({ params: { csrfmiddlewaretoken:'{{csrf_token}}', }, url: '/xed_post', }); Problem is that the "data-model" variable is not given to the server, so the server doesn't know in which model (DB TABLE) to look for primary key "pk" Hard coding that data-model in the javascript code is possible: $(document).ready(function () { $.fn.editable.defaults.mode = 'inline'; $('.xed').editable({ params: { csrfmiddlewaretoken:'{{csrf_token}}', model:'django_model1' }, url: '/xed_post', }); ... but then how can we get this working … -
Django: how to pass "Javascript ready" context from template to view
In Django, how do I pass a dictionary from view to template, so that the dictionary can be accessed in JavaScript? For example, the following code: <script> {% for k, v in d.items %} console.log( {{ v }} ) {% endfor %} </script> will throw an error in browser console: SyntaxError: expected expression, got '&' Similarly, trying to print the dictionary keys: <script> {% for k, v in d.items %} console.log( {{ v }} ) {% endfor %} </script> will throw: ReferenceError: numbers is not defined where numbers is one of dictionary's keys. However, similar loops will work fine outside of <script> tag: #this works {% for k, v in d.items %} {{ v }} {% endfor %} -
promotions by schedule/scheduled shares in django-oscar
I want to write a web application using django-oscar framework. Can you please tell if there is an opportunity to create scheduled actions? For example, what would each of the 1st, 11th, 21st of each month automatically activate the scheduled share with special offer, and every 7, 17, 27 activate another scheduled share with special offer, and etc. -
How to translate user uploaded content?
I just integrated django's built-in translation capabilities with my website. Maybe I'm missing something, but if you have to go into your .po files and translate each msgstr manually, then how does user uploaded content get translated unless I go in and translate every time someone posts something? Also, do most of you use Google Translate for this or is there a better option? Any other tips or things you think I should know would be appreciated. -
How to customize the login error message?
I want to change "please enter a correct username and password. note that both fields may be case-sensitive" to something else. In login.html I have {{ form|crispy }} and in urls.py I have url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), in my URLs.py. -
how to fixe obj is not callable in pycham
TypeError: 'NoneType' object is not callable enter image description here -
Decoding Django POST request body
I'm building an mapping app using cordova and making a post request sending the following JSON (feature) { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ -6.6865857, 53.2906136 ] }, "properties": { "amenity": "pub", "name": "The Parade Ring" } } This is the JQuery code sending the request function savePub(feature){ $.ajax({ type: "POST", headers: {"csrfmiddlewaretoken": csrftoken}, url: HOST + URLS["savePub"], data: { pub_feature: JSON.stringify(feature) }, contentType:"application/json; charset=utf-8" }).done(function (data, status, xhr) { console.log(data + " " + status); pubDialogAlert("Pub saved",feature); }).fail(function (xhr, status, error) { showOkAlert(error); console.log(status + " " + error); console.log(xhr); }).always(function () { $.mobile.navigate("#map-page"); }); } When the request is received in the Django backend I am not sure why when I print the request body it looks like this, b'pub_feature=%22%7B%5C%22type%5C%22%3A%5C%22Feature%5C%22%2C%5C%22geometry%5C%22%3A%7B%5C%22type%5C%22%3A%5C%22Point%5C%22%2C%5C%22coordinates%5C%22%3A%5B-6.6865857%2C53.2906136%5D%7D%2C%5C%22properties%5C%22%3A%7B%5C%22amenity%5C%22%3A%5C%22pub%5C%22%2C%5C%22name%5C%22%3A%5C%22The+Parade+Ring%5C%22%7D%7D%22' and when I try to decode it and then use json.loads() it throws this error @api_view(['POST']) def save_pub(request): if request.method == "POST": data = request.body.decode('utf-8') received_json_data = json.loads(data) return Response(str(received_json_data) + " written to db", status=status.HTTP_200_OK) JSONDecodeError at /savepub/ Expecting value: line 1 column 1 (char 0) I am assuming because once it decodes the binary string it can't be converted to valid JSON because of those characters %22 etc, but I don't know what the … -
Tablediff in Django for sync'ing two table
I'm dealing with two tables that are growing at consistent rate. I need to find a way to sync these two tables. Whatever's missing from one table should be added or modified, but I can't seem to come up with a good way to do it as I don't know which to update. For example: Table A has a row with value (1, 2, 3, 4, '2018-12-10') while Table B has (1, 2, 3, 5, '2018-12-11'). I want to take the last modified value (so 1, 2, 3, 5) In addition, any newly added rows from one table should be added to the other table. I searched around and found tablediff using CLI, but I'm doing it through Django and wonder if I can do it through Django models or raw sql commands. If so, how? -
How to fix NoReverseMatch on redirect
Why am I getting Reverse for 'explorer_js' not found. 'explorer_js' is not a valid view function or pattern name. when calling the select view below?: def explorer_js(request): activities = Activity.objects.all() fill_column = lambda attr : [getattr(activity, attr) for activity in activities] d = { 'ids' : fill_column('id'), 'dates_added' : fill_column('date_added'), 'numbers' : fill_column('number'), 'athletes' : fill_column('athlete'), 'start_dates' : fill_column('start_date'), 'names' : fill_column('name'), 'countries' : fill_column('country'), 'links' : fill_column('link'), 'segment_efforts' : fill_column('segment_efforts'), 'distances' : fill_column('distance'), 'average_speeds' : fill_column('average_speed') } context = {'d': d} return render(request, 'explorer_api/explorer_js.html', context) def select(request): """Filters explorer data and sends it to explorer again""" return redirect('explorer_js') The app's urls.py: app_name = 'explorer_api' urlpatterns = [ # Home page. path('', views.index, name='index'), path('explorer_js/', views.explorer_js, name='explorer_js'), path('select/', views.select, name='select'), ] -
post_save doesn't list tags
Idea is to use a post_save signal to do things if an object has certain tags, but the tags are not being listed @receiver(post_save, sender=List) def list_saved(sender, instance, created, **kwargs): if created: for tag in instance.tags.all(): print(tag.name) This never lists any tags, it's an empty query set. Yet if I then open the shell and do: >>> l = List.objects.filter(pk=1) >>> for tag in l.tags.all(): >>> print(tag.name) It works fine. Why are the tags not available in the post_save? Tags are added to list as such: class List(models.Model): tags = TaggableManager() -
Add a link to custom django admin view
I've created a custom admin view as documented here. class MyAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [ path('stats/', self.admin_site.admin_view(self.stats)), ] return my_urls + urls def stats(self, request): request.current_app = self.admin_site.name context = dict( # Include common variables for rendering the admin template. self.admin_site.each_context(request), # Anything else you want in the context... key='blah', ) return TemplateResponse(request, "sometemplate.html", context) The URL is working and the template is loading. But how, can I get a link to my new custom view into the overview of the Django admin?