Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference between OData and Django rest framework
I am having a hard time understanding or figuring out if there is any difference between using OData instead of Django rest framework. I've studied django's rest framework but just found out about OData and was wondering if there is much to be gained in using it instead of django or is it just a different way of doing things? -
How to add additional keyword argument to all Django fields?
The application I am working on requires merging of identical type Django models. These models hold state that can be altered by chronological events, so it is not as straightforward as deep copying one object to the other, as it is not always correct to take the latest value or always copy truthy values for example. I have written a customer model merging class to handle this operation, however, I need to be able to describe on a field by field basis whether it should be included in that merge and if it is to be included, how to handle that merge. I have already tried creating a dictionary to describe this behaviour and pass it into the merger. However, this becomes unwieldy at greater levels of nesting and is very brittle to codebase change. I have also tried adding a merge method to each individual model, which solved the problem but highly susceptible to failure if a foreign key relationship that lives on a different model is missed, or the codebase changes. I have started writing a custom version of every field in Django, as the fields feel like the correct place for the logic to live, but it … -
How do I make a post request to a Django ManyToManyField? (Json Array)
I have an API that has an array of other objects that all has a name, like this: [ { "id": 1, "title": "Push Workout Bjarred", "description": "Kör Hårt!", "exercises": [ { "name": "Tricep Cable Pushdown" }, { "name": "Delt Side Raises" }, { "name": "Delt Barbell Press" }, { "name": "Chest Cable Flyes" }, { "name": "Barbell Bench Press" } ], "cardio": [ { "name": "Stairmaster", "time": 12 } ] }, { "id": 2, "title": "Pull Workout Loddekopinge", "description": "", "exercises": [ { "name": "Bicep Cable Curl" }, { "name": "Back Barbell Row" }, { "name": "Back Pullback Machine" } ], "cardio": [ { "name": "Bike", "time": 10 } ] } ] How do I make a post request that includes which exercises to include? The exercises are from another Api (pretend that I have those locally, that I have made a get request previously to get them) - Lets say I select exercises from a list and add them to the parameters to make a post request! If Someone could show how to do this in any type of post request it would help loads, postman, flutter, Xcode, (other...) -
How add some css in stored values with django autocomplete-light?
I overrided get_results method of autocomplete-light as follow to have single tag in bold: views.py class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self, **kwargs): qs = Tag.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs def get_results(self, context): results_list = [] for result in context["object_list"]: text2show = "{}" tag_occurrences = result.org_set.count() if tag_occurrences == 1: text2show = '<b>{}</b>'; results_list.append({ "id": self.get_result_value(result), "text": format_html(text2show, self.get_result_label(result)), "selected_text": format_html(text2show, self.get_selected_result_label(result)), }) return results_list Everything works perfectly if I search a tag, but if I try to view a stored event, all its tags are represented without any style. forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = "__all__" widgets = { 'tags': autocomplete.ModelSelect2Multiple(url='myapp:tag-autocomplete', attrs={'data-html': True}) } def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # if I try to edit an event if self.instance: # self.fields['tag'].queryset = ??? And this is a piece of my template: <form method="post" class="form-horizontal"> {% csrf_token %} {% for field in myform %} <div class="form-group form-group-lg"> <label for="{{ field.id_for_label }}" class="col-sm-4 control-label">{{field.label}}</label><div class="col-sm-4"> {{ field }} </div> </div> {% endfor %} {{ myform.media }} </form> Is there a way to manipulate self.fields['tag'].queryset queryset to show field names in bold or another elegant solution? Thanks. -
django how to test that data from session was saved to model correctly
In a current django project I have a view which saves data from the session into a series of models. What is the best way to test that in django as testing with the client merely returns the response (and the session). Should I make calls to the db in the test and verify against the response? eg in the view I have: user = User.objects.create_user(username=request.session['profile']['email'], email=request.session['profile']['email'], password=request.session['profile']['password'], **user_fields) -
Django Swagger Rest API, tryit now function when api is on different server to ui
I am trying to document our Django Rest API using Django Swagger Rest API where our API is on different server to UI Trying to change the TryIt now URL for the curl request as the API is on a different server to the UI I have tried setting url in get_swagger_view, but this appends ui url before this url I have tried changing base_path in SWAGGER settings but nothing works -
Django- Field appears as Null
I want to show the name of a field and not the ID of it, so I tried a couple of different methods but with nothing worked for me. I couldn't figure out why or find a suitable solution for this, so here it goes: Basically, my views returns a null field when in fact it is not null. Code bellow. tags = TagListSerializer() # Returns null tags = serializers.Field(source='tags.name') # Returns null tags = TagListSerializer # Doesn't change anything Comercial inherits from Project which is abstract: class Comercial(Project): name = models.CharField() Project is abstract: class Project(models.Model): tags = models.ManyToManyField(Tag, blank=True, editable=True) The Tag Model: class Tag(models.Model): name = models.CharField() The Comercial View which searches by tag: class ListComercialAPIView(ListAPIView): serializer_class = ComercialListSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): tag = self.request.GET.get('tag') if(tag!=None): return Comercial.objects.filter(tags__name=tag) else: return Comercial.objects.all() The Tag Serializer: class TagListSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('__all__') And finally the ComercialSerlialzier: class ComercialListSerializer(serializers.ModelSerializer): tags = TagListSerializer() class Meta: model = Comercial fields = ('name', 'tags') At listing the Comercial object I expected something like this: { "name": "Example Comercial Name" "tags": { "name":"Example Tag Name"} } But all i get is: { "name": "Example Comercial Name" "tags": { … -
Seek not working when multiple HTML5 Audio files are on the same page
I have multiple HTML5 Audio players loading different sources within a for-loop on the same page. The audio players work perfectly and are playable but when seeking to a specific position, the audio restarts. I am unable to seek at all. Whether I'm using the HTML5 audio player or an audio library such as plyr. After some debugging, I concluded the issue is due to having multiple HTML5 Audio players on the same page. Seek works fine with one audio player but anymore on the page, as I'm doing in my for-loop, breaks it. What is the best solution around this? I'm using Django 2.2 but I'm confident that is not related to the issue. See my code below - {% for song in songs %} <div class="col-lg-6 col-md-12 mb-4"> <div class="card shadow-sm"> <div class="card-body"> <h4 class="card-title mb-4">{{ song.title }}</h4> <div class="row mb-2 px-3"> <div class="col-md-12"> <audio id="{{ song.id }}" class="js-player" preload="auto" autobuffer controls> <source src="{{ song.song.url }}" type="audio/mp3" /> <source src="{{ song.song.url }}" type="audio/ogg" /> </audio> </div> </div> </div> <div class="card-footer"> <div class="float-left text-left"> <a data-toggle="modal" data-target="#{{ song.id }}"><i class="fal fa-info-circle ml-3"></i></a> </div> <div class="float-right text-right"> <a href="{{ song.song.url }}" download>Download <i class="fal fa-cloud-download-alt ml-3"></i></a> </div> </div> </div> </div> … -
Django: How to organize migration for two related models and automatically set default field value for id of newly created object?
Suppose there is a production database, there is some data in it. I need to migrate in the next tricky case. There is a model (already in db), say Model, it has foreign keys to other models. class ModelA: ... class ModelX: ... class Model: a = models.ForeignKey(ModelA, default = A) x = models.ForeignKey(ModelX, default = X) And we need to create one more model ModelY to which Model should refer. And when creating a Model, an object should have some default value related to some ModelY object, which is obviously not yet available, but we should create it during migration. class ModelY: ... class Model: y = models.ForeignKey (ModelY, default = ??????) So the migration sequence should be: Create ModelY table Create a default object in this table, put its id somewhere Create a new field y in the Model table, with the default value taken from the previous paragraph And I'd like to automate all of this, of course. So to avoid necessity to apply one migration by hands, then create some object, then write down it's id and then use this id as default value for new field, and only then apply another migration with this new … -
How to define 'set_password' attribute for models.Model
I'm new to Django and this is my first time creating a web application using the framework. My web app has 3 user types: client, supervisor, and contractor. These 3 users are connected to a custom User model through a OneToOneField called 'user'. (My custom User model subclasses AbstractBaseUser) I've created the database tables and run migrations, done all the initial to-do's, etc. but when I try to create a Client user (which subclasses models.Model) for my web app, I get the following AttributeError: 'Client' object has no attribute 'set_password'. I've seen some solutions that suggest either defining your own set_password attribute (being that models.Model has no such attribute), or subclassing AbstractBaseUser. I would like to try the first option, however, I'm a little stumped as to how to define the 'set_password' attribute for my model. P.S: please feel free to point out any other errors in my code. models.py: from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser from django_countries.fields import CountryField from django.contrib.auth.base_user import BaseUserManager from myproject import settings # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Email must be set!') user = self.model(email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, … -
ValueError: Cannot serialize: jdatetime.datetime() in django
I installed django-jalali package in order to be able to use the Jalali calendar. The package worked well, and I could run it until I want to change fields that record was already in place.but when I wanted to change that fields I got this error: ValueError: Cannot serialize: jdatetime.datetime(1398, 3, 10, 18, 17, 10, 557480) There are some values Django cannot serialize into migration files. what's wrong? And how can I fix that? -
Is there a way to get full debug info in the production environment without mail_admins handler?
When debug = False, we can configure logging and enable mail_admins handler to get the full traceback in the email. Is there any way to get that informations without configuring email settings? -
How to limit model instances in django?
I'm creating a subscriber service. In this service a user can have limited number of subscriptions. Consider two models: class Channel(models.Model): name = models.CharField(max_length=20) class User(models.Model): subscriptions = models.ForeignKey(Channel) I want to limit number of subscriptions to "2". One approach I know about is using pre_save signal and raising error. Is there any more "django" way for achieving this (like doing something in models)? -
the issue is probably caused by a circular import
i'm trying to runserver for a django project and it shows me this error : The included URLconf 'Smartfarmer.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. eventhough the same project works fine in another envirenement i've tried to check if there are any mistakes in urls but i believe everything is fine my urls file of the project : from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from main_app import views urlpatterns = [ url(r'^admin/',admin.site.urls), url(r'^', include('main_app.urls')), url(r'^detect/', include('detect.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) my urls for my apps : from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), ] from django.conf.urls import url from . import views urlpatterns = [ url(r'^result/$', views.result, name='result'), ] -
How to implement datatables server-side pagination in Django app
I need server-side pagination + individual column search for my django project. Sadly I was not able to implement the pagination. I searched a lot for working examples but did not find any. I want to implement my server side api myself, there are some django apps but they seem not the be maintained anymore. Following is my datatables code + django view. Anyone here who could give me some advice? var table = $('#mainTable').DataTable({ dom: 'Bfrtip', responsive: true, serverSide: true, processing: true, pageLength: 25, buttons: [ 'csv', 'print', { extend: 'colvis', text: 'Spalten filtern', columns: ':not(.noVis)' }, ], ajax: { url: '/akquise/mainTableData', dataSrc: function ( json ) { return json; } }, columnDefs: [ { targets: [0,1,2,3,4,5,6,7,8,9], orderable: false}, { targets: 0, className: "leadID", searchable: false }, { targets: 3, className: "firmenname" }, ], columns: [ { data: "leadID", render: function ( data, type, row, meta ) { button = '<a role="button" class="btn btn-secondary" target="_blank" href="details?leadID='+data+'"><i class="fas fa-search"></a>'; return button } }, { data: "leadID"}, { data: "status", render: function ( data ) { if(data == "Lead"){ return "<span class='badge badge-primary'>"+data+"</span>"; } if(data == "Kunde"){ return "<span class='badge badge-info'>"+data+"</span>"; } if(data == "Akquise"){ return "<span class='badge badge-warning'>"+data+"</span>"; } if(data … -
How do I highlight active link of navbar?
I don't know how do I highlight the active link of navbar. This is my solution but it didn't work: navbar.html included in base.html: <nav class="navbar navbar-expand-sm bg-light navbar-light border-bottom" style='right:0px;'> <!-- Brand --> <a class="navbar-brand" href="{% url 'blog:home' %}">Logo</a> <!-- Links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link {% block home_active %} {% endblock home_active %}" href="{% url 'blog:home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link {% block blog-active %} {% endblock blog-active %}" href="{% url 'blog:blogs' %}">Blog</a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link {% block create-active %} {% endblock create-active %}" href="{% url 'blog:blog_create' %}">Create</a> </li> {% endif %} <!-- Dropdown --> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown"> Dropdown link </a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Link 1</a> <a class="dropdown-item" href="#">Link 2</a> <a class="dropdown-item" href="#">Link 3</a> </div> </li> </ul> </nav> as you can see I added something like {% block home_active %} {% endblock home_active %} in every single links and then added active in templates as home.html: {% block home_active %} active {% endblock home_active %} I am wondering why this active class is not applied on these links when I click every single link. Please help me with this. thank you -
How to Internally redirect from home page to Catalogue page in Django-oscar?
I'm using Django-oscar for my project. After Django-oscar config, I can see localhost:8000 empty, Instead, I want to redirect to localhost:8000/Catalogue Page urls.py urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^admin/', admin.site.urls), url(r'', application.urls), ] I expected output is. when i run localhost:8000 it should take to localhost:8000/catalogue -
I want to retrieve auth code to take access_token using python 3
I'm getting error from server side. I need to take auth code to variable to get access to the access_token using python 3 -
How can i change status to 'ingedient'
I want to change status from 'Niet ingedient' to 'ingedient' with a button click. I have created a script but I keep getting an error. Does someone know how I can fix this error? Error: Reverse for '' not found. '' is not a valid view function or pattern name. view.py def indienen(request, id): global Weekstaat weekstaat = Weekstaat.objects.get(pk=id) Weekstaat.status = 'Ingedient' weekstaat.save() return redirect(request, 'weekstaat/index.html') -model class Weekstaat(models.Model): id = models.AutoField(primary_key=True, null=False, blank=False) status = models.CharField(max_length=11, choices=STATUS_CHOICES, default='Niet ingediend',) jaar = models.ForeignKey(Jaar, default=datetime.now().year, null=False, blank=False,on_delete=models.CASCADE) week = models.ForeignKey(Week, default=date.today().isocalendar()[1], null=False, blank=False,on_delete=models.CASCADE) werknemer = models.ForeignKey(User, related_name='weekstaat_werknemer', null=False, blank=False, default=1,on_delete=models.CASCADE) maandag = models.FloatField(null=True, blank=True, default=0) dinsdag = models.FloatField(null=True, blank=True, default=0) woensdag = models.FloatField(null=True, blank=True, default=0) donderdag = models.FloatField(null=True, blank=True, default=0) vrijdag = models.FloatField(null=True, blank=True, default=0) zaterdag = models.FloatField(null=True, blank=True, default=0) zondag = models.FloatField(null=True, blank=True, default=0) def __str__(self): return str(self.jaar) + ' week ' + str(self.week) + str(self.werknemer) + str(self.status) -html indienen </td> <td class="text-center"> <button type="button" class="read-Contract btn btn-sm btn-primary" data-id="{% url 'read_Weekstaat' Weekstaat.id %}"> <span class="fa fa-eye"></span> </button> <button type="button" class="update-Contract btn btn-sm btn-primary" data-id="{% url 'update_Weekstaat' Weekstaat.id %}"> <span class="fa fa-pencil"></span> </button> </td> </tr> {% endfor %} </tbody> </table> {% else %} <p class="text-primary">U heeft nog geen Weekstaat</p> {% … -
I could not get any source to understand about serializers and mixins in django with detailed examples
I am a beginner in the django framework . I have tried a lot of time but confused about how serializers and mixins used and work. I did not get any source examples so that I can understand it completely. -
How to store Json Array in Django where Database is mongoDB
I am using django with backend as mongoDB using djongo I want to write a model for storing below schema... { "id" : 101, "timestamp" : "utc(12/05/2019:T)", "readings" : [ { "bod" : 12, "cod" : 25, "cod" : 16, "flow" : 45, }, { "bod" : 2, "cod" : 2, "cod" : 17, "flow" : 25, } ] } -
How to run migrations in AWS Code Deploy without generating deadlocks?
The codebase of my app is written in Django and the deployment pipeline is in AWS. Using the Code Pipeline of AWS with: Code Deploy and Code Build services. The problem is when running the database migrations, deadlocks are popping up because of the other EC2/ECS2 services/containers that are still running while migrating. How can I stop all the ECS containers and prevent them from starting up until the migration has completed ? A solution would be to create another step in the Code Pipeline before the migrations step and use aws-cli to set the number of tasks for each ECS service to 0 and somehow wait until all of them are stopped. After that run the migrations and change back the ECS services. Is there a better, easier solution than using aws-cli and creating custom scripts ? The deployment pipeline should first stop all the other services, run the migrations and then start all the services. Downtime is not an issue in this case. -
Cannot define 'through' relationship on two models which share a base class in Django
I've got a 'set' model, which has a many to many relationship to the 'Item' model. The issue is that 'set' is a subclass of Item (everything is an Item on the project). It works fine, until I try to create a 'through' relationship to an intermediary model called 'order', which I'm defining so I can order the 'Items' inside the 'Set'. When I try to define the relationship, I get this error: ERRORS: curate.Set.items_: (fields.E001) Field names must not end with an underscore. curate.order.set: (fields.E304) Reverse accessor for 'order.set' clashes with reverse accessor for 'order.item'. HINT: Add or change a related_name argument to the definition for 'order.set' or 'order.item'. I've tried adding a related_name to Order.set, and also Order.item, but it doesn't seem to work. I can get migrations to be happy, but then when I try to migrate I get an error saying: ValueError: Cannot alter field curate.Set.items into curate.Set.items - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields) models.py class Item(models.Model, AdminVideoMixin): title = models.TextField(max_length=5000) slug = models.SlugField(max_length=5000, default='') ... class Video(Item): video_embed = EmbedVideoField(max_length=500) ... class Article(Item): authors = models.CharField(max_length=10000) ... class Podcast(Item): … -
KeyError at /url/ on Django site in prod. Not seen on local server. Using Django session
I need to save data for a session in django and perform some action when user clicks on a button. I am storing the data processed after a query in django sessions. This was working well and good on my local server even after I tried hitting the server simultaneously from different sessions at the same time. However when pushed to prod, this shows key error at /url/ the second time onward when I hit the site. The data serves fine on the first go. I looked up some solutions and have tried adding SESSION_ENGINE as "django.contrib.sessions.backends.cached_db". I have added SESSION_SAVE_EVERY_REQUEST = True in settings.py. I also tried savng data for every session key separately, which did not work either. I am saving the data to sessions like this: request.session['varname'] = varname and retrieving it the same way: python varname = request.session['varname'] Expected behavior would be successful retrieval of session data every time like on local server. However on prod, the data is not retrieved after the first time. -
Mode ID not serialized in django DRF response
Is it possible to serialize unique ID of the model within Django DRF? I have a view which generates dummy user for testing purposes: @api_view(['GET']) @permission_classes((permissions.AllowAny, )) def user(request): email = 'dummy@example.com' try: user = User.objects.get(email=email) except User.DoesNotExist: user = User.objects.create_user( email=email, first_name='Jane', last_name='Doe' ) user_data = { 'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name } serialized = UserSerializer(data=user_data) if not serialized.is_valid(): raise Exception(serialized.errors) return Response(data=serialized.data, status=status.HTTP_200_OK) And a user serializer which serializes the user model: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name') However, when I try to send request, the response only contains first_name and the last_name. I've tried implementing this solution, but it only works with calculate values (since obj passed to custom method is in this case OrderedDict([('first_name', 'Jane'), ('last_name', 'Doe')])) - id value is not passed to the method. I've tried adding read_only_fields but it does not work.