Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am having this TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType' in Django code
Am using fusion chart to create a histogram below is the code for my data source, the line in bold throws a dataType error, which I have searched everywhere to find to no avail. datasource['data'] = [] for item in get_employee_overall_performance(emp_id, year, period): data1, data2 = {}, {} data1['label'], data2['label'] = '% Achieved','% Unachieved' **data1['value'], data2['value'] = item['score']/item['weight']*100, 100 -item['score']/item['weight']*100** datasource['data'].append(data1) datasource['data'].append(data2) doughnut3d = FusionCharts("doughnut3d", "ex3" , "100%", "400", "emp-perf-donutchart", "json", datasource) -
Force a cascading delete for a Django model
I have a Django model with foreign-key relations that are marked as deletion.PROTECT, and I am OK with that behavior, since it's how the model should behave in most scenarios. However, there is one use case for those models where I kind of need to do a "hard delete" (ie user wants to delete their account). In that case, I'd really like everything to behave like a CASCADE, instead of having to delete each of the foreign-key relationships manually. Is there a way to do this cleanly? In an ideal world, the model.delete() call would take a parameter that is something like force_cascade=True. -
How to add django event stream javacsript file to react project?
Django event stream is a community project on top of channels 2 python package. I have a repo that has both Django project and react project in it. It is deployed on heroku. The static files are generated first. The react project is built next. Django static files serve the react build folder. I did not find a npm package for django event stream. How to add the scripts such that the event stream can be read from the browser? https://github.com/fanout/django-eventstream#receiving-in-the-browser Source code of my project: https://github.com/pmontu/fulfil.io -
What is the way used by the ORM Django for the B-tree index?
I have this B-tree each number is the id of a member How the ORM Django count each element (with this select : SELECT count(*) FROM member , the way used is: 23 -> 11 -> 33 -> 1 -> 13 -> 25 -> 77 or 23 -> 11 -> 1 -> 13 -> 33 -> 25 -> 77 And how the ORM Django travel the B-tree with thes select : SELECT last_name FROM member SELECT * FROM member ORDER BY member_id The travel is level by level or branch by branch ? -
Pictures not saving in media folder
I noticed that when I upload a profile picture the picture is not being saved in my media directory. I have manually created the folder and referenced it in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) ... class Mentor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) linkedin = models.URLField(max_length=200,null=True,blank=True) photo = models.ImageField(null=True, blank=True, upload_to='media') forms.py #basic form class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name','last_name','email') # edit mentor profile class MentorProfileForm(forms.ModelForm): class Meta: model = Mentor fields = ('photo',) and views.py: def edit_user(request): user = request.user # form = MentorProfileForm(instance=user) if request.method == 'POST': form = UserForm(request.POST, request.FILES, instance=user) mentorform = MentorProfileForm(request.POST, request.FILES, instance=user) if form.is_valid() and mentorform.is_valid(): form.save() mentorform.save() messages.success(request, ('Your profile was successfully updated!')) return HttpResponseRedirect('%s' % (reverse('teachers:edit_user'))) else: messages.error(request, ('Please correct the error below.')) else: form = UserForm(request.POST, instance=user) mentorform = MentorProfileForm(request.POST, request.FILES, instance=user) return render(request, 'classroom/teachers/app-instructor-profile.html', {'form': form, 'mentor_form': mentorform}) -
I want to fix this Vue.js project issue
I am a beginner of Vue.js developing. I have just built a new project with Python + Django + Vue I faced this issue : The value for a v-bind expression cannot be empty. Found in "v-bind:" My Vue code is this: (testdjango.vue) <template> <div id="mineapp"> {{msg}} <form @submit.prevent ="submitNote"> <label>Title</label> <input type="text" v-model="formData.title"/> <label>Content</label> <textarea v-model="formData.content"></textarea> <br/> <button type="submit">Submit</button> </form> <br/> <h1>All Notes</h1> <ul> <li v-for="(note, index) in notes" : key="index"> <h3>{{note.title}}</h3> <h5>Created on{{note.created}}</h5> <p>{{note.content}}</p> </li> </ul> </div> index.js code: export default{ fetchNotes(method, params, data){ if(method ==='post'){ return ajax('api/notes/', method,{data}) } else{ return ajax('api/notes/', 'get', {}) } function ajax(url,method,options){ if(options !== undefined){ var{params=[], data={}} = options } else{ params = data = {} } return new Promise((resolve, reject)=>{ axios({ url, method, params, data }).then(res => { resolve(res) }, res=>{ reject(res) }) I hope somebody will help to fix this issue. thanks... -
Retrieve data from Django API and store it in database
I created an API with django What I want to do is to fetch data from my django API and store it in my database. serializers.py from rest_framework import serializers, generics from Usersapi.models import Userdata class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Userdata fields = '__all__' viewsets.py from Usersapi.models import Userdata from .serializers import UserSerializer from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): queryset = Userdata.objects.all() serializer_class = UserSerializer main--> urls.py from django.contrib import admin from django.urls import include, path from rest_framework.urlpatterns import format_suffix_patterns from .router import router urlpatterns = [ path('admin/', admin.site.urls), # path('',include('Usersapi.urls')), path('client/',include('clientside.urls')), path('api/', include(router.urls)) ] This is where I am trying to retrieve data from API clientside--> views.py from django.shortcuts import render import coreapi import json from django.views import generic import io from rest_framework.parsers import JSONParser def home(request): client = coreapi.Client() response = client.get('http://127.0.0.1:8000/api/Usersapi/1/') stream = io.BytesIO(response) data = JSONParser().parse(stream) name = data.get("name") age = data.get("age") gender = data.get("gender") user = UserReceived.objects.create( name = name, age= age, gender = gender) user.save() return render(request, 'books.html') This code is not working. How do I retrieve the data from ('http://127.0.0.1:8000/api/Usersapi/1/') and store it in my models.py i.e database clientside --> models.py from django.db import models class UserReceived(models.Model): name = models.CharField(max_length=100) age = … -
How can I make django write faster to database
I've a django project with postgresql backend. An app is structured somewhat like class Patient(models.Model): health_insurance_number = models.CharField(max_length=100) card_number = models.CharField(max_length=100) surname = models.CharField(max_length=256) firstname = models.CharField(max_length=256) gender = models.CharField( max_length=10, choices=( ('Male', 'Male'), ('Female', 'Female'), )) dob = models.DateField() info = models.ForeignKey(SomeClass, on_delete=models.CASCADE) At the end of every month, the client receives and updates the informatiton of it's patients. New patient records uploaded monthly is as high as 400,000 records. Currently with postman, saving 1000 records takes ~6seconds 4000 records takes ~23seconds 1000 records on four different requuests (total 4000 records) take ~23seconds. With this math, saving 400K records would take ~40 minuets. Is there a way to make this better? -
Cannot Load Dhango Fixtures into database
I am able to load 1 fixture file into the database, but not the 2nd file. I run the command python manage.py loaddata fixture.json, and I get the error. I'm not sure how to solve this serialization error, any insights appreciated. The error: for obj in objects: File "/Users/ayunas/.local/share/virtualenvs/CS24-BW-MUD-lJVJyZQx/lib/python3.7/site-packages/django/core/serializers/json.py", line 73, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/ayunas/Documents/lambda/CS24-BW-MUD/tower_app/fixtures/test_fixture.json': Here is how the fixture file looks like: [ { "model": "tower_app.item", "pk": 1, "fields": { "item_name": "Black Stone", "description": "a white stone from Paradise, blackened by the sins of mankind.", "strength": 10, "item_type": "weapon", "playerID" : null, "roomID" : 4 } }, -
Custom Gitlab CI docker image for job
I have application in Django. Requirements consist of many libraries. After linting stage in Gitlab CI I would like to run some tests I wrote. To be able to run Postgres and Django I have to install requirements, it take some time. Is there some easy way how to cache that image with all installed requirements or I have to install it all again every time I want to run that tests? It is impractical according to me. I could have job before test where I would build my custom image based on requirements and image I build last time, as cache image. I could keep custom image in personal registry and use it in next job with tests. linting --> build_job_image --> tests --> staging --> production It looks like better way than install it every time, but still not the best idea. I am new with DevOps so I am trying to find the best way, don't know what is the best practice. I am using python:3.7-alpine image for this job. -
How do I call an API from a Django Model based on one field
I hope someone can help. I am very new to django and programming. I want to populate a number of fields based on the website field below. I send the website as a parameter to the API and it returns a number of values in JSON. I then want to send it store it in the model for that instance. Any help or guidance would be greatly appreciated class newURLposts(models.Model): created_on = models.DateTimeField(auto_now_add=True) website= models.URLField(max_length=250) domain = models.TextField(blank=True) host = models.TextField(blank=True) url = models.URLField(blank=True) img = models.ImageField(upload_to='link/img/',blank=True) title = models.TextField(blank=True) description = models.TextField(blank=True) favicon = models.ImageField(upload_to='link/favicon/',blank=True) def save(self, *args, **kwargs): review_url = self.website u = "u=" + review_url r = "&r=#####" e = "&e=#####" t = "&t=json" PARAMS12 = u + r + e + t URL = "#####" site = requests.get(url = URL, params = PARAMS12) parsed_site = json.loads(site.content.decode('utf-8')) self.domain = parsed_site["domain"] self.host = parsed_site["host"] self.url = parsed_site["url"] self.img = parsed_site["img"] self.title = parsed_site["title"] self.description = parsed_site["description"] self.favicon = parsed_site["favicon"] super().save(*args, **kwargs) class Meta: ordering = ['-created_on'] -
Nginx - UWSGI 504 gateway timeout
I saw lots of topics of nginx 504 error , but non if them solved this. Im using nginx , uwsgi on 1 machine to run Django application . i tried to add these config line at the end of /etc/nginx/nginx.conf : uwsgi_read_timeout 3s; uwsgi_connect_timeout 75s; proxy_connect_timeout 600s; proxy_send_timeout 600s; proxy_read_timeout 600s; fastcgi_send_timeout 600s; fastcgi_read_timeout 600s; send_timeout 600s; in these settings uwsgi_read_timeout is 3 seconds and nginx will raise 504 error at 3 seconds . so it works BUT when i change it to uwsgi_read_timeout 60s; then The 504 error raises in 30 seconds . it seems there is an upstream timeout that causes this error ! How can i solve this ? -
Django Rest Framework Custom Endpoints
I have recently inherited an API built with Django and DRF. I need to add some endpoints to the API but have never worked with Django or DRF before so I am trying to come up to speed as quickly as possible. I am wondering how to do custom endpoints that don't just translate data too/from the backend database. A for instance might be an endpoint that reads data from the DB then compiles a report and returns it to the caller in JSON. But I suppose that right now the simplest method would be one that when the endpoint is hit just prints 'Hello World' to the log and returns a blank page. I apologize if this seems basic. I've been reading through the docs and so far all I can see is stuff about serializers when what I really need is to be able to call a custom block of code. Thanks. -
Django: How to filter data with many-to-many relationship
Suppose that I have models like these: models.py class Category(models.Model): name = models.CharField(max_length=70, verbose_name='Name') order_num = models.IntegerField(verbose_name='Order Number') class Advertisement_Type(models.Model): name = models.CharField(max_length=70, verbose_name='Name') ad_category = models.ManyToManyField(Category, verbose_name='Ad Category') class Advertisement(models.Model): title = models.CharField(max_length=70, verbose_name='Title') ad_type = models.ForeignKey(Advertisement_Type, on_delete=models.CASCADE, verbose_name='Advertisement Type') How can I retrieve advertisement by category and advertisement type in such format by using filters only? Is this possible? Because the only way I can think of is querying everything and then building the dictionary/JSON manually through a number of for-loops and if-else which I would like to avoid. Expected format/output advertisement_type: { name: 'Type 1', category: {'Health', 'Engineering'}, advertisement: {ads1, ads2, ads3}, # Can these be objects? }, advertisement_type: { name: 'Type 2', category: {'Math', 'Numbers'}, advertisement: {ads4, ads5, ads6}, # Can these be objects? } Thank you! -
Media folder not being created
I am trying to create the media folder that would store all profile pictures, however this folder is not being created. This is what I have in my urls.py: if settings.DEBUG: urlpatterns= urlpatterns+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
"conversion from User to Decimal is not supported" in Django rest framework in python
class TreatmentBills(TimeStampedModel, models.Model): """ Description : this table create for treatment_bills """ id = models.AutoField(primary_key=True) treatment_name = models.CharField(_('Treatment Name'), max_length=255, blank=True) code = models.CharField(_('Treatment Code'), max_length=50, blank=True) treatment_bill_receiver = models.ForeignKey( User, on_delete=models.CASCADE, related_name="treatment_bill_receiver", help_text=_("Patient or Employee received bills") ) treatment_bill_creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="treatment_bill_creator", help_text=_("Provider doctor or Hospital generate bills") ) price = models.DecimalField( _('Bill price amount'), blank=True, null=True, default=0, max_digits=11, decimal_places=2 ) class Meta: """ Meta class """ db_table = "treatment_bills" class TreatmentBillGenerate(TimeStampedModel, models.Model): """ To generate bills """ treatment_bill = models.ManyToManyField(TreatmentBills, blank=True, related_name='treatment_bill') reject_reason = models.TextField(_('Reject reason'), default='') reject_date = models.DateTimeField(null=True) is_share = models.BooleanField(default=False, help_text=_("Provider share bill to patient")) is_accept_reject = models.BooleanField( default=False, help_text=_( "Employee can accept/reject bill: if is share True then - accept:True, Reject:False " ) ) objects = TreatmentBillGenerateManager() class Meta: """ Meta class """ db_table = "treatment_bill_generates" These are my models which have bills and the creation of bills is done by a role provider class ProviderUserSerializer(serializers.ModelSerializer): """ Provider List view get """ user_profile = UserProfileSerializer() provider_detail = ProviderDetailSerializer() specialty = serializers.SerializerMethodField() bills_accepted = serializers.SerializerMethodField() bill_generated_price = serializers.SerializerMethodField() bill_accepted_price = serializers.SerializerMethodField() @staticmethod def get_specialty(obj): return obj.get_user_specialities() @staticmethod def get_bills_accepted(self): bills_accepted = TreatmentBillGenerate.objects.filter(treatment_bill__treatment_bill_creator_id= self, is_accept_reject=True).count() return bills_accepted @staticmethod def get_bill_generated_price(self): bill_generated_price = TreatmentBillGenerate.objects.filter(treatment_bill__price= self).aggregate(Sum('price')) … -
How to run OpenStacks Dashboard as standalone locally?
I'm trying to customize some styles in OpenStacks Dashboard. Therefore I want to run the Dashboard locally for checking my results. I tried the default and manuel installation from the offical docs (https://docs.openstack.org/horizon/latest/index.html). Both resulted in a bunch of errors. -
Django view returns empty Dictionary
I have the following view: def myView(request): mydict = {} if request.method == 'POST': data = request.POST for key in data.items(): mydict.update({key[0]: key[1]}) print('FIRST:', mydict) print('SECOND':, mydict) return JsonResponse(mydict) So, when this Django view is called, for example on loading, a POST request is sent to an external Python script, this external Python script sends back another request to the Django view. The POST request received contains a dictionary, like this: {'one': 1, 'two': 2}. After this dictionary is received, my code should take that dictionary and update it to the variable mydict. So the final output of mydict should be {'one': 1, 'two': 2}. If i try print(mydict) here is what happens when the view is called: FIRST: {'data': '1', 'two': '2'} SECOND: {'data': '1', 'two': '2'} [08/Jan/2020 16:54:27] "POST /myView/ HTTP/1.1" 200 25 SECOND: {} If i go to the HTML page of this view, i will see an empty dictionary, instead of seeing '{'one': 1, 'two': 2}'. Can someone tell me what's happening here? Why is the dictionary empty, when returned from the view? Thanks in advance! -
Django: logic not well applied in template using permissions (perm
I develop a Django app I have specifics permission on 2 differents models I use these permissions to display or not some link in a navbar but I have an unexpected behavior I do not understand below the html code with Django logic code between should not be display with one of my user that do not have the two permissions I control to be sure permissions are effectively False but even without permissions, links 'Randomize a patient' and 'Reallocate a patient' are displayed what is wrong in my logic? I give at the end, the entire navbar html code partial template : {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{% trans 'Randomization' %}</a> <div id="randomize" class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> {% if user_allowed_to_randomize and user_can_randomize or allowed_to_randomize and can_randomize %} **<!-- SHOULD NOT BE DISPLAY - START-->** {% if perms.randomization.can_randomize %} <a class="dropdown-item" href="{% url 'randomization:randomisation_edit' %}">{% trans 'Randomize a patient' %}</a> {% endif %} {% if perms.randomization.can_reallocate %} <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'randomization:reallocate_edit' %}">{% trans 'Reallocate a treatment' %}</a> {% endif %} **<!-- SHOULD NOT BE DISPLAY - END-->** {% endif %} </div> </li> <li class="nav-item"> <a class="nav-link" href="#">{% trans … -
MultiValueDictKeyError when trying to upload a file / no console output with print
I am just getting started with Django and I am trying to get a simple file upload to work. After I select a file and submit it I get this error: MultiValueDictKeyError at /upload/ 'document' This is the simple code I wrote: My upload.html {% block content %} <h2>Upload</h2> <form method="post" enctype="multipart/from-data"> {% csrf_token %} <input type="file" name="document"> <button type="submit">Upload file</button> </form> {% endblock %} My views.py from django.shortcuts import render def upload(request): if request.method == 'POST': uploaded_file = request.FILES['document'] print("TEST") return render(request, 'upload.html') Also I added the "upload" path to urls.py A different problem is that I do not know why I cannot see the output of the print command from views.py anywhere. Greets, Tim -
Why use {% load static %} ? (in my case it didn't anything)
guys I'm New to coding and Python and also stack overflow now I practice django and making blog tutorial and I have a question to you guys How can I active {% load static %}? in my case without this, my css file works well.. and rather due to {% load static %}, in base.html unexpected token is occurred which means that &lt!DOCTYPE html&gt is red underlined due to {% load static %} can you find any mistake in this code? If I need to show you more codes, please let me know thatThank you! setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7sh#^-+*tczxfimk@+wq4s6jx$2(204&z9_d)mjomv1^y6644!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/base')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', … -
Displaying Django model on template
Nothing is being displayed. even without any error log. although the model has data in it models.py class Product(models.Model): name = models.TextField() cat = models.IntegerField() price = models.FloatField() company_id = models.IntegerField() status = models.TextField() views.py def list_products(request): object_list = Product.objects.all() return render(request, 'index.html', {'object_list ': object_list}) index.html {% for e in object_list %} <li> {{ e.name }} </li> {% endfor %} urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.list_products, name='index'), ] -
Django: a question about objects.filter() and models.OneToOneField() [closed]
Wondering if anyone could help me to fix it. views.py # tutor links to Tutor, and Tutor.account links to django.contrib.auth.models.User Student.objects.filter(tutor.account=request.user) # it doesn't work ... models.py class Tutor(models.Model): account = models.OneToOneField(User, null=True, on_delete=models.SET_NULL) class Student(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) tutor = models.ForeignKey(Tutor, null=True, on_delete=models.SET_NULL) duration = models.PositiveSmallIntegerField(default=30) Many thanks! -
How can I get public ip address in Django with Nginx as http server and gunicorn?
I want to get public IP address of clients but I just get 127.0.0.1 almost always. I tested some solution, but no right answer found with my configuration (Django, Nginx and Gunicorn) -
Python Django db transaction uses update
I am using django transactions to work with my DB. The thing I am stuck on is that I have a DB and I want to replace the whole DB with a new one created in the transaction block. The behavior of @transaction.atomic is that it will always update the DB. So the old db entries will stay there. How to always remove the old entries? Am I missing something in the Django specs? Or do I need to clear the db table manually inside the transaction block?