Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multipart Parser In Django rest framework
I'm trying to upload image using django rest framework. But I had a problem with that , when I'm using postman form it upload image successfully, but when I'm trying to type json as row in postman it returns to me this error. "The submitted data was not a file. Check the encoding type on the form." here my code: serializer.py class UserImageCreateSerializer(serializers.HyperlinkedModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) class Meta: model = UserImages fields = ('user', 'image',) view.py class UserImageAPICreateView(ListCreateAPIView): queryset = UserImage.objects.all() serializer_class = UserImageCreateSerializer permission_classes = [AllowAny, AllowAnonymous] my request: { "User": 79, "image": "/path/to/image.jpg" } note: when I use postmen form it uploaded successfully and when use django rest framework HTML form it works too I dont know what mistake I did. so, any one has the solution please help me. -
Django group by multiple fields
I want to transform this SQL request into a Django view: SELECT cat, dog, bird, count(1) FROM animals WHERE master_id = 1 GROUP BY cat, dog, bird In order to do that I've tried: animals = Animals.objects.filter(id=1).values('cat', 'dog', 'bird').annotate(ct=Count('cat'), dg=Count('dog'), br=Count('bird')) And then loop on the result to find the count for each one (not very optimized) and the result isn't good. That's group by as I want but doesn't care about the id. -
convert a price field in django to be in a specific currency
i have a Product model which has a price field and a currency field. the user can save different products using different currencies. some products are saved in usd, some in gbp, etc'.. class Product(models.Model):` class Product(models.Model): price = models.DecimalField(decimal_places=1, max_digits=4, default =0) #, blank = True, null = True) usd = 'USD' nis = 'NIS' gbp = 'GBP' CURRENCY_CHOICES = ( (usd , 'USD'), (nis, 'NIS'), (gbp, 'GBP') ) currency = models.CharField( max_length=3, choices = CURRENCY_CHOICES, default = usd, blank = True )` i want to be able to sort and view all of the products in a single currency. how can i add a field, 'price_in_usd', which will be set automatically when fields 'price' and 'currency' will be set? something like this for example: price_in_usd = convert_price_to_usd() convert_price_to_usd(): if currency == GPB: return price*1.25 if currency == NIS: return price*0.33 i don't mind having the currencies not updated daily, my problem is with django not having a setter/getter. -
django: how to find the context variable in inline Model if we use custom template
Below is my code class CommentInline(admin.StackedInline): model= Comments extra=0 template = "admin/comments.html" class BlogAdmin(admin.ModelAdmin): inlines = [CommentInline] admin.site.register(Blog,BlogAdmin) In the comments.html file {% for comments in comments_list %} {{ comments.name }} {% endfor %} But it is not printing anything, but If use a default template it prints the values -
Correct tech stack to be used? is it django for me?
i will be using django rest framework for developing rest apis, django for developing my web application, postgresql as my database, and for the frontend part html,css, javascript, jquery, vuejs and if i would need some other library i will see to that accordingly at that time. so am i using the tech stack right? and what are the things i have missed? what should i change? my site would require not too much write extensive but a bit too much read extensive! I have some experience with machine learning with python, and i am familiar with django too. -
django-filters compatability issue with Djang 2.1
I was upgrading a Django app from 1.8 to 2.1. The app was already using django-filters 0.11.0. As part of upgradation, django-filter has been upgraded to 2.0.0 and Django to 2.1.2. But when starting the app getting the following error RuntimeError: populate() isn't reentrant The error disappears if I remove the django-filters from the installed app list. Any idea what's causing this issue? from the documentation, these versions seem compatible -
how to run migrations on a standalone django reusable app?
I'm new to django and makeing contributions regarding the same, so I started working on this django reusable app on github. The thing is, I made some changes into one of the models and I want to run migrations for the same. Since it's a standalone app, not part of a project-how do I do this? (since I can't run python manage.py makemigrations -
django model form edit automatically
I have a little question :) I want to add/edit user directly with django model. I did that : class AddClientView(generic.FormView): success_url = 'manager/liste' form_class = AddClientForm template_name = 'Manager/Clients/formClient.html' def get_context_data(self, **kwargs): retour = super(AddClientView, self).get_context_data() retour['forms'] = AddClientForm return retour def form_valid(self, form): retour = super(AddClientView, self).form_valid(form) form.save() return retour class EditClientView(generic.FormView): success_url = '/manager/liste' form_class = AddClientForm template_name = 'Manager/Clients/formClient.html' def get_context_data(self, **kwargs): retour = super(EditClientView, self).get_context_data() client = Clients.objects.get(id=self.kwargs["client"]) retour['forms'] = AddClientForm(instance=client) retour['client'] = client return retour def form_valid(self, form): retour = super(EditClientView, self).form_valid(form) a = Clients.objects.get(id=self.kwargs['client']) a.prenom = form.cleaned_data['prenom'] a.nom = form.cleaned_data['nom'] a.telephone = form.cleaned_data['telephone'] a.mail = form.cleaned_data['mail'] a.adresse = form.cleaned_data['adresse'] a.date_anniversaire = form.cleaned_data['date_anniversaire'] a.save() for pConseomme in form.cleaned_data['pConsomme']: a.pConsomme.add(pConseomme) for pInteret in form.cleaned_data['pInteret']: a.pInteret.add(pInteret) return retour For edit, i want to do the same as add, like that : just a form.save() But it does not work ... it creates a new user. How i can do that ? Thanks guys ! -
Is node.js good for an application like timedoctor?
We are planning to build an application like timedoctor(https://www.timedoctor.com and were planning to use node for the backend and Angular for the frontend. But after some discussions, it was not clear whether the node is a good candidate as a backend server for such an application. We are planning to build it as a multitenant application. We are also considering Django as the backend application.So, does node is competitive with OOPs and ORM features in Django? Any performance benefit for using node instead of Django here? If Django have more advantages, what about using node app only as the receiving API server for image uploads (screenshots from agents running on employee PCs). Node, single-threaded event-loop and internal worker threads give a good throughput for concurrent image uploads? Or image uploads are event-loop blocking events and its a bad idea? -
Im getting the folloeing error"OSError at /admin/login"
im getting this error"[Errno 22] Invalid argument: 'C:\Users\TOSHIBA\PycharmProjects\books\venv\lib\site-packages\django\forms\templates\django\forms\widgets\text.html'" when i run the command "python manage.py runserver" and open admin page. i haven't written any views and created only models. can anyone help me with this please. -
filter objects from a model if a foreign key field contains the logged in user
views.py from django.shortcuts import render from notifications.models import Notification from django.shortcuts import render,Http404,redirect,get_object_or_404 from django.db.models import Q def TrainerDashView(request): if not request.user.is_authenticated: return redirect('accounts:index') else: print(request.user.username) notifications = Notification.objects.filter(receiver__username__in = request.user.username) count=Notification.objects.filter(receiver__username__in = request.user.username).count() print("NOTIFYNIUM: ",count) context={ 'notifications':notifications, } return render(request,'trainer_dash.html',context) My Model Notification contains a field called receiver which is a foreign key to all User model.I want to select all objects in Notication if the receiver field contains current logged in user. My code is not returning any objects even aven though user activated from admin -
First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'unicode'
I'm very new to django and i'm following some tutorial to learn it. And from this tutorial i'm trying to build a blog but i'm stuck at this following error. First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'unicode'. Request Method: GET Request URL: http://localhost:8000/blog/2018/10/16/todays_post/ Django Version: 1.11.16 Exception Type: ValueError Exception Value:First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'unicode'. Exception Location: C:\Users\...\mysite\python-ve\env\lib\site-packages\django\shortcuts.py in get_object_or_404, line 90 Python Executable: C:\Users\...\mysite\python-ve\env\Scripts\python.exe Python Version: 2.7.15 Following is my model.py from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from django.contrib.auth.models import User class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset()\ .filter(status='published') class post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published','Published'), ) title = models.CharField(max_length=250) # field for the post title slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name ='blog_posts') body = models.TextField()# text field. body of the post publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length = 10, choices=STATUS_CHOICES,default='draft') # to know the status of the post objects = models.Manager() published = PublishedManager() class Meta: # sort results by the publish field in descending order ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return … -
Add RTF/Rich Text Editor to CustomUserCreationForm/CustomUserEditForm
I try to extend my custom User model as described here. This works fine for the shown fields like ModelChoiceField and CharField. My goal now is to add a RTF field (the control like the one shown in the Page model). I have looked through the source code of wagtail and found the method get_rich_text_editor_widget which is being used in conjunction with a CharField. Sadly I get a JavaScript error: Uncaught TypeError: Cannot read property 'initEditor' of undefined My guess now is that I somehow need to include or modify a hook for the widget. Or is it sufficient to override the JavaScript block in a template? It feels a bit hacky right now and I am stuck with including the required JS, that's why I am posting the question. Maybe I am missing something trivial. # ... from wagtail.admin.rich_text import get_rich_text_editor_widget class CustomUserEditForm(UserEditForm): position = forms.ModelChoiceField(queryset=Position.objects, required=True, label=_('Position')) # biography = forms.Textarea() biography = forms.CharField(widget=get_rich_text_editor_widget()) -
Mayan EDMS \n character showing in main menu
I am new to Django programming so I don't understand why is this happening. The problem is when I load the home page of the website in the first second everything loads fine like it should. You can see at the picture below: After that it loads a lot of \n characters without any reason, just in the main menu part in every new line under div id="main-menu". And here is a picture without background color: I tried to search whole project for "\n" character to see if maybe some code is broken but everything looks fine. I also looked in django.po to see if it appeared in translations but nothing was wrong. I don't know what am I missing. -
What is the best way to have all the timezones as choices for a Django model?
I am creating model which needs to store a timezone value. Right now, I am generating the timezones using pytz in another file, converting that into a tuple, and calling that tuple into my models.py. Like this: timezones.py import pytz TIMEZONE_CHOICES = [] for tz in pytz.all_timezones: TIMEZONE_CHOICES.append((tz, tz)) TIMEZONE_CHOICES = tuple(TIMEZONE_CHOICES) models.py from .timezones import TIMEZONE_CHOICES class MyModel(models.Model): timezone = models.CharField(max_length=255, default='UTC', choices=TIMEZONE_CHOICES) This honestly seems a bit hack-y. Would generating the timezones this way cause problems in the future? What would be the ideal way to do something like this? -
Django permissions when using Django Rest Framework + VueJs as a front
My question address to the usage of Django permission architecture even when the front is on Vue.js and data is requested/responded through Django REST framework. I am a little confused about being able to use default permission libraries of Django when the app is combined with Rest Framework and VueJs: from django.contrib.auth.decorators import login_required, permission_required @permission_required('pobapp.can_add_instance') @login_required def addEmployeeInstance(request): return render(request, 'pobapp/search.html') If not, how can I restrict some data and pages for specific users? For example, if I only wanted to let authenticated users to view some specific pages? -
How to change fields in API?
I'm working on a django backend. One of the models is a SubMentor. This also has to link with the API for an android application. Now, When I access the inbuilt api documentation provided by Django, I don't see any changes being made to the Create option for submentors. The code for my Submentor Serializor:- class SubMentorSerializer(serializers.HyperlinkedModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) mentee_count = serializers.SerializerMethodField() subskills = serializers.PrimaryKeyRelatedField(many=True,queryset=subSkill.objects.all() ) subcourses = serializers.PrimaryKeyRelatedField(many=True, queryset=Course.objects.all() ) #trainees = serializers.PrimaryKeyRelatedField(many=True,queryset=Trainee.objects.all() ) subprojects = serializers.PrimaryKeyRelatedField(many=True, queryset=Project.objects.all() ) class Meta: model = SubMentor fields = ('url', 'user', 'mentee_pref_count', 'mentee_count', 'subskills','subcourses','subprojects') def get_mentee_count(self, obj): return obj.get_mentee_count() Picture of Django API documentation:- Image of django api for submentor Why don't I see subcourses and subprojects as fields in this api documentation? -
Django how to apply to objects.filter(user=request.user) in templates?
First, sorry for my English level. purchaseinfo/models.py class PurchaseInfo(models.Model): purchase_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) purchase_name = models.CharField(max_length=30) purchase_addr = models.CharField(max_length=100) purchase_phone = models.CharField(max_length=15) ...and so on customlogin/views.py from purchaseinfo.models import PurchaseInfo def purchaseHistory(request): history = PurchaseInfo.objects.filter(user=request.user).values() return render(request,'customlogin/purchaseHistory.html',{'history':history}) purchaseHistory.html {% for i in history %} <tr> <td>{{i.purchase_id}}</td> <td>{{i.purchase_name}}</td> <td>{{i.purchase_addr}}</td> <td>{{i.purchase_phone}}</td> <td>{{i.product_name}}</td> <td>{{i.product_price}}</td> <td>{{i.purchase_date}}</td> </tr> {% endfor %} i used PurchaseInfo.objects.filter(user=request.user).values() and want to show the rusult in templates. But, i got an error msg. FieldError at /auth/purchaseHistory/ Cannot resolve keyword 'user' into field. Choices are: id, product_name, product_price, purchase_addr, purchase_date, purchase_id, purchase_id_id, purchase_name, purchase_phone How can i solve this problem?? -
django, views direct to a another html page
I am using Django for develop a website. The website is intended to use to search information stored in a MySQL database. This is the current basic flow of the web site. 1) index.html - this has a form to select an option 2) according the option, users will redirect to search.html (include a form) 3) once the user provides the criteria, the result will be displayed in reply.html In my views.py , I have two functions. from django.shortcuts import render from website.models import WebsiteRepository from .forms import SearchForm from .forms import SelectTypeForm def Search(request): if request.method == 'POST': #do something return render(request, 'reply.html', {'env_dict':env_dict}) else: #do something return render(request, 'search.html', context = context) def index(request): if request.method =='POST': #do something return render(request, 'search.html', context = context) else: #do something return render(request, 'index.html', context= context) When I go to index.html page, I can select a option and it will direct me to search.html. After, I fill the form there and submit, it wont give me the reply.html page. I have a feeling that, I could make this work by changing urls.py. from django.urls import path from website import views urlpatterns = [ path('', views.index, name='index'), #path('search/', view.Search, name ='Search') ] … -
django, count number of posts from the 'name' of the user
I want to make a filter that takes the users name and returns the number of posts they have made. from django.contrib.auth.models import User User.objects.all() <QuerySet [<User: jack>, <User: lenovo>]> I can see my users. And then I was thinking within the html something like this: <p>jack has written {% jack|total_posts %} posts so far. lenovo has written {% lenovo|total_posts %} </p> I have blog_tags.py file for my filters, and I have some simple tags already working, but bit confused by the volume of available information. I have this so far: @register.filter def total_posts(user=jack): return #expression to count jacks posts. but stuck on the return expression. Any suggestions/corrections would be really appreciated. -
Django DRS adding a row with a query in the serializer return error
Hi i got a problem with DRF im using this as serializer: from rest_framework import serializers from Sitios.models import Sitio, muestras class SitiosSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) ultimo_estado = serializers.SerializerMethodField(read_only=True) class Meta: model = Sitio fields = '__all__' depth = 1 datatables_always_serialize = ('id', 'SitioNombre', 'url') def get_ultimo_estado(self, obj): f = muestras.objects.filter(sitio__id=obj.pk).latest('-muestraDate') return str(f.estado) the problem is the query set i tested this in the console return the right value but when i put it into the function muestras matching query does not exist. this problem happens when there is a problem with the foreign key but it works in the console. i rely dont know what im doing wrong or if you can suggest another course of action. -
Which way is the best to call api from server side
I’m building web application with React. And I’ve never experienced making backend server. But I need to make a server to call api with private key. Call api is the only thing that I’m going to do with server. In this case, which way is the best? -
How do I dynamically access barcode image i saved folder django
guys, I don't seem to understand how to get an Image of barcode I render and save into the template. I am saving the code with, description and the id, adding a little dynamism to it. my problem now is how to point to the image from the HTML template or if there is a better way to do this I would love the suggestion. Thanks here is my code: def barcode(request, stock_id): obj = get_object_or_404(Stock, id=stock_id) d = utility.MyBarcodeDrawing(obj.description,) d.save(formats=['svg','img'],outDir='static_root/media',fnRoot='%s_%d' %(obj.description, stock_id)) barcodePicUrl = "barcode/%s_%d" %(obj.description, stock_id) print(obj.description) return render_to_response('barcode.html', {'url':barcodePicUrl,'obj':obj}) I really need help with this. -
loading and serving static and media files with django and aws S3
I am trying to configure my django app to load static and media files to aws s3 buckets. I have set up the following file structure: settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] # set S3 as the place to store your files. DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = '<my_key_id>' AWS_SECRET_ACCESS_KEY = '<my_access_key>' AWS_STORAGE_BUCKET_NAME = '<my_bucket_name>' AWS_QUERYSTRING_AUTH = False #This will make sure that the file URL does not have unnecessary parameters like your access key. AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com' #static media settings STATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' MEDIA_URL = STATIC_URL + 'media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = 'staticfiles' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) I have set up a user and a bucket on AWS per the instructions here. When I run python3 manage.py collectstatic the staticfiles compile locally but not on AWS. Any guidance much appreciated! -
django abstract model to have slugfield
I want all my models to have SlugField however it seems like its not a DRY principle for each and every model to have: slug = models.SlugField(max_length=50) I want to implement this as follows: Base Model class BaseModel(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, unique=True) class Meta: abstract = True Company Model class Company(BaseModel): code = models.CharField(max_length=2, primary_key=True) name = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Companies' def __str__(self): return self.name My other models will inherit BaseModel to have those fields inherited however, whenever I save new record, SlugField is empty. Anyone could enlighten me on this please!