Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Syntax Error in PostgreSql JSONField in django models
I have the following model from django.db import models from django.contrib.postgres.fields import JSONField class Fixture_lineups(models.Model): fixture_id = models.ForeignKey("Fixture", null=True, on_delete=models.SET_NULL) home_formation = models.CharField() home_start_xi = JSONField() home_substitutes = JSONField() away_formation = models.CharField() away_start_xi = JSONField() away_substitutes = JSONField() lastUpdate = models.DateTimeField(null=True) After creating this model i was trying to do migrations to my database(PostgreSql) but my traceback said me that in my model is syntax error. away_start_xi = JSONField() away_substitutes = JSONField() But i can not find this syntax error. -
Django Rest with strange tags
The products listed have two tags, one for category and one for more fine grained description. The problem is some of the tags have ampersands and spaces etc. A choicefield seems innapropriate, does DRF handle these things gracefully with a charfield? -
how to fix TypeError: 'int' object is not iterable? [on hold]
Python shell is raising TypeError: 'int' object is not iterable when running a function with a for-loop imported from a python script. But when I type the for loop itself line by line in the shell it performs the for-loop. Any ideas why this is happening? I am running the python shell using "python manage.py shell" in a django project folder. I also have a python file (fill_db.py )with some functions in it to populate the DB. When in the shell proceed to import fill_db.create_authors there is no problem. When I run create_authors() it raises the TypeError mentioned. However, If I re-write the create_authors() function in the shell it doesn't raise the error and the loop is executed. fill_db.py import random from catalogue.models import Author from catalogue.models import Publisher def create_authors(): # Create an 50 authors and their publishers for i in range(50): # kwargs for expanding in model creation kwargs={ 'first_name':'Author_'+str(i), 'last_name':'Perez_'+str(i), 'date_of_birth':str(1930+i)+'-01-11', 'date_of_death':'2013-06-06' } # Create and save an author author = Author.objects.create(**kwargs) author.save() # Create and save a publisher new_publisher = Publisher.objects.create(name=('Publisher_'+str(author.id))) new_publisher.save() # add the publisher to the author author.publisher_set.add(new_publisher) # save the author authors = Author.objects.all() return '%s authors created succesfully' % (str(len(authors))) I expect … -
django rest_framework and modeltranslation not work expected
i use the the django rest_framework to access data from outside my application (API). I have installed the django modeltranslation to store some data in various languages in the database. For example i have a model named category: class Category(models.Model): name = models.CharField(max_length=50, verbose_name="Name", unique=True) description = models.TextField() locked = models.BooleanField() def __str__(self): return self.name I defined a serializer for this model to serialize the data on an api call, it looks like this: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' All works fine! If i call the url to the rest_framework view, i get this: [ { "category": { "id": 1, "name": "test", "description": "example", "locked": false, } ] Now i register the model for modeltranslation in the translation.py: class CategoryTranslationOptions(TranslationOptions): fields = ('name', 'description', ) translator.register(Category, CategoryTranslationOptions) After do that and insert the other languages in the database for the specific category with id = 1, i get the following output for the api call: [ { "category": 1 } ] I don't know why. I would like to get all data from category model including all translations. -
Store sum from views to database django
I am trying to store the total attendance of the student in percentage to the database without form. the Views.py def attStudName(request): #to display each student name with their total mark in table form students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance')) #to convert the total mark to percentage and save in FinalAtt table mark = 0 mark += students.attendance work = FinalAtt.objects.all() for stud in students: stud.mark = (stud.mark/1100) * 100 work.VMSAcc = students work.finalMark = mark work.save() context = { 'students' : students } return render(request,'show-name.html',context) MarkAtt Model: class MarkAtt(models.Model): studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) week = models.IntegerField(default=1) attendance = models.IntegerField(default=100) FinalAtt Model: class FinalAtt(models.Model): VMSAcc= models.ForeignKey(Namelist, on_delete=models.SET_NULL, null=True) finalMark = models.DecimalField(max_digits=5, decimal_places=2) The error i am getting is: 'QuerySet' object has no attribute 'attendance' How do i resolve this and save the information i want successfully? -
Getting JSON data for a Bootstrap Table from a Django server
I am trying to get data for the Bootstrap table from Django server as Json responce: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.15.4/dist/bootstrap-table.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script src="https://unpkg.com/bootstrap-table@1.15.4/dist/bootstrap-table.min.js"></script> <table class="table table-striped" id="table" data-toggle="table" data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data" #data-url="http://totoshick.pythonanywhere.com/getdata" data-side-pagination="server"> <thead> <tr> <th data-field="id">#</th> <th data-field="name">Report name</th> <th data-field="description">Description</th> <th data-field="link">Link</th> <th data-field="start_date">Last launch</th> </tr> </thead> </table> Data from Bootstrap Table example: https://examples.wenzhixin.net.cn/examples/bootstrap_table/data My data: http://totoshick.pythonanywhere.com/getdata The table successfully shows the data from example, but not my ones - "No matching records found". Local varianat of my data: { "total": 5, "totalNotFiltered": 5, "rows": [ { "id": 1, "name": "name1", "description": "descr1", "link": "link1", "start_date": "2019-09-26T14:04:18Z" }, { "id": 2, "name": "name2", "description": "descr2", "link": "link2", "start_date": "2019-09-26T14:04:37Z" }, { "id": 3, "name": "name3", "description": "descr3", "link": "link3", "start_date": "2019-09-26T14:04:50Z" }, { "id": 4, "name": "name4", "description": "descr4", "link": "link4", "start_date": "2019-09-26T14:05:30Z" }, { "id": 5, "name": "name5", "description": "descr5", "link": "link5", "start_date": "2019-09-26T14:05:46Z" } ] } Accroding to documentation there are two types of json data BT work with. I have tried both variants (have not succeed), but my aim is server-side. Django view.py code: from django.http import JsonResponse from django.forms.models import model_to_dict from .models … -
Error while Running Python manage.py runserver comman
I have started learning django this was my first tutorial. first i ran '''django-admin startproject First''' this command works as according to tutorial but when i run this command '''python manage.py runserver''' Following Error Occur but not in tutorial video *Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 27, 2019 - 18:01:04 Django version 2.2.5, using settings 'first.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 203, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 67, in init super().init(*args, **kwargs) File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 449, in init self.server_bind() File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\MuBasHer\AppData\Local\Programs\Python\Python37\lib\socket.py", line 676, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 6: invalid start byte * -
How to dynamically create picklist field in html and add values dynamically to that picklist?
i want to add add pick list field in my form like this - https://demo.vtiger.com/vtigercrm/index.php?module=LayoutEditor&parent=Settings&view=Index&sourceModule=Assets&mode=showFieldLayout website credentials - username and password is admin. when you open that website go to add custom field and there you will find a picklist option just click on that. I want to do same. Can this is possible using html? i tried but i could not able to do this. -
Which is better for working with forms? Django Rest Framework vs Classic Django Form
I have a question. What is a better solution working with django rest framework and rendering forms on html, or using classic django forms. Is this a big difference? -
Django caching with Redis
I have implemented django caching using redis following this blog: https://realpython.com/caching-in-django-with-redis/ So I followed this, installed the package, Added in CACHES = { "default": { "BACKEND": "redis_cache.RedisCache", "LOCATION": "redis://127.0.0.1:8000/", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } Then in views. from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT from django.views.decorators.cache import cache_page CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT) and then added the decorator for the function @cache_page(CACHE_TTL) @login_required_dietitian def patient_profile(request, id): data = {} return render(request, 'profile.html', {'data':data}) And then I am getting this error while I run the server redis.exceptions.ConnectionError: Connection closed by server. I am new to such caching technique, Any suggestion how to resolve this issue? -
Django: How do I update only ONE record in my database?
I'm having a lot of trouble trying to update a single (record) object in my database. context['eval_list'] = Evaluering.objects.update(eval_relationer_id=self.kwargs.get('pk')) I use objects.update, but it updates ALL my objects fk. How do I achieve only updating one object? I have also tried this: context['eval_list'] = Evaluering.objects.update_or_create(eval_relationer_id=self.kwargs.get('pk')) But this creates a new object and does not update the record that I want to update. I know why it creates a new objects, and it is because the FK I'm trying to update is null. Surely, there must be a way to only update and not create a single record? What am I missing here? I tried adding a filter, but it feels redundant? I tried this: context['eval_list'] = Evaluering.objects.filter(eval_relationer_id=self.kwargs.get('pk')).update(eval_relationer_id=self.kwargs.get('pk')) I did consider trying to create an ID of the FK instantly and not later on, but I couldn't really get that to work, but if I created an ID then the update_or_create would work because an ID would exist already, BUT I cannot believe that I can't update a single object without create? If creating the ID earlier on is the only work around, I will have to figure out how. -
Declare ChoiceField in view.py in Django
I am dealing with some dynamic data based on selected category. I am using get_form_kwargs to declare dynamic fields. """Return the keyword arguments for instantiating the form.""" kwargs = super().get_form_kwargs() PowerPlugType = [ ("1", "1"), ("2", "2"), ] kwargs["dynamic_fields"] = [ { "type": forms.CharField, "name": "AnalogRGBInput", "required": False, }, { "type": forms.ChoiceField, "name": "PowerPlugType", "choices": [("1", "1")], "required": False, } ] return kwargs as you can see I am add CharField but I am not able to specifiy choices for ChoiceField. Thanks. -
Why when i call a javascript file in html it doesn't find it
Im trying to call an js file from my html but i always get an 404 Originaly i hadit in another folder but now i've decided to move it to the same directory so it would be "easier" to call it but still no efect -
Django/Python string maintain the number of spaces when save in a model
In my django app i have models with CharField or Textfield fields; sometime i need to save in this field strings with more than one single space within word, like for example "hello world" but after save() process in my db i find thad the 3 spaces become 1. i try: from django.utils import safestring but i don't know how to apply at the whole models fields How can i maintain the exact string i write in my textbox with the exact number of spaces i need? So many thanks in avance -
Django add multiple tags html tags
Trying to add two html tags, how can I do this in Django html template? Here is an example: ${{ data.price|floatformat:2 and Intcomma }} Need to load this to use the intcomma tag: {% load humanize %}. -
Use vuelidate from node_modules in django template
I've used Vue to consume an API but never in Django templates. I'd like to use the Vuelidate package for form validation but I'm having some problems importing validationMixin as specified in their documentation: import { validationMixin } from 'vuelidate'. I'm currently importing Vue.js from a CDN. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> I'm adding the path to vuelidate to my static files. # settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'node_modules', 'vuelidate', 'dist'), ] When my Django template is loaded I get SyntaxError: import declarations may only appear at top level of a module (Firefox) and Uncaught SyntaxError: Unexpected token { (Chrome) <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="module" src="{% static 'vuelidate.min.js' %}"></script> <script> import { validationMixin } from 'vuelidate' const app = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { test: 'Hello' } }) </script> I added type="module" to the script tag but that results in TypeError: Error resolving module specifier: vuelidate What am I missing here? -
User performs rate action api
User will rate a story. It is better to reference to StoryView(ModelViewSet) or create another. Or may be there is another easy way of doing that? class Story(models.Model): ... @property def average_rating(self): return self.rating_set.all().aggregate(Avg('rate'))['rate__avg'] class Rating(models.Model): rate = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10.0)]) story = models.ForeignKey(Story, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class Meta: constraints = [ CheckConstraint(check=Q(rate__range=(0, 10)), name='valid_rate'), UniqueConstraint(fields=['user', 'story'], name='rating_once') ] urls.py router.register('rate', StoryView, basename='rate') views.py class StoryView(viewsets.ModelViewSet): queryset = Story.objects.all() serializer_class = StorySerializer serializers.py class StorySerializer(serializers.ModelSerializer): rate = serializers.FloatField(source='average_rating', read_only=True) author = AuthorSerializer(read_only=True) class Meta: model = Story fields = '__all__' -
Django Admin - custom column in first row isn't rendered properly
We've came across a weird problem. There is a Transaction model and it's admin has a custom column revert which sends POST to server. The weird thing is that revert in the first line doesn't work. I just doesn't render the <form> tag. Other rows works correctly. @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): list_display = ['code', 'created', 'modified', 'wallet', 'title', 'amount', 'invoice_link','revert'] def get_queryset(self, request): qs = super().get_queryset(request) self.request = request return qs def revert(self, obj: Transaction): if obj.pk: html = render_to_string("alex_wallets/transactions/revert_block.html", context={'transaction': obj}, request=self.request) return mark_safe(format_html(html)) revert_block.html <div> <form onsubmit="return confirm('Naozaj chcete vytvoriť opačnú transakciu?')" action="{% url "wallets:revert_transaction" transaction.pk %}" method="post"> {% csrf_token %} <button style=" color: #fff; background-color: #00D996; border: 0; border-radius:4px; cursor: pointer; padding: 5px 10px;" type="submit">Vrátiť </button> </form> </div> This is an html of the first row (column revert): <td class="field-revert"><div> <input type="hidden" name="csrfmiddlewaretoken" value="agpE7aEExG19YJ3n8wDv88sC7J7u7aHXa5Od3vVJptA6t0on1gGENECaTt2Qp7hb"> <button style=" color: #fff; background-color: #00D996; border: 0; border-radius:4px; cursor: pointer; padding: 5px 10px;" type="submit">Vrátiť </button> </div></td> And this is an html of other than first row revert column: <td class="field-revert"><div> <form onsubmit="return confirm('Naozaj chcete vytvoriť opačnú transakciu?')" action="/alex/transakcie/transactions/revert/45/" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="Pc7Pt41tXgMUyZyKOORUb2gQutkqCkjpP1woppiyP3lR3gTKHyU3QyqogdfMUhTD"> <button style=" color: #fff; background-color: #00D996; border: 0; border-radius:4px; cursor: pointer; padding: 5px 10px;" type="submit">Vrátiť </button> </form> </div></td> The same … -
How to pass Json Web Token with post request in python?
Im testing my server API and Im trying to make a new user and using his account ask server for JWT access token, then refresh it and using new access token add a new record to my database. When i send request manualy like this with httpie it works - Server responds with 201 and new link created in json format: http POST :8000/api/urlslist/ Authorization:'Bearer <access token>' url=time.is But when I try to do the same kind of request in python server denies me. self.user = User.objects.create_user(username='Bob', password='Q@wertyuiop', email='name@example.com') def test_using_refreshed_api_key(self): # Ask for token response = self.client.post('/api/token', data={'username': 'Bob', 'password': 'Q@wertyuiop'}) json_data = response.json() # Refresh token response = self.client.post('/api/token/refresh', data={'refresh': json_data['refresh']}) json_data = response.json() # Add new url using refreshed token response = self.client.post('/api/urlslist/', \ data={'url':'google.com'}, headers={'Authorization':'Bearer {}'.format(json_data['access'])}) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Right now server responds with 401 Bad Authentication. I expect the respond to be 201 Created. -
how to get queryset from django orm create
i want to get queryset as a return value when i use the create in django orm newUserTitle = User_Title.objects.none() newUserTitle = newUserQuestTitle | newUserReviewTitle newUserTitle = newUserQuestTitle | newUserReviewTitle | newUserlevelTitle i want add three objects(newUserQuestTitle, newUserReviewTitle, newUserlevelTitle) as queryset -
django get_or_create saves data in parentheses
I am using django's get_or_create to save the data into postgres. The code works fine but the itemgrp1hd field saves as ('Mobile 5010',) while I have only fed Mobile 5010. Can anyone explain why the parentheses & single quotes are appearing when saved in postgres. The code is as below: @api_view(['GET', 'POST', 'PUT', 'DELETE']) def Post_Items_Axios(request): data_itemfullhd = request.data['Item Name'] data_itemgrp1hd = request.data['Item Group1'] td_items, created = Md_Items.objects.get_or_create( cunqid = entity_unqid, itemfullhd = data_itemfullhd, # defaults = dict( # itemgrp1hd = data_itemgrp1hd, # ) ) # type(request.data['Item Group1']) # <class 'str'> td_items.itemgrp1hd = data_itemgrp1hd, td_items.save() data = { 'data_itemfullhd': data_itemfullhd } return Response(data) -
How to access django mediafiles on virtualmin?
I am trying to deploy django website on virtualmin panel.i uploaded my django website into filemanager.if i am trying to access my django website,Some of the contents in media file are not shown .how do i access media folder?Any help is appreciated. -
Why i can not fetch data from backend what is error in this
i am trying to fetch data from backend django and with filter user and mode so why am i not able to fetch data if i putting user = 1 i can fetch data but when i try to put user=${this.props.match.params.user} i can't fetch data please help me async componentDidMount() { try { const res = await fetch( `http://localhost:8000/api/1/deliveries/${this.props.match.params.pk}/?mode=foot&user=${this.props.match.params.user}` ); const walk = await res.json(); console.log(walk); this.setState({ walk: walk.results }); } catch (e) { console.log(e); } } Here i attched image of backend with filterenter image description here Image of backend -
Get element of list by variable in Django template
I have line of code in Django template: <h4>{{ totals.date.weekday }}</h4> Totals is the Python list, how do i get item of this list by index stored in date.weekday? Creating another variable, which stores date.weekday doesn't work -
NoReverseMatch_Error_Django
When i try to get a link from function {% extends 'blog/base.html' %} {% block title %} My blog {% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </h2> <p class="date">Published {{ post.publish }} by {{ post.author }}</p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} NoReverseMatch error raised and i can't resolve it Some pictures for your understanding models.py views.py urls.py