Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want a Django Rest Framework nested serializer but don't want to 'post' to referenced objects
I want a Django Rest Framework ModelSerializer to return a foreign field with a nested object with some fields of the referenced object, so I defined a ModelSerializer that returns the desired fields from the related objects, and nested it. The 'get' method works as desired, but for the 'post' I need to provide the data for the nested object, instead of only the key to the referenced object. If I set read_only=True, then I am unable to provide the data for the required field and I get an error: This is the result I expect from the serializer: { "id": 1, "name": "Crescencio Rejon", "city": { "id": 4, "name": "Merida" }, "iata": "MID" } This is my model: class Airport(models.Model): city = models.ForeignKey('City', on_delete=models.PROTECT, related_name='city_airports', verbose_name=_('City')) name = models.CharField(max_length=40, unique=True, verbose_name=_('Name')) iata = models.CharField(max_length=3, unique=True, null=True, blank=True, verbose_name=_('IATA')) class Meta: verbose_name = _('Airport') verbose_name_plural = _('Airports') def __str__(self): return "[{}]{}".format(self.city, self.name) These are my serializers: class CityRelatedFieldSerializer(serializers.ModelSerializer): class Meta: model = models.City fields = ('id', 'name') class AirportSerializer(serializers.ModelSerializer): city = CityRelatedFieldSerializer() class Meta: model = models.Airport fields = ('id', 'city', 'name', 'iata') I haven't found another way to get the result I want but nesting the serializers, but, when … -
Django admin panel can not set valid choice when choices are enum.Enum
I use enum.Enum as choices for field language. I can create a book by b = Book(title="Some Title", language=LanguageChoice.EN). And query by books = Book.objects.filter(languge=LanguageChoice.EN). However, when I want to create new books at admin panel, it says Select a valid choice. LanguageChoice.EN is not one of the available choices.. Django has ability to serialize enum.Enum since 1.10. So how should admin panel work? Thanks. from enum import Enum from django.db import models class LanguageChoice(Enum): DE = "German" EN = "English" CN = "Chinese" ES = "Spanish" class Book(models.Model): title = models.CharField(max_length=255) language = models.CharField( max_length=5, choices=[(tag, tag.value) for tag in LanguageChoice] ) -
Django URL parameters replace each other
Perhaps my question will seem somewhat simple and understandable, but even so. In my project, I use standard pagination and sorting. The problem is that they replace each other in the get request, for example I sort them and if I go to the second page then the set is not sorted. I understand the reason and it seems the answer lies on the top, but even so I could not find it. Sorting: <a href="?order_by=counter__service__name_service&sort={{ sort_type }}">Counter</a> Pagination example: <a class="page-link" href="?page={{ history_application.previous_page_number }}">&laquo;</a> The question is how to save the parameters that were transmitted earlier. -
Ajax call using Django REST API python?
I am trying to pass multiple search fields to my Django API from my Ajax request but for some reason, its not filtering the results. I am still getting everything as if my search queries are not being passed to the Django API. What could i be doing wrong ? api.py from . import models from . import serializers from rest_framework import viewsets, permissions, filters class Useradviewset(viewsets.ModelViewSet): """ViewSet for the patientVisit class""" queryset = models.Userad.objects.all() serializer_class = serializers.useradserializer permission_classes = [permissions.IsAuthenticated] filter_backends = (filters.SearchFilter,) search_fields = ('user_id','category','country') ajax request $.ajax({ url: "/plentyofcats/api/v1/useradapi/", type: "get", data: { 'category': 'msw', 'country':'congo', }, success: function (json) { console.log(json) } }); -
In Django, what is the best practice for an app which relies on certain model instances?
In a Django project, we have a model SessionType which has a category foreign key to a SessionCategory. There is a function, create_checkin_sessions, which expects a SessionCategory with a certain name, 'Guide Check In', to exist in the database. If it doesn't, an error is logged: import logging from lucy_web.models import Session, SessionType, SessionCategory logger = logging.getLogger(__name__) class SessionCategory(models.Model): name = models.CharField(max_length=255, unique=True) class SessionType(models.Model): category = models.ForeignKey('lucy_web.SessionCategory') GUIDE_CHECKIN_CATEGORY = "Guide Check In" def create_checkin_sessions(family): _check_guide_checkins_category() session_number = 1 session_types = SessionType.objects.filter(category__name=GUIDE_CHECKIN_CATEGORY)\ .order_by('enterprise_checkin_ordering').all() for session_type in session_types: Session.objects.create( session_type=session_type, session_number=session_number, family=family) session_number += 1 def _check_guide_checkins_category(): """Check whether the expected session category for guide check-ins exists""" if not SessionCategory.objects.filter(name=GUIDE_CHECKIN_CATEGORY).exists(): logger.error(f"A session category for guide check-ins, '{GUIDE_CHECKIN_CATEGORY}', " "is expected to exist, but was not found in the database.") The problem with this is that the name of each SessionCategory is editable in an internal dashboard. If the name is changed, this function would throw an error, whereas ideally, we would like everything to continue to work as before. For this reason, I'm considering adding a field like original_name, and populating it in a data migration with the name at that time, and using the original_name instead of the name from … -
How to create dynamic form fields from schemas
I'm trying to make a JSON Creator form that is dynamically created based off of a schema chosen by the user. I made an example of how I would want one to more or less look like. Take this given schema: { "type":"object" "properties": "color": { "type": "string", "enum": ["red","green","blue"] }, "unique_id": { "type": "string" "maxLength": 15 }, "workload":{ "type": "object", "properties":{ "write_pre":{ "type": "number", "minimum": -1 }, "read_pre":{ "type": "number", "minimum": -1 }, "required": ["write_pre","read_pre"], "additionalProperties": false } }, "required": ["color", "unique_id"], "additionalProperties": false } I would want my form to look something like this: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static "css/background.css" %}"> </head> <body> <div class="navbar"> </div> <h1>Welcome To The JSONCreator</h1> <form method="post" class="creator"> {% csrf_token %} <h4>color: *required</h4> <select name="color" required> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <h4>unique_id: *required</h4> <input type="text" name="unique_id" required> <h4>workload:</h4> <h5>work_pre: *required</h5> <input type="number" min="-1" name="workloadWork_pre" required> <h5>read_pre: *required</h5> <input type="number" min="-1" name="workloadRead_pre" required> <br><br><input type="submit" value="submit"> </form> </body> </html> My problem is I don't know how I would auto update the form fields to the given property fields given in the schema. I'm planning not to actually write the form with Django's form … -
Serializing a Django Queryset returns wrong data
I'm writing a bit of Javascript for my app and I need to get a queryset to my .js file by serializing to JSON data first and then returning it to the HTML template. I followed the documentation and I thought I got it working the first time but I now realized that the data it returns aren't the same with what there is in the database. Here's my views.py: class DetailView(generic.DetailView): model = Poll template_name = 'voting/detail.html' context_object_name = 'question' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data'] = serializers.serialize("json", Profile.objects.filter(user_id=self.request.user)) return context def get_queryset(self): """ Excludes any questions that aren't published yet. """ return super(DetailView, self).get_queryset().filter( eligiblevoters__user=self.request.user, pub_date__lte=timezone.now() ) """ return super(DetailView, self).get_queryset().filter( eligiblevoters__user=self.request.user, pub_date__lte=timezone.now() ) Basically I'm putting into context a JSON serialized Queryset that contains data about the logged in user from the Profile model. The profile model in models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) encrypted_private_key = models.BinaryField(max_length=500, blank=True) public_key = models.BinaryField(max_length=30, blank=True) salt = models.BinaryField(max_length=16, blank=True) The output serialized data that is accessible in my HTML file is this which looks correct at first but I noticed that even though the user id is correct the fields encrypted_private_key, public_key and salt are … -
how to trigger a django function when the user logout
Hi guys I tried to use django signals to be triggered for five different models but I also have the same models being used in another function an this function import a xml file so it makes my page slow because of the signal and I was wondering if I can change it to a normal function to be triggered when the user click in logout, How it can be done, should I use ajax to do it or there is another way? thanks -
Where is the update method on the BaseUserManager class?
I have the following class that creates a new user and the user has a m2m object located in the kwargs dict and the update creates this error: 'SomeUser' object has no attribute 'update'. class SomeUserManager(BaseUserManager): def _create_user(self, email, password=None, is_superuser=False, **kwargs): if type(kwargs['m2mobject']) is list: m2mobject = kwargs['m2mobject'].pop(0) user = self.model(email=email, is_superuser=is_superuser, **kwargs) if password: user.set_password(password) user.save() user.update(m2mobject=m2mobject) return user def create_user(self, email, password=None, **kwargs): return self._create_user(email, password, is_superuser=False, **kwargs) def create_superuser(self, email, password, **kwargs): return self._create_user(email, password, is_superuser=True, **kwargs) I have to remove this m2mobject from kwargs so that the user can be created first and then through this update method I can add the m2m object to the user. Why won't Django just add the m2mobject so I don't have to remove the m2mobject from kwargs? If I don't do this I get this error Cannot add "m2mobject": instance is on database "None", value is on database "default" Any help would be appreciated. -
Django 2.0 syndication feed not working with Wordpress reader
I followed the following material to create a feed for my site - https://docs.djangoproject.com/en/2.0/ref/contrib/syndication/ https://www.bedjango.com/blog/how-generate-feeds-using-django/ My code is as below class ArticleFeed(Feed): title = "Arushi Pant" link = "/" description = "Always eager to learn. Determined to make the best of the time I've got on Earth." def items(self): return Article.objects.filter(publishedDate__lte=timezone.now()).order_by('-publishedDate')[:30] def item_title(self, item): return item.title def item_description(self, item): return item.shortDescription def item_link(self, item): return reverse('post_detail', args=[item.slug, item.pk]) The feed is online at http://arushipant.pratibimb.co/feed/ I also checked that it was valid here - https://validator.w3.org/feed/check.cgi And it says this is a valid RSS feed. Now, I am trying to follow this blog from Wordpress Reader. The blog gets followed, but there are no posts being shown as published. Is there some other way I should be making feeds if I want others to follow my blog from Wordpress? -
timezone.now() - datetime.timedelta(days=1)
I following django offical tutorials i don't know meaning of this function: class Question(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) It will return TRUE if pub_date is > this time - 1 Day Why TRUE is consider to recently objects? Why it return recently published Questions Objects? What is meaning of datetime.timedelta(days=1) and also timezone.now() - datetime.timedelta(days=1) Thanks. -
Django query filter with model method
I have a model code like: class Person: ... def is_male(self): .... def is_female(self): .... Then, how can I get all the male or female, especially - I just wanted to make a query that getting all males or females. -
How to get the attributes for a query object based on latest timestamp in django?
I have a query object Conversation that has certain attributes.Below is the model defined for it class Conversation(models.Model): timestamp = models.DateTimeField(auto_now=True) context_name = models.CharField(max_length=100) user = models.CharField(max_length=50) type = models.CharField(max_length=10) data = models.TextField(null=True) feedback = models.CharField(max_length=10, null=True) Now I want to access the attributes of the queryset object.If I use the below query serializers.serialize("json", Conversation.objects.all()) I am able to get all the attributes.But if I want the attributes based on a latest timestamp, I am unable to get it.I tried the below query serializers.serialize(queryset = Conversation.objects.latest("timestamp")) I am expecting a JSON for the latest timestamp but I get the error as TypeError: 'Conversation' object is not iterable. However I am able to access the individual attributes like Conversation.objects.latest("timestamp").context_name but not all of them for the latest timestamp. How can I achieve this? -
Python code inside HTML file not working (Django)
I have two templates one is called index.html and the other cart.html. The index.html file accepts python code but if I put exactly the same code in cart.html Python is not recognised. I am working with Django. How can I fix this? Thanks :) -
I'm New on Coding field. How do I connect access to django?
Is possible to connect an access database to django/python web application? If is it, someone could help me providing a script or the code for that connection please. -
Django Rest Framework RelatedField can't return a dict object
I have a serializer and I want to use a serializers.RelatedField so I can manipulate the content of one of the fields of the serializer. I want that field to nest a couple fields from a related table. This is my serializer and the serializer.RelatedField. I want the 'city' field to return a nested object with the 'id' and the 'name' of the related city: class CityRelatedField(serializers.RelatedField): def to_representation(self, value): city = { 'id': value.id, 'name': value.name } return city class AirportSerializer(serializers.ModelSerializer): city = CityRelatedField(queryset=models.City.objects.all()) class Meta: model = models.Airport fields = ('id', 'city', 'name', 'iata') This is the error I get: TypeError: unhashable type: 'dict' Thanks for your help. -
How django sessions work
I am new to django i made a registration page and login page now i want a user registered to login to my website when a user is logged in i want to associate a session for user which only dies when he logs out or he closes the browser now whenever the user loads the page even after a week if the browser is not closed he should be granted access.Now the django is storing sessions in its database but will i be able to authenticate the user as different users have different permissions.can someone suggest any resource for my requirement. -
Unable to view the add screen in Django's Admin panel
I added a field to my database model that was completely unrelated, when I started getting this issue Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/backend/network/add/ Django Version: 2.0.6 Python Version: 3.6.5 Installed Applications: ['backend.apps.BackendConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Template error: In template C:\Users\woode\Documents\RIoT Suite\riot-portal\env\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 'str' object has no attribute 'utcoffset' 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} 14 : {% else %} 15 : {{ field.label_tag }} 16 : {% if field.is_readonly %} 17 : <div class="readonly">{{ field.contents }}</div> 18 : {% else %} 19 : {{ field.field }} 20 : {% endif %} 21 : {% endif %} 22 : {% if field.field.help_text %} 23 : <div class="help">{{ field.field.help_text|safe }}</div> 24 : {% endif %} 25 : </div> 26 … -
AWS RDS Only Accepts Connections from IP Where DB Was Created
Im hooking up my Django app to Postgres, and my initial connect works fine, but when I change my physical location and try connecting again, my connection times out. django.db.utils.OperationalError: could not connect to server: Operation timed out Is the server running on host "****.*******.us-west-2.rds.amazonaws.com" (18.236.40.221) and accepting TCP/IP connections on port 5432? What am I missing? -
Keep file name when uploading to a FileField in Django
In one of my models, I have an ImageField (which is basically a FileField, but with a couple extra tidbits). I specify an upload location with the following: class MyModel(models.Model): image = models.ImageField(blank=True, null=True, upload_to='path/to/directory' When I save an image to this ImageField, I use the following: with open(original_image.path) as image_file: image_temp = ContentFile(name=os.path.basename(original_image.path), content=image_file.read()) my_model.image = image_temp Unforturnately, this renames the file from what it was originally to 'directory.' Now this wouldn't be so much of a problem, but I need to keep the original extension of the image. How can I keep the original file extension? -
Type error after importing custom class in Django
I have test.py file with a python class added. class code looks like this. class foo: def __init__(self,firstname,lastname): self.fname = firstname self.lname = lastname self.email = firstname + "." + lastname + "@test.com" def Get_Fullname(self): return self.fname+ " " + self.lname test.py file is directly under the app folder. my view.py file look like this from django.views.decorators.csrf import csrf_exempt from test import * @csrf_exempt def New_Function(): myFunc = foo('Test','User') return HttpResponse(myFunc.Get_Fullname()) added the below into urls.py urlpatterns = [ url(r'^$','app.views.home',name='home'), url(r'^functionCall/','app.views.New_Function'), ] in java-script i have $(document).ready(function(){ $.ajax( { url: '/functionCall/', method:'POST', success: function(response){ console.log(response) } }); }); when i load my page i'm getting TypeError at /functionCall/ and New_Function() takes no arguments (1 given) What am i doing wrong over here, new thoughts are appreciated. -
Multiple Model Seralizer
class SongsSerializer(serializers.ModelSerializer): artist_name = Artist.objects.name genre_name = Genre.objects.name class Meta: model = Song fields = [ 'pk', 'album', 'art', 'title', 'song', 'artist', 'slug', 'genre', ] read_only_fields = ['id'] Serializer.py So have 3 type of model classes and each one have some foreign key relation class Song(models.Model): album = models.ForeignKey(Album,on_delete=models.CASCADE) title = models.CharField(max_length=250) song = models.FileField(upload_to='songs') slug = models.SlugField(max_length=250,default='') genre = models.ForeignKey(Genre,on_delete=models.CASCADE) artist = models.ForeignKey(Artist,on_delete=models.CASCADE) JSON response of the API is: {pk: 1, album: 1, art: "http://localhost:8000/media/art_music/pp_PAgznjI.jpg", title: "Test", song: "http://localhost:8000/media/songs/Daaru_Band_-_Mankirt_Aulakh_DJJOhAL.Com_CtS7TAv.mp3", …} Instead of showing Artist and Genre as 1, it should show the name of the Album, Artist and Genre -
Django performance: Defining var in for loop vs first()
In my for loop, I am defining currency & event. While I am performing some tasks in this for loop where I need a for loop, currency and event will always be the same as it is the same order. I now wonder should I still do it that way, or would it be better to access event & currency before separately with a ReservedItem.objects.filter(order_reference=session_order_reference).first()call? reserved_item = ReservedItem.objects.filter(order_reference=session_order_reference) for i in reserved_item: currency = i.ticket.event.currency event = i.ticket.event [...] -
Django: redirect doesn't work as expected
I want to redirect the user if session_order_reference is empty. However, Django is still running till i.ticket.event.currency which brings an error local variable 'currency' referenced before assignment. I thought once I call redirect it will stop there and just redirects the user. Am I wrong there? def checkout_page(request): session_order_reference = request.session.get('order_reference') if not request.session.get('order_reference'): redirect('website:index') # TODO Marc: Better change to direct event link reserved_item = ReservedItem.objects.filter(order_reference=session_order_reference) d = {} total_amount = total_tax_amount = 0 order_item_data = [] for i in reserved_item: currency = i.ticket.event.currency -
Error Execution Celery - Django - CentOS
I deploy my website on CentOS server and i have an error that was not seen yet on help forums. My config : Python = 3.6.5 Django = 2.0.6 Kombu = 4.2.1 celery = 4.2.0 settings.py Only the part of celery # Configure Celery BROKER_URL = "pyamqp://" BROKER_POOL_LIMIT = None CELERY_RESULT_BACKEND = "redis://localhost" init.py The init file in MYSITE/MYSITE. I put the DEBUG settings here because in my prod env, MYSQLdb is not surported with mariaDB. from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .settings import DEBUG from .celery_settings import app as celery_app __all__ = ['celery_app'] if DEBUG == False: import pymysql pymysql.install_as_MySQLdb() celery_settings.py The celery settings file in MYSITE/MYSITE. from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MYSITE.settings') app = Celery('MYSITE') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app …