Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve excluded form fields in ModelAdmin?
I have a simple CategoryForm which has a hidden field that automatically gets added during save on the front-end. In the Admin panel I would like is_staff users to be able to add a Category while the field is hidden there as well. To superusers I would like the field to be shown. How do I get the excluded fields back in my Admin form? Forms.py: class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ('category', 'company',) exclude = ['company'] widgets = {'company': forms.HiddenInput()} Admin.py: class CustomCategoryAdmin(admin.ModelAdmin): form = CategoryForm def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) if not request.user.is_superuser: self.fields = ('category',) else: self.fields = ('category', 'company',) # this throws a key error because company is excluded return form def get_queryset(self, request): qs = super(CustomCategoryAdmin, self).get_queryset(request) if not request.user.is_superuser: return qs.filter(company=request.user.company) return qs.all() # To add company to company field while saving def save_related(self, request, form, formsets, change): super(CustomCategoryAdmin, self).save_related(request, form, formsets, change) company = request.user.company form.instance.company.add(company) -
Legacy Rails database in Django - Generic Relations - Object queries
I'm migrating a rails app to django. I am currently having some chalanges with relations and filters. There is a Posts table and a Articles table. They have categories trough a Categorizations table. The Categorizations table has categorizable_type,categorizable_id and category fields. So I can see in a existing Categorizations instance that the categorizable_type=Post and categorizable_type=Article and with the categorizable_id set to a eighter or... I've found the documentation for Django Generic Relations and it seems like thats basically whats in use. But I am not able to run any migrations on the database at this time. So I am wondering how I could make this work so I could do standard object filtration queries. Here is a example of the setup: class Articles(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=1000) class Posts(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=1000) class Categorizations(models.Model): id = models.BigAutoField(primary_key=True) category = models.ForeignKey(Categories, models.DO_NOTHING, blank=True, null=True) categorizable_type = models.CharField(max_length=1000, blank=True, null=True) categorizable_id = models.BigIntegerField(blank=True, null=True) So I would like to be able to do something like this: acticles_in_category_2 = Articles.objects.filter(categorization__catogory.id=2) The constrait is that I cant do any structural changes or migrations on the existing database. For now it looks like I might have to get around this … -
Why this Django Views decorators running reverse order?
there are 3 decorators: def a(view): def wrapper(request, *args, **kwargs): import time print("a") print(int(time.time())) time.sleep(1) return view(request, *args, **kwargs) return wrapper def b(view): def wrapper(request, *args, **kwargs): import time print("b") print(int(time.time())) time.sleep(1) return view(request, *args, **kwargs) return wrapper def c(view): def wrapper(request, *args, **kwargs): import time print("c") print(int(time.time())) time.sleep(1) return view(request, *args, **kwargs) return wrapper and decorated view: @c @b @a def hello(request): return HTTPResponse("hello\n") normally, it means below: c(b(a(hello()))) but it running below: a(b(c(hello())) it is OK for my task. i just using reverse. but so funny... do you know why it's mistaken? -
How can I draw a pigeon pedigree using HTML and CSS? Are there other ways to do that like jQuery or something else?
I develop a web app using python and django for managing pigeons and I want to draw their pedigrees. How can I do that? Which technologies I should use? -
How do i add HTML classes to built-in 'User' model? (Python Django)
I want to add some HTML classes to set of built-in Django model User that imports from from django.contrib.auth.models import User. I searched this information about 1 day, and found nothing. All answers only applicable to self created models, not User model. -
Django newbie's tragedy
Ok, first thing- I'm awful in programming (in all aspects) but I've to do this till monday so I'm trying my very best. My target is creating a website, that takes text (fragment of lyrics or title of song) and search for it in database (I'm using a .csv one). But no matter what I try I will end with "403 Forbidden". I'll be really frateful for any help html template forms views -
How to create an instance of a model through foreign key
I'm trying to find a way how to create or update an instance of a model through a foreign key. I have two models: Podcast and Guest which are connected via foreign key on guest_name. I'm using Youtube API to pull data from videos and regex to extract data needed for a set of fields in both models. I'm wondering if there to pass guest_name from Podcast model (which would be extracted via calculated filed in Podcast model) to Guest model and create or update (search via 'WHERE LIKE '%guest_name%') its instance on the creation of Podcast instance? Thank you for all the help class Guest(models.Model): guest_name = models.CharField(max_length=30) #full name occupation = models.CharField(max_length=20) short_bio = models.TextField() def __str__(self): return self.guest_name def get_absolute_url(self): return reverse("roll:guest_detail", kwargs={'pk':self.pk}) class Podcast(models.Model): category = models.CharField(max_length=255) # Needs to be a Dropdown date = models.DateTimeField(blank=True, null=True) #published date guest_name = models.ForeignKey(Guest, on_delete=models.CASCADE) # https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_one/ synopsis = models.TextField() index = models.IntegerField(blank=True,null=True,unique=True) video = EmbedVideoField(help_text="Remove anything after the Video ID",blank=False) # same like models.URLField() thumbnail_url = models.URLField(help_text="URL to the image",blank=True) # slug = models.SlugField(max_length=140, unique=True) # video_id = re.search('(\?v=)(.*)', self.video) # thumbnail = models.CharField(max_length=100,default="https://img.youtube.com/vi/{}/0.jpg".format(str(save(video)))) @property def thumbnail(self): video_id = re.search('(\?v=)(.*)', self.video) return 'https://img.youtube.com/vi/{}/0.jpg'.format(video_id.group(2)) @property def publishedAt(self): api_key … -
Am I overriding the save method on the model in a wrong way in django?
I am have a Profile model that extends the user model like so, class Profile(User): user = models.OneToOneField(User, parent_link=True, on_delete=models.CASCADE) slug = models.SlugField(unique=True, blank=True) def save(self, *args, **kwargs): print('self.username') print(self.username) self.slug = self.username super(Profile, self).save(*args, **kwargs) I am trying to create a slug field for my model , so I override the save method to include the slug as the username of the user, the thing is when I create a new user with the command createsuperuser and print out the username of the user as you can see in the code .. it doesn't show anything , it doesn't show the provided username could this be the reason why I am having this problem ? of so how can I fix it ? -
How to render custom column on django-datatable-view
I'm having trouble finding the correct way of rendering HTML <h6> tags within django-datatable-view columns to use material.io icons as the content of the said column. I've referred to numerous resources including this, which seems outdated and unfortunately the closest I could get to having rendering some custom columns. Here's how my datatable definition looks like: class LeaveDatatable(Datatable): class Meta: columns = [ 'status' ] def render_colum(self, row, column): if column=='status': if row.status == 'Verified': #render-some-icons else: #render-another-icon class LeaveReview(DatatableView): model = Leave datatable_class = LeaveDatatable def get_queryset(self): return Leave.objects.filter(employee__id=self.request.user.id) Technically, what im trying to achieve is, if status == 'Verified', render <h6 class="material-icons col-sm text-center" style="color:green;" id='fulfilled-icon'>check_circle</h6> in the status column. Appreciate any help. Thanks! -
Django rest framework - how to use different model only for listView
I'm using Djano 2.1.5 with Django rest framework 3.7.7. I'm using ModelViewSet, i.e the relation between the view and the model is by routing with base_name and the serializer_class in the view. Now, for some reason, I want to create a database view for retrieving some calculated fields on 'list'. This view should be connected to a new model that is not managed (managed=False). My question is how can I connect between the new model and the listView specifically (and not other views of that model). my urls.py: router.register( r'container/(?P<container_id>[^/]+)/item/?', views.ItemViewSet, base_name='items') the item view: class ItemViewSet(viewsets.ModelViewSet): serializer_class = ItemSerializer I want to create a new unmanaged model that will look something like: class ListItemModel(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True) calc_field = models.IntegerField(default=0) class Meta: managed = False db_table = 'list_item' So the question is how can I connect between the new model and the item listview? -
Django : Create custom object list in the view and pass it to template to loop over
I want to create a custom object list in the view and pass it to the template. In the template I want to loop over the list and display the information. My models are class CustomUser(AbstractUser): def __str__(self): return self.email class Post(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_url = models.URLField(max_length = 200, blank = True) slug = models.SlugField(unique=True, blank=True) class subscription(models.Model): creator = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='creator',) booster = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='booster') sub_value = models.FloatField(blank = True) sub_id = models.TextField(blank = True) status = models.BooleanField(default=False) dateSubscribed = models.DateTimeField(default=timezone.now) dateSubscriptionEnded = models.DateTimeField(default=timezone.now) paymentCount = models.FloatField(default= 0) I want to filter objects from subscription model like below subs = subscription.objects.filter(booster = request.user) Then find creators in the above subs object list and for each creator get the name, numbers Posts, and number of Subscribers. Add this to custom list and pass it to the template to loop over and display the information in the template. Can someone help me how to create this custom list. Thanks! -
How to set up the base language for a Django project i18n?
I have a Django project in spanish and I want that language to be the base language for localization. The Django documentation shows that it is possible, here. But doesn't explain how. -
Django Rest Framework many-to-many relation create the link
Since there are a few questions about m2m and DRF I'll try narrow down what specifically I'm interested in. Let's call the two models 'article' and 'publication'. Assume that: The 'publication' object already exists. The 'article' object may or may not exist. specifically: a) If a previous publication contained the article, then it will already be there. b) If not, then the article will need to be created. I want to send a post http request with the article data in the body and the publication id available from the url which will: a) if the article already exists, link it to the publication b) if the article does not exist, create it, and then link it to the publication Going for the 'default' strategy below did not work out. I can think of two ways to approach this problem: Overriding the create method on the article serializer. However I'm scepticle of doing that since this seems like a problem that should be common and have a non-custom solution. Creating an endpoint to directly work with the 'through' model. I could then split up the process into two steps (and 2 requests) where I first get_or_create the article, and then … -
Django TypeError unsupported operand type(s) for %: 'tuple' and 'dict'
I made a base model. And I want to inherit it and makemigrations model. But I catch an error. I don't understand the cause. I want you to tell me if you understand. from django.db import models from apps.models.commons import User from django.utils import timezone from django.utils.translation import gettext_lazy as _ import uuid class AbstractModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_user = models.ForeignKey(User, _('created_user'), related_name=('created_user',), editable=False) updated_user = models.ForeignKey(User, _('updated_user'), related_name=('updated_user',)) created_at = models.DateTimeField(_('created_at'), default=timezone.now, editable=False) updated_at = models.DateTimeField(_('updated_at'), default=timezone.now) class Meta: abstract = True from django.db import models from apps.models.commons.accounts import User from apps.utils.models.abstract import AbstractModel from apps.utils.models.region import CityModel from django.utils.translation import gettext_lazy as _ class Cast(AbstractModel): """Cast Model""" class Meta: db_table = 'Cast' image = models.ImageField(upload_to='aaa', default='profile/default.png') name = models.CharField(_('name'), max_length=30, blank=True) introduction = models.CharField(_('self introduction'), max_length=150, blank=True) establishment = models.DateField(_('establishment'), blank=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name -
UserCreationForm VS AbstractForm
What is the difference between AbstractForm and UserCreationForm ? Do I still need to code more to override make my custom form. Why do mention in class Meta that the model I use is User Model when using UserCreationForm ? -
Python 3 on Django 2 throws a UnicodeEncodeError
On my Django 2 / Python 3 project I get a UnicodeDecodeError when uploading an image to the server. Interestingly I don't get this error on my development PC. I only get this on the staging server. views.py if request.method == "POST": image = request.FILES.get("avatar") user.avatar = image user.save() # <-- Error is thrown here my locale setup on the server LANG=en_GB.UTF-8 LANGUAGE= LC_CTYPE="en_GB.UTF-8" LC_NUMERIC="en_GB.UTF-8" LC_TIME="en_GB.UTF-8" LC_COLLATE="en_GB.UTF-8" LC_MONETARY="en_GB.UTF-8" LC_MESSAGES="en_GB.UTF-8" LC_PAPER="en_GB.UTF-8" LC_NAME="en_GB.UTF-8" LC_ADDRESS="en_GB.UTF-8" LC_TELEPHONE="en_GB.UTF-8" LC_MEASUREMENT="en_GB.UTF-8" LC_IDENTIFICATION="en_GB.UTF-8" LC_ALL= on manage.py shell I get this: Python 3.5.2 (default, Oct 8 2019, 13:06:37) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import sys >>> sys.stdout.encoding 'UTF-8' >>> And this is the error: UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 75: ordinal not in range(128) I also have included # coding=utf-8 on all my python files. My code seems to be OK, because the same image (filename is: Vs_Filemón.png) uploads fine on my development machine. So, I guess there must something broken on my staging machine which is this: No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 16.04.6 LTS Release: 16.04 Codename: xenial -
How to associate foreign keys model in HTML
I am writing portal to manage tasks , i have created following models shown below and in addition following view shown below , in the HTML(shown below ) i have section i display recent tasks last 30 days, when i am looping on each main task that can have multiple sub tasks i would like for example to show sub task associated users and details , i know how to get data from main model class data, but i don't know how to retrieve data associated form foreign Key sub model to its main model. for example how do i display all users for sub task associated to main task task_assign = models.ForeignKey(User, on_delete=models.CASCADE, related_name="task_assign",default=1) or any other related like all sub tasks descriptions associated to main task for example task_description = models.CharField(max_length=200) Please advice Thanks view class class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) #filter active runing tasks context['active_tasks'] = MainTask.objects.filter(complete=False).count() #All oobjects main Task context['maintask'] = MainTask.objects.all() #All objects Subtask context['childtask'] = MainTask.item_main.all() #filter task due date #due_range = context['due_task'] = MainTask.objects.filter(due_date__day__lte=7, complete=False).count() #task paused context['task_paused'] = MainTask.objects.filter(task_status='PA', complete=False).count() #task paused context['task_completed'] = MainTask.objects.filter(task_status='CO', complete=True).count() #task paused context['task_started'] = MainTask.objects.filter(task_status='NS', complete=True).count() ###query for … -
Best Practises for Storing Email Templates in Django
I was wondering what's best practise for storing email templates in terms of project structure. I don't like the idea of having them in the same directory as your normal templates. I can imagine it can be quite hard to differentiate which is which with growing project size. Wouldn't it be better to have a separate folder "mail_templates" within your app? In case that was a good idea how do I change TEMPLATES in settings.py so that Django would be able to find "mail_templates"? -
Django UpdateView with multiple models and forms
Is it possible to have, for example, two forms with different models in one class (UpdateView)? Around stackoverflow and rest of the web, I couldn't find any information about that. Here is what I try to accomplish: class SettingsView(LoginRequiredMixin, UpdateView): # Here I'm trying to combine multiple models and display each form in settings.html model = (User, Currency) fields = [ # ... ] success_url = reverse('main:settings') template_name = 'settings.html' -
Basic Django, How do I configure this empty path
So, I was trying to run a Django website I found on github Link but the home page for the site isn't working. It gives the following error Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: blog/ admin/ login/ [name='login'] logout/ register/ [name='register'] login/ [name='login'] logout/ [name='logout'] password_change/ [name='password_change'] password_change/done/ [name='password_change_done'] password_reset/ [name='password_reset'] password_reset/done/ [name='password_reset_done'] reset/<uidb64>/<token>/ [name='password_reset_confirm'] reset/done/ [name='password_reset_complete'] The empty path didn't match any of these. Can anybody take a look at the repository and help me out with what's wrong. Thanks -
Synchronize authentications between two django projects
I have two separate Django projects with separate databases. I would like that when a user logs in site A, he is automatically logged into site B. I thought of doing the following: When user log into site A, server A requests server B to create a new session for the user, Server A then sends back session information to the user client, When the client logs into site B, the session data is sent so that server B considers the user as logged in. Would that work? How should I send the session data from the browser to server B (with a cookie?)? -
how to match a year range (string) argument eg. 2001-2002 in django urls by using regex
I am getting a string value from Django form which I want to map to a URL. I tried with regex but it gives an error. I tried below URL pattern to match: year/2006-2007 re_path(r'year/(?P<clg_year>.+?+)/', view.get_details, name="year") Please note that the value 2006-2007 is a string that I am getting in some of the forms. The error I am getting is: Reverse for 'year' with arguments '('2', '0', '0', '6', '-', '2', '0', '0', '7')' not found. 1 pattern(s) tried: ['year/(?P[\w-]+)/'] -
Using django project on a notebook pc
I developed a django project and selling it to my customers. Generally we install it on a server. But some customers tell us that they will use the project iternally, not on internet. So they want us to install it on their daily used pc. So they will use it like a desktop application with the web browser just on the local pc. So they wont make any investment on server. Everyday they will shutdown their pc while taking to home. So is it feasable, applicable and safe to use a django project on a laptop pc. -
Can't receive data value with a PUT Ajax request in a django view
I'm doing a PUT Ajax request sending a value in data parameter, but i don't receive any data in my django view. This is my code: function wordUpdate(){ $.ajax({ url:'/socialanalyzer/dictionary_update/', headers: { "X-CSRFToken": $.cookie("csrftoken") }, type: 'PUT', data: { word_id: temporalWordToEdit },success: function(data) { if (data.code==200) { alertify.success('Word modified successfully'); var delayInMilliseconds = 2000; setTimeout(function() { location.reload(true); }, delayInMilliseconds); }else{ console.log('Error, status:',data.code); alertify.error('Error updating the word'); } } }) } views.py def put(self, request, *args, **kwargs): try: if request.method == 'PUT' and request.is_ajax(): import pdb;pdb.set_trace() Am I passing this in properly? This should be works, but I receive empty data: (Pdb) request.GET <QueryDict: {}> I also tried sending data with JSON.stringify function, but i get the same result: var word_id = { 'word_id': temporalWordToEdit }; $.ajax({ url:'/socialanalyzer/dictionary_update/', headers: { "X-CSRFToken": $.cookie("csrftoken") }, type: 'PUT', data: JSON.stringify(word_id) I received the value, but instead of sending it as data, i sent it directly in the url like this: url:'/socialanalyzer/dictionary_update/?word_id='+temporalWordToEdit, (Pdb) request.GET <QueryDict: {'word_id': ['1']}> I don't know if this is the right way or I'm doing something wrong. I understand that in a PUT request, you try to update an instance, but it's correct to send the id instance in the url … -
How to return only the relevant related objects in Django REST Framework
I am trying to create an API such that when I give it a keyword it will return all the cinemas that have movies containing said keyword. Right now I am using: queryset = Cinema.objects.filter(movies__icontains = keyword) My serializer is: class CinemaSerializer(serializers.ModelSerializer): class Meta: model = Business fields = ('id', 'name', 'city', 'movies') depth = 1 If the keyword is "ghost" this returns the cinemas with all their movies. { "id": 1, "name": "My Cinema", "city": "London", "movies": [ { "id": 1, "title": Ghosts }, { "id": 2, "title": Ghostbusters }, { "id": 3, "title": Star Wars } ] Is there a way to return the cinemas and only the relevant movies (Ghosts and Ghostbusters)?