Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create 2 different user types in Django using One to Many relationship
I am creating a basketball statistic application where I would like to have two different user types, Coach and Player. I want the coach to be able to log in and view the stats for his players only. Therefore one coach will have many players. I want to be able to create user profiles for each coach and display their players only and not all of the players in the database. As of now, I have created the user profiles that displays all of the registered users but I am confused on how to separate the two users so that the players will be under the coaches. Thank you!!! Models.py view: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): name = models.CharField(max_length=100, default='') school_name = models.CharField(max_length=100, default='') user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') state = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) jersey_number = models.IntegerField(default=0) image = models.ImageField(upload_to='profile_image', blank=True) position = models.CharField(max_length=100, default='') height = models.CharField(max_length=100, default='') weight = models.CharField(max_length=100, default='') grade = models.CharField(max_length=100, default='') background_image = models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) Views.py: @login_required(login_url='login') def view_profile(request, … -
dealing with delayed POST responses in django
I am using some forms to create qualifications and hits in Amazon mTurk using boto3 and AWS api. Using boto or AWS does not matter in this case, but what does matter is that the response (that a HIT successfully created on Amazon side) comes with a delay. It usually pretty quick, but I am worried that sometimes it can be too long and would generate an error due to too long delay. What is the most 'clean' way of dealing with delayed responses in Django? Right now I process the GET responses from boto and mturk using Django StreamingHttpResponse on server side and XmlHttpRequest on client's side. But I am not sure it makes sense to do it with POST. -
How to convert Django model that has FileField into JSON
I tried to get the last inserted data from the following method latest = AudioContentModel.objects.latest('id').id object = model_to_dict(AudioContentModel.objects.get(pk=latest)) but I get the following error TypeError: Object of type 'FieldFile' is not JSON serializable How can I get the data from the table that was last inserted? This is my model.py class AudioContentModel(models.Model): background_music = models.FileField(upload_to='documents/') tts = models.FileField(upload_to='documents/') final_audio = models.FileField(upload_to='documents/') created = models.DateField(auto_now_add=True) This is my view.py def index(request): if request.method == 'POST': if request.is_ajax(): audiouploadform = AudioUploadForm(request.POST, request.FILES) if audiouploadform.is_valid(): audiouploadform.save() latest = AudioContentModel.objects.latest('id').id print('Need to get the all the data from the latest and resturn as a JsonResponse') data{ 'background_music': 'tts': 'id': } return JsonResponse({'error': False, 'data': data}) else: return JsonResponse({'error': True, 'errors': audiouploadform.errors}) else: error = { 'message': 'Error! Must be an Ajax call' } return JsonResponse(error, content_type="application/json") else: audiouploadform = AudioUploadForm() all_audio_files = AudioContentModel.objects.all() data = { 'audio_file_list': all_audio_files, 'audiouploadform': audiouploadform, } return render(request, template_name='index.html', context=data) -
Django admin forms error, delete form with errors and then press cancel
I am using Django 1.11.2. In every form in admin(on edit), if I have errors on the form, and I press delete, and on the delete page I press cancel to go back, I receive this error: Confirm Form Resubmission This webpage requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. Press the reload button to resubmit the data needed to load the page. ERR_CACHE_MISS If The form is clean and I don't have errors on it, is working. How can I resolve this? -
Django/Celery - AttributeError: module 'novopagemento' has no attribute 'celery'
When I try to execute the command celery -A novopagamento worker -l info I receive the following error: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/celery/app/utils.py", line 365, in find_app found = sym.app AttributeError: module 'novopagamento' has no attribute 'app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/celery", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/celery/__main__.py", line 16, in main _main() File "/usr/local/lib/python3.6/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) File "/usr/local/lib/python3.6/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/local/lib/python3.6/site-packages/celery/bin/base.py", line 273, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/usr/local/lib/python3.6/site-packages/celery/bin/base.py", line 479, in setup_app_from_commandline self.app = self.find_app(app) File "/usr/local/lib/python3.6/site-packages/celery/bin/base.py", line 501, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/usr/local/lib/python3.6/site-packages/celery/app/utils.py", line 370, in find_app found = sym.celery AttributeError: module 'novopagemento' has no attribute 'celery' My project's structure: novopagamento ├──novopagamento | ├──__init__.py | ├──settings.py | └──celery.py ├──api | └──tasks.py My celery file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'novopagemento.settings') app = Celery('novopagemento') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) My task file: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def task_number_one(): #code My settings file: import os # Other Celery settings from celery.schedules import crontab # Build paths inside the … -
Django update a page on POST.get
I have a Django project where i use NFC keychains. When a keychain is read, the reader sends a HTTP POST request to my Django server, which is now basically displaying the key that has been read. What causes the problem is that in order to show that the keychain has been read i need to refresh the page. Is there any way to show the changes immediately, or force a refresh on the browser from the server when a POST request is executed? I have read that Ajax might be capable for this, but i dont know Ajax. If Ajax would be the solution, can anyone show me a working example? -
Django query list with foreign key constraint
We have a number of Django models with a foreignkey constraint. First of all there is Relation, which has two integer fields that together form a unique combination, let's say number1 and number2 (as well as some other fields that are not relevant here). Then there is RelationAddress, which has a ForeignKey constraint to Relation (and some more fields but they are not relevant here). We are getting the data from an external source and have no way of getting them differently. First we get a file containing the Relation data, and this can get imported without any problems (it has not foreigkey constraints so rather straightforward). Next we get a file containing the RelationAddress data, which has the number1 and number2 on each row (together with other data that is again not relevant now) of the file to be able to identify the related Relation. If we would do it the naive way, we would just import the file row by row and lookup the related Relation from the database using a query like Address.objects.filter(number1=given_number1, number2=given_number2) In case of a lot of records (we have to deal with millions of records) this approach is way too slow. So we … -
Why does my Django Forms Input only render when the submit button is clicked?
I am currently making a Django forms for the first time and encountered a problem with rendering the text inputs of the forms. I used a simple template for my forms and attached a submit button along with the input. <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> I used a TemplateView in my views.py to name the template and render the forms: class HomeView(TemplateView): template_name = "WebApp/index.html" def post(self, request): form = HomeForms() return render( request, self.template_name, { 'form': form, 'title': 'Home', } ) And my forms.py currently looks like this: from django import forms class HomeForms(forms.Form): post = forms.CharField() Any help would be greatly appreciated. -
django call to custom method in model when rendering the page
If I have a custom method in my Model that I am calling in my template, does it mean there are multiple roundtrips happening from client(browser) to server? I am pretty sure when I return render() from my view, rendering happens on the server side and the output as HTML is returned to the client. Please correct me if my understanding is off. -
Django - wont let me add a new field to my model because 1054, "Unknown column 'field list'")
I am trying to simply add a boolean field to a model in my database following the simple rules: - add field to model - python manage.py makemigrations app - python manage.py migrate app Works all but 99% of the time. So during the second step (makemigrations), with my newly added field in my model raring to go, i get an error: django.db.utils.OperationalError: (1054, "Unknown column 'model.field' in 'field list'") Excellent. its not letting me make migrations by adding a new field..... because it cant find the field that I am trying to newly add... makes perfect sense! Anyway, I have gone as far as deleting all my migrations, removing my new field, making migrations again, migrating... all fine - so now i have only 1 migration file (0001)... Follow the same steps as above... ERROR Am i missing something ridiculous here? I mean, adding a field to a model is very simple, and I have done it probably 1000 times. Why does Django tease me so -
Django 2.0.7. is missing the complete path in url when the user try to upload a file. It works on local enviroment but not in production server
I have a model with a ImageField: class Usr( User ): idusuario = models.AutoField( primary_key = True ) usuario = models.CharField( blank = False, unique = True, max_length = 50 ) contraseña = models.CharField( blank = False, max_length = 250 ) telefono = models.CharField( max_length = 15, blank = True, null = True ) celular = models.CharField( max_length = 15, blank = True, null = True ) fotografia = models.ImageField( blank = True, null = True, upload_to = 'usuarios' ) depende_de = models.ForeignKey( 'self', on_delete = models.CASCADE, related_name = '+', blank = True, null = True ) def __unicode__( self ): return self.get_full_name() def __str__( self ): return self.get_full_name() And its form (a ModelForm ): class RegUsuario( forms.ModelForm ): class Meta: model = Usr fields = [ 'usuario', 'contraseña', 'is_active', 'is_superuser', 'first_name', 'last_name', 'email', 'telefono', 'celular', 'fotografia', 'groups', 'depende_de' ] In views (vw_usuario.py) I have: def new( request ): if 'POST' == request.method: frm = RegUsuario( request.POST, files = request.FILES ) if frm.is_valid(): obj = frm.save( commit = False ) obj.username = obj.usuario obj.set_password( obj.contraseña ) obj.save() for g in request.POST.getlist( 'groups' ): obj.groups.add( g ) obj.save() return HttpResponseRedirect( reverse( 'usuario_ver', kwargs = { 'pk' : obj.pk } ) ) … -
Django language field with translation
I want to create a language choice field but I am struggling to output the language field in the correct language. Please find the source code below: #model.py from django.conf.global_settings import LANGUAGES class Language(models.Model): language = models.CharField(max_length=7, choices=LANGUAGES) #formy.py class LanguageForm(forms.ModelForm): class Meta: model = Language fields = ['language'] So if I render the form in my template I get the name of the language always in English. How can I use the correct translation depending on the language which is set in the django settings? -
accessing image files residing in static directory of django
I've some image files that are in the 'img' folder in the static directory of django app. I want to access them all and store into a list in my 'views.py' so that I can iterate through them to display them by rendering them through the template. How can that be done? -
how to update data using modelformset on django
i'm making example code to use form and modelformset. create_function is working good. but update_function has a problem. when it call the function occur the error MultiValueDictKeyError. i'dont know how to fix it. please help. def update(request, portfolio_id): template_name = 'portfolio_create_form.html' pofol = Portfolio.objects.get(id=portfolio_id) if request.method == 'GET': form = PortfolioForm(instance=pofol) formset = PortfolioImageModelFormSet( queryset=PortfolioImage.objects.filter(portfolio__id=portfolio_id), prefix='image' ) elif request.method == 'POST': form = PortfolioForm(request.POST, instance=pofol) formset = PortfolioImageModelFormSet(request.POST, request.FILES, prefix='image') if form.is_valid() and formset.is_valid(): portfolio = form.save() for imageForm in formset: pofolImage = imageForm.save(commit=False) pofolImage.portfolio = portfolio pofolImage.save() return redirect('detail', portfolio_id) return render(request, template_name, { 'form' : form, 'formset' : formset }) -
Django: [Errno 30] Read-only file system: '/static' when trying to upload image through admin when deployed through Heroku
I have my app deployed on Heroku using MySQL database. I am trying to upload an image using the admin interface, but am getting the following error: [Errno 30] Read-only file system: '/static' I can upload images just fine locally. How can I write files to this folder, as to upload images? Here are my static settings and Image model field currently: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if DEBUG: MEDIA_URL = '/static/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'media') # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' models.py image = models.ImageField(null=True, blank=True, upload_to='') I believe it should default upload to the media folder by default. DEBUG is set to True. -
Django 2.1 and select_related()
This is a follow-up / clarification to this question. I'm using Django 2.1, Python 3.6, and Oracle 12c. Suppose I have two models: class ModelA(models.Model): modelB_field = ForeignKey(ModelB, on_delete=models.DO_NOTHING) example_field = models.IntegerField() class ModelB(models.Model): example_field = models.IntegerField() Then if I do ModelA.objects.filter(...).select_related('modelB_field') I get django.db.utils.DatabaseError: ORA-00918: column ambiguously defined. Three observations: I only get the error if the field example_field is in both models...even though it is not the primary key of ModelB. The query that Django generates works in sqldeveloper. The code works if I use a virtualenv with Django 2.0 instead of Django 2.1. The docs don't indicate anything changed with select_related in Django 2.1. Can anybody help? Thanks much! -
Bulk delete Django by ids
I writing a project using Django REST Framework, Django and Postgres as a database. I want to bulk delete in one query. So, it is possible to do without writing a query using pure SQL? There is an example, but the count of query equal length of a list of ids: delete_ids = [...] MyModel.objects.filter(id__in=delete_ids).delete() -
Do not create sub-objects in django
I have a model representing a Status - and have a foreign key to Status from an Object model. I want to be able to create new objects, but do not want to allow the possibility of creating any more Status entries (there are a set of 5 pre-defined ones that are migrated into the database). I believe I have figured out how to structure serializers in such a way as to only re-use existing Status entries, but I'm not sure if it is the best way to go about doing something like this... Some Simplified Code: class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status fields = ('name',) def to_representation(self, obj): return obj.name def to_internal_value(self, data): return { 'name': data } class ObjectSerializer(serializers.ModelSerializer): status = StatusSerializer(read_only=True) class Meta: model = Object fields = ('obj_name', 'status',) def create(self, validated_data): # We do not want to create new statuses - only use existing ones status = Status.objects.get(name=self.initial_data['status']) return Object.objects.create(status=status, **validated_data) def update(self, instance, validated_data): instance.obj_name = validated_data.get('obj_name', instance.obj_name) # We do not want to create new statuses - only use existing ones instance.status = Status.objects.get(name=self.initial_data['status']) if 'status' in self.initial_data else instance.status return instance As seen above, I also flatten out the Status object … -
Retrieving null as JSON default in django and MySQL
I have a JSON column in MySQL: Should be null if the admins give it the default value. Preload with the default value to admins if it is null. Using django-mysql third party library from django.db import models from django_mysql.models import JSONField def json_default(): return {'foo': '', 'bar': ''} class Test(models.Model): json_field = JSONField(default=json_default) def __getattribute__(self, name): attr = models.Model.__getattribute__(self, name) if name == 'json_field' and not attr: return json_default() return attr def save(self, *args, **kwargs): if all(value.strip() == '' for value in self.json_field.values()): self.json_field = None else: self.json_field = {k:v.strip() for k, v in self.json_field.items()} super(Test, self).save(*args, **kwargs) The problem is whenever the super method is called, __getattribute__ is internally called and as a result, it saves as json_default() and not null. -
django leaflet layer control
Hello guys I'm trying to add a control panel of layers but don't understand why it is not working, can somebody check my code of what I have done wrong? This is my code: The layers are loaded from geoserver also I copied the three dist files from: https://github.com/ismyrnow/leaflet-groupedlayercontrol. index.html {% extends 'workorders/base.html' %} {% block jumbotron2 %} <div class="jumbotron"> <h1>Navbar example</h1> <p class="lead">This example is a quick exercise to illustrate how the top-aligned navbar works. As you scroll, this navbar remains in its original position and moves with the rest of the page.</p> <a class="btn btn-lg btn-primary" href="../../components/navbar/" role="button">View navbar docs &raquo;</a> </div> {% endblock %} {% block content %} <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title>Map</title> <style type="text/css"> #gis {width: 100%;height:600px;} </style> <link rel="stylesheet" type="text/css" href="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.css' %}"> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}" > </script> <script type="text/javascript" src="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.js' %}" > </script> </head> <body> <script type="text/javascript"> function our_layers(map, options){ var osm = 'http://{s}.tile.openstreetmap,org/{z}{y}{x}.png'; var datasets = L.tileLayer.wms('http://localhost:8080/geoserver/geodjango/wms', { layers: 'geodjango:layer_ww_manholes', format: 'image/png', transparent: true }); var lines = L.tileLayer.wms('http://localhost:8080/geoserver/geodjango/wms', { layers: 'geodjango:layer_ww_lines', format: 'image/png', transparent: true }); datasets.addTo(map); lines.addTo(map); var baseLayers = { … -
How to render an image through |safe filter
as I said I need to be able to render an image like... <img src="{% static 'forum/img/Confucius.png' %}" class="responsive-img" style='max-height:200px;' alt="face"> everything else in staticfiles like fonts works but safe filter is unable to render an image.... what do I do? -
Restricting value of a choice field based on another field value: Django
Searching the web for resolution I cam across this page. However my requirement is a bit different. Say my models are: Category class Category(models.Model): cat_id = models.CharField(primary_key=True, max_length=6.... cat_desc = models.CharField(max_length=100, ......... .... Material class Material(models.Model): matl_id = models.CharField(primary_key=True, max_length=5.... matl_desc = models.CharField(max_length=100, ......... matl_category = models.ForeignKey(Category, on_delete=..... .... Now when the user attempts to create a transaction (say a PO), they will be required to pick a Category (say the selected category is BLACKOIL) and the choice of Materials shall be limited to those with the particular category selected (again, e.g. only materials with category BLACKOIL will be available in the drop down list). How do I create the scenario in Django Admin? -
How save element multiple in dictionary?
Suppose I have a model like this: class Post(model.Model) name = model.CharField(max_lenght) description= model.CharField() and i have this dictionary d={'name':'jerry', 'description':'all} For save dict: p=Post(**d) p.save() But IF I have this dict: d={'name':'jerry', 'description':'all, 'name1': 'lucy', 'description1': 'tr'} Can I save element in Post: Name Description jerry all lucy tr -
Django if statements dont work together
So I have been trying to implement a way to post a project post I can upload multiple images with it. Every time I do my create project function like this: views.py class CreateProjectsView(View): def get(self, request): p_photos = P_Images.objects.all() #project_form = ProjectsForm(initial=self.initial) project_form = ProjectsForm() context = { 'p_photos': p_photos, 'project_form': project_form, } return render(self.request, 'projects/forms.html', context) def post(self, request): project_form = ProjectsForm(request.POST or None, request.FILES or None) p_formset = P_ImageForm(request.POST, request.FILES) # Checks if the project_form is valid before save if project_form.is_valid(): instance = project_form.save(commit=False) instance.user = request.user instance.save() # Checks if multiple image upload is valid before save if p_formset.is_valid(): #if project_form.is_valid() and p_formset.is_valid(): #instance = project_form.save(commit=False) #instance.user = request.user #instance.save() images = p_formset.save(commit=False) images.save() data = { 'is_valid': True, 'name': images.p_file.name, 'url': images.p_file.url } else: data = { 'is_valid': False, } return JsonResponse(data) It works if it is like that, but I would want it with an "and" like this one below but it doesn't work. class CreateProjectsView(View): def get(self, request): p_photos = P_Images.objects.all() #project_form = ProjectsForm(initial=self.initial) project_form = ProjectsForm() context = { 'p_photos': p_photos, 'project_form': project_form, } return render(self.request, 'projects/forms.html', context) def post(self, request): project_form = ProjectsForm(request.POST or None, request.FILES or None) p_formset = P_ImageForm(request.POST, … -
how to run .sh file from python functions in windows
i want to run .sh file from python function when i call rest api function but i am not able to run it please can any one help me out below is code from where i am trying to execute class GetLittleHotelierData(APIView): def post(self, request, format=None): if request.data.get("key") != settings.SECRET_KEY: raise APIException("You don't have access to perform this action") print("Milan") parm1= "test" parm2 = "test" parm3 = "test" parm4 = "test" parm5 = "test" call(['sh /path/test.sh ' + str(parm1) + " " + str(parm2) + " '" + parm3 + "' 1 " + parm4 + " " + parm5], shell=True) return JsonResponse({"success":True})