Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add custom button in django admin to run django management command
I have to add an Update button in one of the model at my django-admin page and match_action is an update button on django-admin and match_status is my management command, here is my code , actually I want , when I click update button I want to run a service named as goalserveService using management command admin.py` @admin.register(Match) class MatchAdmin(admin.ModelAdmin): list_display = ['id', 'start_time', "home_club", 'away_club', 'created_on', 'status', 'lookup_id', 'timer', 'match_actions'] search_fields = ['id', 'home_club__name', 'away_club__name'] list_filter = ['status', 'season', 'start_time'] inlines = [ MatchLookupInline, MatchEventInline, ] def lookup_id(self, obj): if obj.matchlookup_set.all().exists(): return obj.matchlookup_set.get().source_match_id else: return None def get_urls(self): urls = super().get_urls() custom_urls = [ url( r'^(?P<match_id>.+)/update/$', self.admin_site.admin_view(self.match_update), name='match-update', ), ] return custom_urls + urls def match_actions(self, obj): print (obj.id) return format_html( '<a class="button" href="{}">Update</a>', reverse('admin:match-update', args=(obj.id,)), ) def match_update(self, request, match_id, *args): from django.core.management import call_command call_command("match_status", match_id) core/management/commands/match_status.py from django.utils import timezone from django.core.management.base import BaseCommand, CommandError from core.models import UserTeam from ourapp.models import Match class Command(BaseCommand): help = 'Update Match Status' def add_arguments(self, parser): parser.add_argument('match_id', nargs='+', type=int) def handle(self, *args, **options): # NOT_STARTED = 0 # HF = 1 # FT = 2 # IN_PLAY = 3 # FINISH = 4 match = Match.objects.filter(id=options.get('match_id')) self.stdout.write(self.style.NOTICE("Match competition Name … -
Django - template - check if a field has attribute
forms.py class someForm(forms.ModelForm): class Meta: model = someModel field = '__all__' widgets = {'length': forms.TextInput(attrs={'class': 'has-checkbox'})} I gave a form field an attribute like the above. The goal is to add an HTML code row that has checkbox. Something like this: {% if field hasAttr('has-checkbox') %} <input type="checkbox"> {{ field }} {% end if %} The problem is that I do not know Django Template version of code that does what hasAttr() does. This is a random function that I just made up to ask question here. How can I do this? -
How to properly populate Docker Django image with data from Postgres?
so I wanted to create a Docker image for my Django project called mysite that has two apps tracks and users. I used docker build -t mysite to build my docker image. I have written a Dockerfile like it says on dockerhub. Then i created docker-compose.yml file and bash script entypoint.sh that I use in docker-compose file. These are my files: Dockerfile: FROM django:onbuild COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh docker-compose.yml: version: '3' services: db: image: postgres restart: always container_name: postgres_container environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres - DJANGO_SETTINGS_MODULE=mysite.settings_docker ports: - 5432:5432 volumes: - /var/lib/postgresql/10/main web: image: mysite:latest build: context: . dockerfile: Dockerfile container_name: mysite_container ports: - "8000:8000" depends_on: - db environment: - DJANGO_SETTINGS_MODULE=mysite.settings_docker entrypoint.sh #!/bin/sh python manage.py makemigrations python manage.py migrate python manage.py runserver 0.0.0.0:8000 exec "$@" So when I wanted to start the whole container I used following commands docker build . docker-compose build docker-compose up My database in settings.py is DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } My database in settings_docker.py, that I use in container is DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': … -
Dealing with Multiple Databses in Django 1.10
I have a Django website which is connected to a legacy database. My project structure is as follows: PLC -> Python Scripts -> Data -> Legacy dB -> Django -> Web Page I now want to get user data from the web page and pass it back to the python scripts such that calculations are performed according to the user's needs. So in essence: Web Page -> User Input -> Django -> database -> Python Scripts I have managed to get the user dat into my views.py and asking about suggestions when it comes to dealing with multiple databases. Considering that the datbase is a legacy databsae created and maintained by the python scripts should I: Allow Django to modify the existing legacy database and add data. This will allow me to simlpy read from the same database from my python scripts. Create a new database and access the new database from my python scripts. Those are the two main options I have thought of. How should one go about this implementation? -
Django; How to do conditionals for custom templatetags
I've been working on Django project. Seems like conditionals doesn't work for templatetags. How can I make it work? my custom templatetag is like this. register = template.Library() @register.simple_tag(takes_context=True) def get_counts(context): ... return counts and in templates {% load app_name_tags %} ... {% if not get_counts == 0 %} {% get_counts %} {% endif %} but this conditional doesn't work. How can I fix this? -
JSONField in Serializers of Django Rest Framework
I am trying to create a serializer which has only one JSONField class DataSerializer(serializers.Serializer): data = serializers.JSONField() When I am trying to use this serializer in the shell as - >>> s = DataSerializer(data={"name": "Tom"}) >>> s.is_valid() False >>> s.errors {'data': [ErrorDetail(string='This field is required.', code='required')]} I don't know what I am doing wrong. Please bear with me if its a too simple question as I am new to using DRF. -
Django TypeError: id() takes exactly one argument (0 given)
So I have been trying to implement a way to upload multiple images to a post. The way I did it is to have tables. One for the actual post, and one of the multiple images uploaded. I was planning to link them with a foreign key but it is not working. My terminal started throwing the error "TypeError: id() takes exactly one argument (0 given)" . It throws me this error whenever I migrate it. I am not sure how to fix this. MY code: models.py from django.db import models from django.utils import timezone from django.forms import ModelForm from django.utils.text import slugify from django.utils.crypto import get_random_string from django.conf import settings from PIL import Image import os DEFAULT_IMAGE_ID = 1 # Create your models here. class Projects(models.Model): title = models.CharField(max_length=30) description = models.TextField(max_length=150) publish_date = models.DateTimeField(auto_now=False, auto_now_add=True) update_date = models.DateTimeField(auto_now=True, auto_now_add=False) slug = models.SlugField(unique=True) files = models.FileField(upload_to='files/', blank=True) images = models.ImageField(upload_to='images/', height_field = 'img_height', width_field = 'img_width',blank=True) img_height = models.PositiveIntegerField(default=600) img_width = models.PositiveIntegerField(default=300) #feature_images = models.ForeignKey(P_Images, on_delete=models.CASCADE, default=DEFAULT_IMAGE_ID) feature_images = models.AutoField(primary_key=True) def __str__(self): return self.title def save(self, *args, **kwargs): # Generates a random string unique_string = get_random_string(length=32) # Combines title and unique string to slugify slugtext = self.title + "-" … -
Customize Packages
I'm new in Django and python, so I don't know the best way to customization. so what I want is I have installed a captcha package, I want to some modification in that package. so question is what is the best way to customize that package? -
any way to import old django project models while installing wheel package in new virtualenv
python3 setup.py sdist bdist_wheel I build wheel package using above command and get below files --dist/ --example-0.1-py3-none-any.whl --example-0.1.tar.gz I install example-0.1-py3-none-any.whl package using pip install example-0.1-py3-none-any.whl in new virtualenv and also able to import my old django application using import example from examples.reports_apis.views import exampleDef But when I using its functions using above code then it gives error home.models is not module. Then I change code inside python package as from home.models to example.home.models and also add example in installed app in django settings.py Now able to use exampleDef function. But Now facing database error. Question 1.) Is there any way to automatically migrate old project DB models to new Project Virtualenv Question 2.) Is there any way to do not do below thing every time after installing my old django project in new virtualenv using wheel home.models to example.home.models Is I miss anything while creating wheel Package? Please suggest me any solution to fix above issues. Thanks in Advance -
How to populate(get the data filled) the modelform with the user data?
This is my models.py. from django.db import models from django.contrib.auth.models import User class User_data(models.Model): user_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) def __str__(self): return self.name This is my forms.py from django import forms from lrequests.models import User_data class UserForm(forms.ModelForm): class Meta: fields = ("name", "user_ID") model = User_data This is my views.py from django.shortcuts import render from django.http import HttpResponse from .forms import UserForm from django.shortcuts import render_to_response from .models import User_data def get(request): form_class = UserForm if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): data = form.save(commit = False) data.user = request.user form.save() return HttpResponse("Sucessfully submitted") else: form = UserForm() return render(request, "request_form.html", {'form' : form_class}) Now, I've tried populating the user data, which was specified whilst creating account. So, that he(user) doesn't tamper the data (as it need to read-only) and it is automatically filled without the user giving the input. I've read django documentation but it specifies only dynamically initialising data see here. I've tried putting that code in the forms.py, but it didn't work. I've even tried in the HTML template, that didn't work too. {% csrf_token %} <div class="form-row"> {{ form.name.errors }} {{ … -
html form to firebase storage with Django
I want to get and save iamge file and get firebase storege's url. HTMLform send POST with <input type="file" multiple> And Django's view def image(request) get request from django.shortcuts import render from django.http import Http404, HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required from django.utils import timezone from django.contrib.auth.models import User import firebase_admin import time, datetime from firebase_admin import credentials, auth, firestore, storage import os import json def image(request) locate_url = request.FILES['file'] firebase_key = os.environ["FIREBASE"] cred = credentials.Certificate(json.loads(firebase_key)) firebase_admin.initialize_app(cred, {'storageBucket':'xxx.appspot.com'}) db = firestore.client() db = firestore.client() filename = str(time.time()) blob = storage.bucket().blob('imgae/' + filename + locate_url[-4:]) blob.upload_from_filename(locate_url) blob.make_public() -
Ionic app post fails with "Referer checking failed - no Referer."
From the Django docs: Django’s CSRF protection requires that the request have a Referer header that matches the origin present in the Host header. Using Ionic 3.9.2 (Angular 5.2.10), how does one satisfy this requirement when posting forms since one can't add the referer header? Disabling csrf protection is not an option. The same URL works via browser (even Ionic's in-app browser but the experience is just not desirable). I'm posting JSON data. My code: let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded', 'HTTP_X_CSRFTOKEN': csrftoken}); return this.http.post( hostUrl + "/auth/reset_password?org=" + org, body, {headers: headers} ).toPromise(); -
How to call postgres function in Django with OUT parameter
I've created a simple function in postgres as below: CREATE OR REPLACE FUNCTION test_django(p_a int, p_b int, out p_cursor refcursor, out p_int int) RETURNS record AS $BODY$ begin p_cursor := 'test_cursor'; open p_cursor for select id, name, des from test; p_int := 100; END $BODY$ LANGUAGE plpgsql; I want to call this function via Django and get 2 OUT parameters. one is cursor and one is INTEGER; Is there any way to pre-register those parameters like Java? Thanks. -
Django problems with database
Hello I'm getting problems with my Django db. this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'MConDb', 'USER': 'postgres', 'PASSWORD': 'KODOkona880,', 'HOST': 'localhost', 'PORT': 5432, } } This is the error I'm getting. conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: FATAL: database "MConDb" does not exist and this is the list shown by the command \l in postgres Name | Owner | Encoding | Collate | Ctype | Access privileges ----------------------+----------+----------+----------------------------+--- django | postgres | UTF8 | English_United States.1252 | English_United States.1252 | mcondb | postgres | UTF8 | English_United States.1252 | English_United States.1252 | postgres | postgres | UTF8 | English_United States.1252 | English_United States.1252 | hope you could help me, I'll be very grateful thank you. -
Django: Do something when user goes to a listview page
I have a notifications page that collects notification actions when someone does something. I want to be able to run a command on my notificaitons model to set all of my objects to read when the user goes to the page. How can I do that when I'm using a class based list view? -
How to instantiate object with custom auto-incrementing field in Django?
I'm working on an application which needs to import some data from an old database - let's say IDs one through one million. The IDs from the old database will be loaded into an integer column which is unique but will no longer be the primary key. While loading old data (and afterwards) entries created in the new system should be assigned a serial ID starting at three million so that there is definitely space to import all the old entries over some time without getting collisions. This is currently implemented with a a migration doing ALTER SEQUENCE […] START 3000000 and a custom field type: import typing from django.db import models, ConnectionHandler from psycopg2.extensions import AsIs class SerialField(models.IntegerField): def db_type(self, connection: ConnectionHandler) -> str: return 'serial' def get_db_prep_save(self, value: typing.Optional[int], connection: ConnectionHandler) -> typing.Union[int, AsIs]: if isinstance(value, int): # so we can override the default with our own value return value return AsIs('default') The problem with the current solution is that when creating an object having a SerialField the value of the field is None rather than the actual value saved in the database. Can I change SerialField so that I don't have to manually sync the returned object … -
Simple way to access a model grandchildren?
I have this model classes: class Proficiency(models.Model): name = models.CharField(max_length=40, unique=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='children') class ProfessionalProfile(models.Model): user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) class ProfessionalProficiency(models.Model): proficiency = models.ForeignKey(Proficiency, on_delete=models.CASCADE, unique=False) professional_profile = models.ForeignKey(ProfessionalProfile, on_delete=models.CASCADE, unique=False) What is the correct way to access the data from UserProfile to ProfessionalProficiency? -
Django gives 502 Bad Gateway error when uploading a file
I have a file upload form which is defined below <form method="post" enctype="multipart/form-data", action="/api/file_upload" style="padding: 15px;"> <!-- {% csrf_token %} --> <label style="display: table-cell;">Upload</label> <input type="file" name="file"> <div class="container-fluid" style="padding:5px"> <button type="submit" style="width:100px;border-radius:50px;font-family: NunitoSans-Regular;height:20px;background-color:#fff;border:1px solid rgb(66, 66, 66);color:black;padding: 0px;" class="btn btn-primary pull-right">Upload</button> </div> </form> Here is my urls.py file based on the action defined url(r'^api/file_upload$', ui_server.store_file, name='store_file') Here is the function defined for the file upload @csrf_exempt def store_file(request): if request.method == "POST": logged_in_user = request.user.username # now get the uploaded file client_file = request.FILES['file'] file_path = /home/ec2-user/uploads/ + "" + org + "/" print("client file name", client_file.name) # the file is going to be an instance of UploadedFile try: with open(file_path + '%s' % client_file.name, 'wb+') as dest: for chunk in client_file.chunks(): dest.write(chunk) # return success message print("file created") return HttpResponse('Success') except Exception as e: print(e) return HttpResponse('Failure') finally: # process the client file result = read_client_file() print(result) Now I am able to upload a file and store it in appropriate path.But the function read_client_file() takes some time to read the file and process it.Which is why I define a return statement for successful upload of file and continue the processing in a finally block. But this does't help … -
ValueError when trying to save to ImageField
AIM I am attempting to render an image based on data in the db. I suspect that the issue may be with the directory ("mapping_twitter/images/histogram.png) that I'm attempting to save the image too. ERROR Exception Type: ValueError Exception Value: The 'histogram' attribute has no file associated with it. CODE Models.py class Hashtag(models.Model): """ Model representing a specific Hashtag serch by user """ search_text = models.CharField(max_length=140, primary_key=True) location = models.ManyToManyField(Location, blank=True) histogram = models.ImageField(upload_to='img', blank=True) def __str__(self): return self.search_text def display_locations(self): """ Function to create a dict by frequency of the locations associated with search_text """ country_list = list(self.location.values_list('country', flat=True).all()) for country in country_list: location_freq = {i:country_list.count(i) for i in set(country_list)} return location_freq @property def get_histogram(self): """ Function to create a histogram of locations associated with search_text """ location_freq = self.display_locations() plt.bar(list(location_freq.keys()), location_freq.values(), color='g') f = io.BytesIO() # redirect into the BytesIO object plt.savefig(f, "mapping_twitter/images/histogram.png", facecolor=(0.95,0.95,0.95)) content_file = ImageFile(f) HTML <img src="{{ hashtag.histogram.url }}" alt="Histogram" /> -
How to get Flight name based on From and To Fields in Django models?
I have a Model called ticket in Django. class ticket(models.Model): From = models.CharField(max_length=200) To = models.CharField(max_length=200) Flightname = models.CharField(max_length=200) We will get the From and To data from the Frontend. How to return the flightnames that match from and to.? -
" RuntimeError: Model class wagtail.core.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS"
I was trying to add wagtail cms to react application using GraphQL and Python+Django on the back end. When I try to migrate i get this error. How can i solve this error? I followed Brent Clark on wagtail site. pip freeze gives:aniso8601==3.0.2 beautifulsoup4==4.6.3 certifi==2018.8.13 chardet==3.0.4 Django==2.0.8 django-modelcluster==4.2 django-taggit==0.23.0 django-treebeard==4.3 django-webpack-loader==0.6.0 djangorestframework==3.8.2 draftjs-exporter==2.1.2 graphene==2.1.3 graphene-django==2.1.0 graphql-core==2.1 graphql-relay==0.4.5 html5lib==1.0.1 idna==2.7 iso8601==0.1.12 Pillow==5.2.0 promise==2.1 psycopg2==2.7.5 pytz==2018.5 requests==2.19.1 Rx==1.6.1 singledispatch==3.4.0.3 six==1.11.0 typing==3.6.4 Unidecode==0.4.21 urllib3==1.23 wagtail==2.1.2 webencodings==0.5.1 Willow==1.1 Thanks in advance for your support! -
Adding Sum of Object Attributes to Django Rest Framework Response
I'm Trying to add the sum of multiple objects to a DRF response. For example, right now the response works with just listing the objects: [ { "id": "47d0deaa5c8c", "amount": "25.00" }, { "id": "29787731", "amount": "25.00" } ] But what I want is to be able to sum the amount attribute of those objects together and then include that in the response, so that it would look like this: { "sum":"50.00", "objects":[ { "id":"47d0deaa5c8c", "amount":"25.00" }, { "id":"29787731", "amount":"25.00" } ] } Here's my current APIView: class TransactionsList(GenericAPIView): """ Retrieve list of transactions """ authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request): """List Transactions""" transaction = Transaction.objects.all() serializer = TransactionSerializer(transaction, many=True) return Response(serializer.data) And Serializer: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ('id', 'amount') How could I efficiently go about adding the sum field into the response? -
Run a python script on amazon web service on beanstalk?
I just recently completed a school project. i want to put the code I have written on the cloud platform for computing. I hope that i could do that on cloud server, now we set the current user interface is set on the android app, i have tried django and amazon elastic beanstalk as the operation Platform. But i found that i can't set the input parameter and retrieve the return value from server.(i knew that it could return on the web page, but i need to get the return value on the android app) Can I do it through existing resources? Or need to start from those aspects -
Django Rest Framework get serializer of different model?
I have a method in one of my viewsets: Endpoint: /api/game/{id}/sessions: from .serializers import GameSerializer from .models import Game from gamesessions.models import GameSession from gamesessions.serializers import GameSessionSerializer from gamesessions.viewsets import GameSessionViewSet @action(methods=['get'], detail=True) def sessions(self, request, **id): game = self.get_object() sessions = [] for session in GameSession.objects.filter(game=game.id): sessions.append(session) serializer = GameSessionViewSet.get_serializer(sessions, many=True) return Response(serializer.data) But I'm getting an error because I can't figure out where the get_serializer method comes from and/or how to implement it externally. I need to get the serializer of the session model. I can generate the list of sessions just fine, but it says the object is not JSON serializable, which is what DRF is supposed to handle. So I just need to know what do I import to get the seralizer from the other class? -
Not Null constrain failed Integrity Error
Hi I am having trouble figuring out how to solve this error. I was creating a form to be able to add new topics to a website I am working on. After creating the form and trying to use it to submit a request to add a new topic I got a integrityError which I haven't encountered before. After doing some research I know it has something to do with a foreign key relationship where there is a field that is empty inside the database but I am not sure how to root cause it. here is my Models.py file: from django.db import models # Create your models here. class Category(models.Model): """A category the user is writing about""" text = models.CharField(max_length=200) class Meta: verbose_name_plural = 'Categories' def __str__(self): """Return a string represtation of the model.""" return self.text class Topic(models.Model): """A topic that is associated with a certain Category""" category = models.ForeignKey(Category, on_delete=models.CASCADE) text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Topics' def __str__(self): """Return string represtation of the model.""" return self.text class Entry(models.Model): """A entry associated with a certain topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Entries' def __str__(self): """Return …