Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload files to Django
I am using a DropzoneJS Plugin in my Django project. I want to upload files to the database (The problem is that I am uploading blank file objects without a file attached). These are the models: class File(models.Model): file = models.FileField(null=True, blank=True) class Meta: verbose_name_plural = 'Files' def __unicode__(self): return self.file def __str__(self): return "{file}".format(file=self.file) def get_absolute_url(self): return reverse("Assignments:detail", kwargs={"id": self.id}) class Assignment(models.Model): name = models.CharField(max_length=100, null=True) info = models.CharField(max_length=10000, null=True) subject = models.CharField(max_length=50, null=True) created = models.DateField(default=date.today, null=True) deadline = models.DateField(default = date.today, null=True) files = models.ManyToManyField(File, blank=True, null=True) class Meta: verbose_name_plural = 'Assignments' def __str__(self): return "{name}".format(name=self.name) This is my view for posting: @login_required def teacher_assignment_add_files(request, assignment_id): if request.method == 'POST': thefile = request.FILES.get('file-assignment') file = File(file=thefile) file.save() assignment = Assignment(id=assignment_id) assignment.files.add(file.id) return redirect('teacher-detail-assignment', id = assignment_id) I have tried: thefile = request.Files['file-assignment'] This donsen't even create an object The HTML form to create a file: <form class="dropzone" action="{% url 'teacher_assignment_add_file' OBJECTID %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="fallback"> <input type="submit" type="file" name="file-assignment" enctype="multipart/form-data"> </div> </form> -
partial_update only if not exist (PATCH Django Rest Framework)
I am currently using partial_update to update info but I want to update it only if that specific field is empty. views.py class TitleViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] queryset = Title.objects.all() serializer_class = TitleSerializer def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) serializers.py class TitleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Title fields = ['pk', 'name', 'steam_appid', 'website', 'twitter'] So instead of updating for example 'twitter' field. I ONLY want to update if its empty. Also I dont want to specify 'twitter' as a field since I have many more. -
Cant Return Responce from Django View to Front end
I have Django view which is responsible return response value after the file is modified.but it didn't receive anything. import pyinotify from django.http import JsonResponse def get_all_data(request, *args, **kwargs): def onChange(ev): f = open("statics/input.txt", "r") value = f.read() print('change detected') return JsonResponse({'foo': value}) print('Started') print(os.path.join(BASE_DIR, "statics", "input")) wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm) wm.add_watch("statics/input.txt", pyinotify.IN_MODIFY, onChange) notifier.loop() what I want is when the file is modified. I want to get that data to Django template without refreshing the view.i use ajax request to get data from the back end.i couldn't understand what is wrong here. -
Trying to add email activation but Django doesn't like url
I'm trying to follow this email activation tutorial. https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef I've mimicked everything he has done. However my url is not working: path('activate/<uidb64>/<token>',views.activate, name='activate'), -
Django Populate ManyToManyField overriding save method
When i create a Mess also it requires to fill the admin field and i do it always. I want, when i create a Mess, the members field of the mess should populate automatically with the admin Here you go for my admin: class Mess(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) name = models.CharField(max_length=50, null=False, blank=False) address = models.CharField(max_length=300) admin = models.OneToOneField( Person, on_delete=models.CASCADE, related_name='mess_admin' ) members = models.ManyToManyField( Person, related_name='mess_members', blank=True, ) def save(self, *args, **kwargs): if self.admin not in self.members_set.all(): self.members.add(self.admin) super(Mess, self).save(*args, **kwargs) I want overriding save method, I want to add the admin to members field too but I don't to populate it manually, it will add the admin of the mess and the same admin will be in members field too. Can anyone help me to achive this? My current save method is not working following my requirement -
Self referencing model causing error when inserting value in the self referenced foreign key field
Here is my model class Organization(models.Model): id = models.IntegerField(primary_key=True, verbose_name='org ID', help_text='Organization ID') name = models.CharField(unique=True, max_length=255, verbose_name='org name', help_text='Organization Name') mother_org_id = models.ForeignKey( 'self', on_delete=models.SET_NULL, related_name="child_org", related_query_name="mother_org", null=True, blank=True, verbose_name='mother org', help_text='Immediate parent organization' ) As you can see, I am trying to self reference this model through the mother_org_id field. The table was created successfully using migrations. From the admin panel, I can create a new organization without any issues if I keep the mother org dropdown empty. But when I try to assign a Mother Organization to an organization, the following error occurs. ProgrammingError at /admin/organizations/organization/add/ ('42000', "[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '1'. (102) (SQLExecDirectW)") I am using SQL Server 2014. Does anyone know what's going wrong? -
int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' when calling my get method
When calling my get method on an URL on Postman, I get : TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' def get_payment_scheduler(self, id): userAccount = AccountManager.objects.get(id = id) payment_scheduler = PaymentScheduler.objects.get(userAccount=userAccount) if payment_scheduler.exists(): return payment_scheduler[0] return None AccountManager and PaymentSchedule have a one to one field Expecting something like this : { "id": 12, "purchaserId": null, "subscriptionDate": "2019-09-27", "validityDate": null, "offer": "Free offer", "priceTTC": "12.00", "tva": "0.00", "priceHT": "0.00", "hasSubscribed": true, "reader": "readerId" } -
How to add additional field to django oscar product field in dashboard
How do I add an additional field to django-oscar dashboard? I've forked catalog app added an extra field, but the form is not showing after forking dashboard. from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): file = models.FileField(upload_to='files/%Y/%m/%d') from oscar.apps.catalogue.models import * dashboard/catalogue/forms.py from oscar.apps.dashboard.catalogue import forms as base_forms class ProductForm(base_forms.ProductForm): class Meta(base_forms.ProductForm.Meta): fields = ('file',) -
Error occurs when using Pyinstaller to packing Django project
when i packing the django project, i use the pyi-makespec -D manage.py and add something userful into the manage.spec(according to the reference). Then, use pyinstaller manage.spec however, it raises ImportError. t\typhoon\typhoon2>pyinstaller manage.spec 100 INFO: PyInstaller: 3.5 100 INFO: Python: 3.7.3 101 INFO: Platform: Windows-10-10.0.17763-SP0 102 INFO: UPX is not available. 104 INFO: Extending PYTHONPATH with paths ['D:\\Data\\Pycharm_project\\typhoon\\typhoon2', 'D:\\Data\\Pycharm_project\\typhoon\\typhoon2'] 104 INFO: checking Analysis 104 INFO: Building Analysis because Analysis-00.toc is non existent 104 INFO: Initializing module dependency graph... 108 INFO: Initializing module graph hooks... 113 INFO: Analyzing base_library.zip ... 3754 INFO: running Analysis Analysis-00.toc 3771 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by C:\Users\gql\Miniconda3\python.exe 4318 INFO: Caching module hooks... 4323 INFO: Analyzing manage.py 4389 INFO: Processing pre-find module path hook distutils 8221 INFO: Loading module hooks... 8221 INFO: Loading module hook "hook-distutils.py"... 8223 INFO: Loading module hook "hook-django.core.cache.py"... 8366 INFO: Loading module hook "hook-django.core.mail.py"... 8447 INFO: Loading module hook "hook-django.core.management.py"... 8484 INFO: Import to be excluded not found: 'tkinter' 8484 INFO: Import to be excluded not found: 'IPython' 8485 INFO: Import to be excluded not found: 'matplotlib' 8485 INFO: Loading module hook "hook-django.db.backends.py"... 9506 WARNING: Hidden import "django.db.backends.__pycache__.base" not found! 9506 INFO: Loading module hook "hook-django.py"... Traceback (most … -
How to make `manage.py` search tests also in a `tests` subfolder and not only in the app toplevel directory?
This is my directory structure: ~ |--- scratchpad |--- manage.py |--- my_project |--- __init__.py |--- settings.py |--- urls.py |--- wsgi.py |--- my_app |--- __init__.py |--- admin.py |--- apps.py |--- models.py |--- tests.py |--- views.py |--- migrations |--- __init__.py The contents of tests.py are simple enough: from django.test import TestCase # Create your tests here. class TrivialTestCase(TestCase): def test_trivial(self): self.assertTrue(True) In this setting I can run my tests without problems: m@mycomp:~/scratchpad$ python3 manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Destroying test database for alias 'default'... BUT what if the tests.py file gets so large I'd like to split it into many smaller files AND move them all to a separate folder to keep the app directory clean? ~ |--- scratchpad |--- manage.py |--- my_project |--- __init__.py |--- settings.py |--- urls.py |--- wsgi.py |--- my_app |--- __init__.py |--- admin.py |--- apps.py |--- models.py |--- tests |--- tests_trivial.py |--- views.py |--- migrations |--- __init__.py Now manage.py cannot find my tests! m@mycomp:~/scratchpad$ python3 manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Destroying test database … -
How to use heroku buildpack ffmpeg for python
I want to use ffmpeg buildpack in my python app on heroku. How can I use buildpack?subprocess?os?How to call the ffmpeg? Anybody can teach me? This is my error code and I want to convert mp4 file to mp3 file. os.chdir('vendor/ffmpeg/bin') subprocess.call(['ffmpeg', '-i', 'xxx.mp4','-vn','-f mp3', 'xxx.mp3']) subprocess.call(['ffmpeg', '-i', 'xxx.mp4','-vn','-f mp3', 'xxx.mp3']) Pls help me.I am newbie in heroku -
Docker requirements can't install
I'm having some problems with starting docker on my Windows machine. First it's downloading some files as usual and after that I'm receiving messages like. WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [Errno -3] Try again')': /simple/django/ This is how my dockerfile looks: FROM python:3.7-alpine MAINTAINER Someone ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user and this is requirements.txt Django>=2.2.5,<2.2.0 djangorestframework>=3.10.3, <3.10.0 What am I doing wrong? -
set ForeignKey to be a specific model when posting data
Hi I'm fairly new to Django and I have a question. I have 2 models - Category and Comment. I want the user to be able to post a comment on each category and display them. When I'm catching the data from the form it asks me to set the category field to some default value - I want the Category model to be saved there so that I can access all comments associated with a particular category. How can I go about this problem? I'm not using forms.py, I'm just catching data in the view from html template Thank you My models class Category(models.Model): name = models.CharField(max_length=30) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) def __str__(self): return self.name class Comment(models.Model): username = models.CharField(max_length=30) comment_body = models.TextField() category = ForeignKey(Category, on_delete=models.CASCADE) My views so far def category_detail(request, category_id): # get the current category try: current_category = Category.objects.get(id=category_id) except Category.DoesNotExit(): return f"Error - there's not such category" context = { 'current_category': current_category } # handle POST request if request.method == "POST": pass #username = request.POST['username'] #comment_body = request.POST['comment'] -
How to pass a views variable to a template using Django
After checking several similar threads I still can't make it work. I want to pass a simple variable from my views.py to my index.html template. But the template displays the variable as it is in the frontend and the variable isn't passed. These are my files: views.py import requests from django.http import HttpResponse from django.shortcuts import render def liga(request): liga1 = ['1. Bundesliga', 'Premier League', 'La liga'] return render(request, 'dasocc_app/templates/index.html', {'liga1': liga1}) index.html (snip): <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="/dasocc_project/styles.css"> <link href="https://fonts.googleapis.com/css?family=Muli&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="images/dasoccfavicon.png"/> <title>DASPO</title> </head> <body> <div id="outerContainer"> <!-- Sidebar --> <div id="sidebar"> <header> <a href="#">{{ liga1 }}</a> </header> <ul class="nav"> <li class="countries"><img src="/dasocc_project/images/germany.png" alt="germany">{{ liga1 }} <ul class="subbar"> urls.py from django.urls import path from django.urls import include urlpatterns = [ path('dasocc_app', include("dasocc_project.urls")), path('templates/', include('dasocc_app.urls', namespace='dasocc_app')) ] and my project structure and the according frontend output -
unnecessary table on the django admin page. How come a table being shown on admin home page?
One of my table is being shown on the admin page. Need to remove that so how come that table being showed on admin page? actual image getting is one the picture and desired result is normal django admin page -
Serializer return incorrect output
Hello ! I have a model: class Route(models.Model): name = models.CharField("Номер маршрута", max_length=100) evotor_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="пользователь эвотор", on_delete=models.CASCADE) nds_CHOICES = ( (0, 'БЕЗ НДС'), (1, 'Основная ставка 0%'), (2, 'Основная ставка 10%'), (3, 'Расчётная ставка 10%'), (4, 'Основная ставка 18%'), (5, 'Расчётная ставка 18%') ) nds = models.IntegerField('НДС', choices=nds_CHOICES, default=0) def __str__(self): return self.name class Meta: verbose_name = "Номер маршрута" verbose_name_plural = "Номера маршрутов" And i have serializer for that model: class RouteSerializer(serializers.ModelSerializer): class Meta: model = Route fields = ("id", "name", "nds") My APIView class CarView(APIView): authentication_classes = (BearerAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request): if 'route_id' not in request.GET or request.GET['route_id']=="": #return Response({'message': 'Не указан ID маршрута'}, status=status.HTTP_400_BAD_REQUEST) car = Car.objects.filter(evotor_user=request.user) else: car = Car.objects.filter(route__id=request.GET['route_id']) serializer = CarSerializer(car, many=True) print(serializer.data) return Response(serializer.data) use this serializer class CarSerializer(serializers.ModelSerializer): route = RouteSerializer class Meta: model = Car fields = ("id", "name", "route") and must return me output like this: [ { "id": 1, "name": "dfgdfgdfg", "route": { 'id': 1, 'name': 'route_name', 'nds': 0, } } ] But it return: [ { "id": 1, "name": "dfgdfgdfg", "route": 1 } ] -
Count all products in all subcategories recursively
So far I have only been able to count products from one child category: <div class='categories'> <ul> {% for category in categories %} <li class='category'><a href="/shop/category/{{ category.slug }}">{{ category.name }}</a></li> {% for child in category.get_children %} <li class='subcategory'><a href="/shop/category/{{ child.slug }}">{{ child.name }} ({{ child.product_set.get_queryset.count }})</a></li> {% endfor %} {% endfor %} </ul> </div> I need to count all products that are in 'child' category and its descendants, so there may be Books -> Textbooks -> Primary school, currently I'm only getting Textbooks, and I need to get Primary school too. Is it possible to count all products in all subcategories recursively? -
How to use HyperlinkedModelSerializer in Django 2.1
I am not able to render the list of books from the configuration below. What I am trying to achieve is just to display the link to detail object via HyperlinkedModelSerializer from the API list of objects. Not sure what i am doing wrong. I keep getting this error message from the console. Could not resolve URL for hyperlinked relationship using view name "book-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Codes below: models class Book(models.Model): title = models.CharField(max_length=250) subtitle = models.CharField(max_length=250) author = models.CharField(max_length=100) isbn = models.CharField(max_length=13) serializers.py from rest_framework import serializers from rest_framework.serializers import HyperlinkedIdentityField from .models import Book class BookSerializer(serializers.HyperlinkedModelSerializer): id = HyperlinkedIdentityField(view_name='api:detail', lookup_field='id') class Meta: model = Book fields = ('url', 'id', 'title', 'subtitle', 'author', 'isbn') PROJECT urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('books.urls', namespace='books')), path('api/v1/', include('api.urls', namespace='api')), path('api-auth/', include('rest_framework.urls')) ] APP urls.py from .views import ( BookList, BookDetail, ) app_name = 'api' urlpatterns = [ path('', BookList.as_view(), name='list'), path('<int:pk>/', BookDetail.as_view(), name='detail'), ] views.py class BookList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) queryset = Book.objects.all() serializer_class = BookSerializer class BookDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (permissions.IsAuthenticated,) queryset = Book.objects.all() serializer_class = BookSerializer Any help would be much … -
I want to make individual multi database calls to one atomic transactions in django?
I am making multi db connections . I want to execute them as if either all will execute or none. I have done a lot of research. In docs it is not mentioned anything about multi db connection. There are few question is stackoverflow but none of them answer perfectly. how to do it ? @transanction.atomic def view(): call to db1 call to db2 -
I am having an error that says "ModelForm has no model class specified."
i was just watching a tutorial in youtube and i was just following what was indicated buti still got those errors. Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(max_length = 50) class Meta: model : User fields = ['username', 'password1', 'password2'] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('home') else: form = UserRegisterForm() return render (request, 'users/register.html', {'form':form}) -
django markdown_deux table made some unintentional br
i'm using markdown_deux for rendering the content of markdown blog. i have a content like this and then it is rendering this. it's result of {{ document.content |markdown|linebreaksbr}} how can i remove this tag? i removed linebreaksbr on jinja2 tag, but there were some error for me. such as several br be the one br. i changed likebreaksbr to linebreaks, it cause same result with linebreaksbr i added safe tag, then everything not changed. MARKDOWN_DEUX_STYLES = { "default": { "extras": { "code-friendly": None, "tables": None, }, "safe_mode": "escape", }, } -
Keeping Pipfile Updated
I just started a new Django project and use Postgresql as my database, so I installed psycopg2 to make it work properly. When i deployed the project in the beginning the app did not work because psycopg2 was not installed on the production server. As i quickly realized this was because psycopg2 was missing in my pipfile. So my question is: Do I have to update the pipfile manually every time i install something for my project? I thought that the pipfile would take care of that automatically every time I install something. Isn't there anything similar to pip freeze > requirements.txt where I can do the update with one short command? -
Polymorphic model from Laravel as Django model
I have database from Laravel project where polymorphic models (morphMany) are used a lot. It is posible to write model in Django what will behave like Laravel polymorphic model? For example: tables products id sku ean13 price posts id created_at translations id translatable_id translatable_type(it could be post or product) name description locale and it's possible that solution will work with admin? -
Django Rest Framework with Python Social Auth (social django)
I just created API for my app with DRF, but for auth I used social_django as shown in this article. And my question is: How to make this work with my create-react-app frontend? I was suprised when I was searching for it, because I didn't find as much quality articles as I excepted. I tried pasting social url into hyperlink like this: <a href = "https://accounts.google.com/signin/oauth/oauthchooseaccount?client_id=253704111438-md6c0imb8hkhj4iarg1jrh6f2jrbrkgn.apps.googleusercontent.com&as=FkHzlQkxuMO1ir0bHgz69g&destination=http%3A%2F%2Flocalhost%3A8000&approval_state=!ChRfMHdxRmNEUktvenhYdGJYWThzRRIfazFpem5GSWF0TllSMEVBN1JaNXdOM09kT1NkMTF4WQ%E2%88%99AJDr988AAAAAXZCBO7LlO41mevk2lXGOcoJevBq1l5Yi&oauthgdpr=1&xsrfsig=ChkAeAh8T07oAT9u1JjU2f8xCPDu- QJthl9lEg5hcHByb3ZhbF9zdGF0ZRILZGVzdGluYXRpb24SBXNvYWN1Eg9vYXV0aHJpc2t5c2NvcGU&flowName=GeneralOAuthFlow"> but, when I tried to login to account that I already used when testing my API it throws these errors: AuthAlreadyAssociated at /auth/complete/google-oauth2/ This account is already in use. Should I try to get path of {% url 'social:begin' 'google-oauth2' %} and pass it to React? Or you know any better way to do it? -
TypeError at /admin/myapp/mymodel when trying to access django admin, after I changed some model fields (Django)
I am developing an app in Django. It was working fine until I renamed some fields in my model. I have run migrate and makemigrations. Then, when I log in as admin ad try to access "mymodel" in section "myapp", this is what I get: TypeError at /admin/myapp/mymodel/ not enough arguments for format string What's the problem? (Everything else in my app works perfectly until it comes to access the model contents inside admin page) I post the complete error message here: TypeError at /admin/myapp/mymodel/ not enough arguments for format string Request Method: GET Request URL: http://127.0.0.1:8000/admin/myapp/mymodel/ Django Version: 2.2.2 Exception Type: TypeError Exception Value: not enough arguments for format string Exception Location: C:\Users\Tommaso\Django rest framework\Udemy Django\Myproject\myapp\models.py in str, line 95 Python Executable: C:\Applicazioni_Tommaso\Phyton\python.exe Python Version: 3.6.5 Python Path: ['C:\Users\Tommaso\Django rest framework\Udemy ' 'Django\Myproject', 'C:\Applicazioni_Tommaso\Phyton\python36.zip', 'C:\Applicazioni_Tommaso\Phyton\DLLs', 'C:\Applicazioni_Tommaso\Phyton\lib', 'C:\Applicazioni_Tommaso\Phyton', 'C:\Applicazioni_Tommaso\Phyton\lib\site-packages', 'C:\Applicazioni_Tommaso\Phyton\lib\site-packages\pip-19.1.1-py3.6.egg'] Server time: Sat, 28 Sep 2019 08:56:32 +0000 Error during template rendering In template C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 62 not enough arguments for format string 52 {% endblock %} 53 54 {% endif %} 55 {% endblock %} 56 {% block nav-global %}{% endblock %} 57 58 59 {% block breadcrumbs %} 60 61 {% trans 'Home' %} 62 {% …