Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic Django model fields
How can I dynamically create fields on a Django model? They just show up as deferred in the __dict__ and when inheriting it says the fields don't exist with my approach: def add_fields(prefix): def wrapper(cls): for field_name,field in vars(base_class).items(): if isinstance(v, (DeferredAttribute, Creator)): setattr(cls, prefix + field_name, field) return cls return wrapper Example on model: @add_fields("tag") class MyTagVariant(models.Model): pass These show up as a bunch of deferred fields... But then when inheriting: class InheritedModel(MyTagVariant): # Dependent vars on fields existing Throws an error saying te fields are non-existent. I know I can use abstract classes etc. My use case is slightly different and prevents this. I tried mixing in a metaclass but the __new__ method wasn't even called. -
Converting pk to slug with Django-Generic-Detail view
I have gotten my test site up successfully and am now trying to change the url link from a private key to a slug to make the link more intuitive for the user. I have read many questions, but have not found one that adequately answers my question. I understand I use the exmodel.name instead of the .slug (code below); however the exmodel.slug does not return anything and the database record is one word so it shouldn't matter (figured I would tackle one problem at a time). The exmodel_list.html compiles as expected, but the exmodel_detail.html returns a 404 error. This doesn't make sense to me since it works when I use the method. Any insight or articles you could provide would be much appreciated. Thanks for the help! models.py class ExModel(models.Model): name = models.CharField(max_length=50, help_text='Enter name of example model') slug = models.SlugField(blank=True) def __str__(self): """String for representing the Model object.""" return self.name def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(ExModel, self).save(*args, **kwargs) def get_absolute_url(self): """Returns the url to access a detail record for this model.""" return reverse('exmodel-detail', args=[str(self.id)]) views.py class ExModelListView(generic.ListView): model = ExModel class ExModelDetailView(generic.DetailView): model = ExModel urls.py app_name = 'presentInfo' urlpatterns = [ path('', … -
Manually rendering choicefield
I've got this in forms.py self.fields['package_selection'].choices = tuple([(t.id, t) for t in Variation.objects.all()]) within my template, I have this: {% for key,value in form.package_selection %} <option value="{{ key }}">{{ value.product.title}} - {{value.title}} </option> {% endfor %} I've getting the following error: Need 2 values to unpack in for loop; got 1. How should i be accessing the value and key in the tuple within my template? thanks! -
cannot pass django object to angular front end
I am using Django 2.1.5 and Angular 7.3.1. I have a Django backend class DetailView that I am trying to use to pass an object to the Angular front end. I know the DetailView is working fine because I can see the object when I render a template with Django. For some reason I cannot seem to pass it to Angular via the Django API. When I load the page nothing is displayed for dogdetail and the console has the error: DogdetailComponent.html:2 ERROR TypeError: Cannot read property 'name' of undefined at Object.eval [as updateRenderer] I have tried several variants and syntax, etc. I would think if the Django API is getting the object correctly, than Angular should be able to pick it up from the API endpoint. My django urls.py: from django.urls import path from .views import DogList, DogDetailDjango, index urlpatterns = [ path('', index, name='index'), path('dogs/', DogList.as_view(), name='doglist'), path('<int:pk>/dogdetail/', DogDetailDjango.as_view(), name='dogdetail'), ] dogdetail.component.ts: import { Component, OnInit } from '@angular/core'; import { ApiService } from '../api.service' import { Dog } from '../dog' @Component({ selector: 'app-dogdetail', templateUrl: './dogdetail.component.html', styleUrls: ['./dogdetail.component.scss'] }) export class DogdetailComponent implements OnInit { dogdetail : Dog[]; constructor(private apiservice: ApiService) { } ngOnInit() { this.getDog(); } getDog(): … -
How do I enforce a positive number on my Python/Django model field?
I'm using Django and Python 3.7. I'm also using PostGres 9.6. I have the following field in my model. class ArticleStat(models.Model): ... score = models.FloatField(default=0, null=False) Is there any way to write constraints such that when my migration is generated, the underlying database will enforce a FloatField that is always equal to or greater than zero? I don't want any negative numbers in this field. -
Django import export package ForeignKey widget to two values
I am trying to use django ForeignKey Widget to import my data class BookResource(resources.ModelResource): author = fields.Field( column_name='author', attribute='author', widget=ForeignKeyWidget(Author, 'name')) class Meta: fields = ('author',) In the documentation it states that the foreign key can use ForeignKeyWidget to lookup related objects using Author.name instead of Author.pk . What i am trying to look up based on the Author.name and Author.nickname. Because I might have many authors with the same name. However, I don't want to use Author.pk because that will confuse the user who will import the data. Is there a way to do that? link to the documentation https://django-import-export.readthedocs.io/en/latest/api_widgets.html -
'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
{% for i in movies.paginator.page_range %} {% if movies.number == 1 %} <h1>{{i}}</h1> {% else %} <h6>{{i}}</h6> {% endif %} {% endfor %} I'm trying to use paginator in django but it seems like something is wrong but I can't seem to figure it out. -
Django - Functioning continuing to execute despite subfunction 404
When #A runs def add_particle_to_atom(particle_uid, atom_uid): node_data = find_node_by_uid(particle_uid) #A particle = node_data['queryset'] #B It triggers this function that I thought would cause an exception in the REPL. def find_node_by_uid(node_uid): # ... try: # thing will fail because i'm making it fail for error handling except: print("|--- ERROR: there is no particle with that uid.") return HttpResponseNotFound("404") But the console give an error that is associated with #B. >>> add_particle_to_atom('wefjhwljefh',a) |--- CHECK: if particle with uid 'wefjhwljefh' exists. |--- ERROR: there is no particle with that uid. Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/layne/Desktop/AlchDB/alchemy/views.py", line 258, in add_particle_to_atom particle = node_data['queryset'] File "/Users/layne/Desktop/venv_alchdb/alchdb/lib/python3.7/site-packages/django/http/response.py", line 145, in __getitem__ return self._headers[header.lower()][1] KeyError: 'queryset' Why does it do this when I have told the sub-function to 404? I don't want to exit because I still want the REPL usable. -
Django: NameError: name 'ManyToManyField' is not defined
In Django I am trying to create a model and get this error: item = ManyToManyField(Standard_pizza_order, blank=True) NameError: name 'ManyToManyField' is not defined class Standard_pizza_order(models.Model): size = models.ForeignKey(Size, on_delete=models.CASCADE) topping = models.ForeignKey(Topping_type, on_delete=models.CASCADE) topping_list =models.ManyToManyField(Topping, blank=True) price = models.FloatField(max_length=8) class basket(models.Model): order_id= models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) item = ManyToManyField(Standard_pizza_order, blank=True) status = models.CharField(max_length=20) I don't understand what's happening as it looks like by the time I used the Standard_pizza_order I already defined it... -
Django Python Key Error that I haven't been able to fix for 5 hours
I'm trying to route my login-page to a dashboard and for some reason my sessions aren't being read and I keep getting a key error that I can't seem to fix. This is my views.py file [The error is on line 18] -
How do I migrate models between apps in Django?
I am trying to migrate models between apps following Ozan’s answer here: How to move a model between two Django apps (Django 1.7) However, I get stuck when I try to run python manage.py makemigrations new_app. I get this error message: The field products.Offer.compared_image was declared with a lazy reference to 'products.comparedimagepair', but app 'products' doesn't provide model 'comparedimagepair'. How do I avoid this? What is causing this? I updated the reference but it seems to still be failing -
Django Rest Framework how assign values manually (without data) for relational fields
I have a model like this: class Listing(...): ... class ListingImage(...): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='images') ... and a serializer field for listing images: class ListingImageSerializer(serializers.ModelSerializer): class Meta: model = ListingImage fields = ('id', ..., 'listing') ... My URL routes are set up in the following way: POST /v1/listings/:listing_id/images in the view, I get the listing based on path param: def upload_photo_to_listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) data = request.data.copy() data['listing'] = listing serializer = ListingImageSerializer( data=data, context={'request': request}) if serializer.is_valid(raise_exception=True): serializer.save() return Response({'data': serializer.data}, status.HTTP_201_CREATED) This works fine (removed error handling for simplicity); however, I do not like mutating request.data (or copying and mutating it). When using original object, I can do something like this: ListingImageSerializer(someListingImageObject, data=data, ...) Is it possible to do something similar to it but instead of original objects, actually pass the related field? -
No Reverse Match Found error in Django when using < > in URL
I'm having problems with my URL paths. Whenever I remove -- path('/follow', views.follow, name='follow') -- everything works fine. When I include it, the page with the link on it reveals --'Reverse for 'follow' with no arguments not found' -- though I can manually type the follow path into the URL and it succeeds. Why is this and how can I fix it? html <a href="{% url 'follow' %}">Follow</a> urls.py urlpatterns = [ path('', views.explore, name='explore'), path('happening/profile/', views.profile, name='profile'), path('happening/', views.happening, name='happening'), path('home/', views.home, name='home'), path('home/likes/', views.likes, name='likes'), path('<query>/follow', views.follow, name='follow'), path('<query>/', views.profpage, name='profpage'), ] views.py def profpage(request, query): obj = User.objects.filter(username=query) if not obj: attempt = {'user':query} return render(request, 'error.html', attempt) try: obj2 = reversed(get_list_or_404(Comments, user=query)) except: obj2= {} try: obj3 = get_list_or_404(Comments, user=query) except: obj3 = {} like_dict={} for x in obj3: likes = x.likes.all().count() like_dict[int(x.id)] = int(likes) img = UserProfile.objects.filter(user__username=query) for x in obj: obj = x for x in img: img=x content = {'obj': obj, 'img':img, 'info':obj2, 'like_dict':like_dict, 'query':query, } return render(request, 'profpage.html', content) def follow(request, query): print("WORKING") return HttpResponse(request) -
Issue with parsing csv from Django web form
I was hoping someone could help me with this. I'm getting a file from a form in Django, this file is a csv and I'm trying to read it with Python's library csv. The problem here is that when I apply the function csv.reader and I turn that result into a list in order to print it, I find out that csv.reader is not splitting correctly my file. Here are some images to show the problem This is my csv file: This my code: And this is the printed value of the variable file_readed: As you can see in the picture, it seems to be splitting my file character by character with some exceptions. I thank you for any help you can provide me. -
Why don't the .url in Django template link to the "upload_to=" directory of the model?
I made a template to list documents with a download link, but instead of linking to : http://127.0.0.1:8000/media/documents/mydoc.csv it links to : http://127.0.0.1:8000/media/mydoc.csv In myapp/models.py class Document(models.Model): docfile = models.FileField(upload_to='documents') In myapp/templates/myapp/list.html <ul> {% for document in documents %} <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li> {% endfor %} </ul> document.docfile.url links to media/mydoc.csv but the file is stored into media/documents/mydoc.csv Versions Python : 3.7.2 Django : 2.1.7 OS : Windows 10 In myapp/views.py def myview(request): documents = Document.objects.all() return render(request, 'myapp/list.html', {'documents': documents}) In myapp/urls.py app_name = 'myapp' urlpatterns = [ path('', views.index, name='index'), path('myview/', views.myview, name='myview'), ] In myproject/urls.py urlpatterns = [ path('', views.index, name='index'), path('myapp/', include('myapp.urls')), path('admin/', admin.site.urls), ] In settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Since it is my fist Django app (and first webapp ever) I guess I missed something very basic. Do you have an idea ? -
Hide an Object in a ListView Django
I wanted to know if there is a way in which I can "hide" an element so that it does not appear in a ListView. First I wanted to try using the deleteview but that erased the object from the database, now I just want the object not to be visible just by pressing a button, I am still new to django so I would like to recommend simple processes, thanks. For example, if i have a list of reports and I want them to stop appearing when I decide but without removing them from the database. Also i show them in a table where in each cell there is a data of the object. I hope you can help me, because I depend a lot on this framework and I do not know much about it. -
django exports, Help !! 2formsets as one table in django template
i have posted same question last week but dint get any response on that so posting again. hoping any Django expert will help me find solution for this. Django: How can I combine 2 formsets as one so as to display as one inline table (of course with pagination) in template please do let me know if you have any question. my goal is to show 2 formsets as one inline table in form using Django -
How to save a thumbnail to default_storage(AWS S3) after converting it in Django views.py?
I have a an HTML form that allows images upload. I want to save the original image to S3 storage and then convert it to thumbnail and save the thumbnail to the same storage. I could only save the original image but after converting it to thumbnail using PIL when I try to save it I get "Server error 500" My views code is as follow, from django.core.files.storage import default_storage as storage class upload(View): def post(self, request): image = request.FILES['pic'] storage.save(image.name, image) thisfile = storage.open(image.name) newimg = Image.open(thisfile) thumb = newimg.resize((128,128), Image.ANTIALIAS) storage.save("newimagename", newimg) #Trying to save it this way doesn't work either #thisobj = userProfile.objects.get(user= request.user) #thisobj.image = newimg #thisobj.save() I tried some print statements to make sure that it was converting the file with no problem and it was but it saved it to memory and it prints like, <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=600x600 at 0x105C1DEF0> I tried overwriting the save method in models.py but I get the same error def save(self, *args, **kwargs): super(userProfile, self).save(*args, **kwargs) if self.image: self.image.name = "y.JPG" image = Image.open(self.image.path) image = image.resize((128,128), Image.ANTIALIAS) image.save(self.image.path) -
Why is Django template engine adding myapp/myview to my URLs?
I made a template to list documents with a download link, but instead of linking to : http://127.0.0.1:8000/media/mydoc.csv it links to : http://127.0.0.1:8000/myapp/myview/media/mydoc.csv In myapp/templates/myapp/list.html <ul> {% for document in documents %} <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li> {% endfor %} </ul> document.docfile.url does actually links to media/mydoc.csv so that I guess it has to do with the template engine. Versions Python : 3.7.2 Django : 2.1.7 OS : Windows 10 In myapp/models.py class Document(models.Model): docfile = models.FileField(upload_to='documents') In myapp/views.py def myview(request): documents = Document.objects.all() return render(request, 'myapp/list.html', {'documents': documents}) In myapp/urls.py app_name = 'myapp' urlpatterns = [ path('', views.index, name='index'), path('myview/', views.myview, name='myview'), ] In myproject/urls.py urlpatterns = [ path('', views.index, name='index'), path('myapp/', include('myapp.urls')), path('admin/', admin.site.urls), ] In settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' Since it is my fist Django app (and first webapp ever) I guess I missed something very basic. Do you have an idea ? -
Best way for implementing ratings with Django and React?
I have a Django REST API set up with React frontend so that the frontend is as it's own app inside the Django project similar to this tutorial. Basically I have an authentication API and an API for listings. I would like to implement ratings for each user as a foreign key so that I can access the ratings for each user and all ratings combined through a separate API. I don't have models.py for my user model since I can create the API straight through a serializer: # User Serializer from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') I checked out django-star-ratings and pinax-ratings but they both seem quite hard to implement with React. My question is, what would be the best way to have ratings as a foreign key for User model and should I create a new API for all ratings, thanks! -
Static files not working with Django, Heroku, and Django Sass Processor
I can't seem to get static files to work when deploying to Heroku. I get 404s for all css and js files. Things I'm using: Django 2.1.5 whitenoise 4.1.2 django-sass-processor 0.7.2 django-webpack-loader 0.6.0 Here are my settings: Whitenoise is in the middleware MIDDLEWARE = [ 'django.middleware.gzip.GZipMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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' ] All of the static file settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') STATIC_SOURCE_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = [ STATIC_SOURCE_ROOT ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder' ] # Ensure STATIC_ROOT exists. os.makedirs(STATIC_ROOT, exist_ok=True) """ Django Sass Processor https://github.com/jrief/django-sass-processor Template Usage: {% load sass_tags %} <link href="{% sass_src 'myapp/css/mystyle.scss' %}" rel="stylesheet" type="text/css" /> """ SASS_PROCESSOR_INCLUDE_DIRS = [ os.path.join(STATIC_SOURCE_ROOT, 'scss/') ] SASS_PROCESSOR_ROOT = STATIC_ROOT SASS_PROCESSOR_ENABLED = False # Django Webpack Loader # https://github.com/owais/django-webpack-loader WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'dist/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-prod.json') } } DEBUG = False When I go to deploy I follow these steps: Run yarn run build Which builds the js (I'm using React so there is babel and such) and places it into 'static/dist/' - which gets committed to git Deploy to Heroku I have collectstatic disabled on heroku so it doesn't get called automatically on deploy … -
Django 1.8. When we use id field in values and annotate operation in django there is ignore another fields in result sql-query
It is my first question. Sorry for my English. I want to update Django from 1.7.11 to 1.11.18. But I found a problem. Django makes different sql-queries for different Django versions. For example. I have a query: Account.objects.values('id', 'name', invoice__payment__payment_gateway').annotate( pay_paid=Sum('invoice__payment__amount'), pay_refunded=Sum('invoice__payment__amount_refunded') ).order_by('-name', ) sql-query for Django 1.7.11: SELECT `member_account`.`id`, `member_account`.`name`, `member_payment`.`payment_gateway`, SUM(`member_payment`.`amount_refunded`) AS `pay_refunded`, SUM(`member_payment`.`amount`) AS `pay_paid` FROM `member_account` LEFT OUTER JOIN `member_invoice` ON ( `member_account`.`id` = `member_invoice`.`account_id` ) LEFT OUTER JOIN `member_payment` ON ( `member_invoice`.`id` = `member_payment`.`invoice_id` ) GROUP BY `member_account`.`id`, `member_account`.`name`, `member_payment`.`payment_gateway` ORDER BY `member_account`.`name` DESC Please pay attention to the GROUP BY section. There is 3 fields: id, name, payment_gateway. But we have next sql-query for Django 1.8.19: SELECT `member_account`.`id`, `member_account`.`name`, `member_payment`.`payment_gateway`, SUM(`member_payment`.`amount_refunded`) AS `pay_refunded`, SUM(`member_payment`.`amount`) AS `pay_paid` FROM `member_account` LEFT OUTER JOIN `member_invoice` ON ( `member_account`.`id` = `member_invoice`.`account_id` ) LEFT OUTER JOIN `member_payment` ON ( `member_invoice`.`id` = `member_payment`.`invoice_id` ) GROUP BY `member_account`.`id` ORDER BY `member_account`.`name` DESC And we have only one field in the GROUP BY section. Why do we have only one id field? It is main question. BUT when I remove 'id' field from values section Django 1.8 makes valid sql-query: SELECT `member_account`.`name`, `member_payment`.`payment_gateway`, SUM(`member_payment`.`amount_refunded`) AS `pay_refunded`, SUM(`member_payment`.`amount`) AS `pay_paid` FROM `member_account` LEFT … -
Get selected rows from datatable to my django views
I am using datatables to create checkboxes to the line items in my table in HTML. I am having a hard time getting the selected rows to my Django views. I am new to JS so any ideas on how to read the data and push it to my views will be really helpful! Here is the code for my table <table id="dtDynamicVerticalScroll" class="table table-hover table-striped table-bordered"> <thead class="thead stylish-color text-white"> <tr> <th></th> <th class="th-lg">Program</th> <th class="th-lg">Profile</th> <th class="th-lg text-center">Age</th> </tr> </thead > <tbody> {% for registeredUser in registeredUsers %} <tr> <td></td> <td>{{ registeredUser.profile.program.program_name }}</td> <td ><a href="{% url 'profile' registeredUser.id %}"><img src="{{ registeredUser.profile.photo.url }}" onError="this.onerror=null;this.src='/media/profile_image/default.jpg';" style="width:30px;height:30px;border:1px;" class="img-fluid rounded-circle"></a>&nbsp;&nbsp;<span>{{ registeredUser.first_name }}</span>&nbsp;<span>{{ registeredUser.last_name }}</span></td> {% if registeredUser.profile.age == "None" %} <td align="center"></td> {% else %} <td align="center">{{ registeredUser.profile.age}}</td> {% endif %} </tr> {% endfor %} </tbody> </table> <a href="{% url 'groups' %}" class="btn btn-pink">E-mail a group</a> and this is the script used to create checkboxes <script type="text/javascript" class="init"> $(document).ready(function() { $('#dtDynamicVerticalScroll').DataTable( { columnDefs: [ { orderable: false, className: 'select-checkbox', targets: 0 } ], select: { style: 'multi', selector: 'td:first-child' }, order: [[ 1, 'asc' ]], responsive: true, } ); } ); </script> I am trying to get the checked line item's … -
Django Automatically Standardize Model Field
I am trying to create a model field for US States that can be used across multiple models in my app. I have a dictionary of common state abbreviations and spellings matched to a standardized set of names - e.g. state_dict = {"WV": "West Virginia", "W Virginia": "West Virginia", "WY": "Wyoming"} I'd like the model field to automatically look up its value against the dictionary and set the field's value to the standardized name if a match is found. If no match is found, the field should raise an exception of some sort. Things I've Tried Choice Field- This doesn't work for my use case, as the models are only modified through a REST API. Furthermore the API receives data from 3p sources, so enforcing the standardization client-side isn't an option. Django-Localflavor US - I've tried to use the custom state field provided by this package, but it just implements a choice field that doesn't automatically standardize the data. -
How to set default value for new model field in existing model with data
I have a small django model with two fields. There is already data in the database for this model. class MetaDataValue(Model): metadata_id = models.ForeignKey(MetaData, on_delete=models.CASCADE,) value = models.CharField('value', max_length=200,) I need to add another field, short_value = models.CharField('short_value', max_length=200,) I know when I perform a migration, it will complain because I don't have a default value for the existing rows in the database. Is there a way to set the default value for short_value to the string in the value field that already exists in the database/model? I want to do this because I only need to create a different short_value for about 20 rows in the database, and there is no universal default value for this field. I would rather not have something like 'fred' or 'default' in the short_value field because some fields have numbers, some have text, some have a combination of numbers and text. I also thought of creating a property instead of another model field, but there isn't a simple way to convert the value field into the short_value field. Thanks!