Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms and Models
I have a function based view: @login_required def profile(request): if request.method == 'POST': form = IngredientForm(request.POST, user=request.user) if form.is_valid(): form.save() ingredient_1 = form.cleaned_data['ingredient_1'] ingredient_2 = form.cleaned_data['ingredient_2'] ingredient_3 = form.cleaned_data['ingredient_3'] ingredient_4 = form.cleaned_data['ingredient_4'] ingredient_5 = form.cleaned_data['ingredient_5'] messages.success(request, f'Ingredients added to your account!') return redirect('profile') else: form = IngredientForm(user=request.user) return render(request, 'users/profile.html', {'form': form}) and the model is: from django.db import models from django.contrib.auth.models import User class ingredients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) ingredient_1 = models.CharField(max_length=32) ingredient_2 = models.CharField(max_length=32) ingredient_3 = models.CharField(max_length=32) ingredient_4 = models.CharField(max_length=32) ingredient_5 = models.CharField(max_length=32) forms.py looks like: class IngredientForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(IngredientForm, self).__init__(*args, **kwargs) class Meta: model = ingredients fields = ('ingredient_1', 'ingredient_2', 'ingredient_3', 'ingredient_4', 'ingredient_5') I am trying to get the current user and use that as the key for the ingredients table in my database. I am not sure how to get the current user and set the user in the table as the current user. Any help would be appreciated :) The error that I get when I submit the form is: -
Cannot Export Django models in Openpyxl
here is my code from django.http import HttpResponse from openpyxl import Workbook from .models import Donor def export_to_excel(request): excel_data = [ ['First Name', 'last Name', 'Email', 'Address','City', 'State', 'Zip','Superdonor', 'Occupation'], [Donor.objects.all()] ] if excel_data: wb = Workbook(write_only=True) ws = wb.create_sheet() for line in excel_data: ws.append(line) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=Donor_List.xlsx' wb.save(response) return response The Models form from django.db import models from django import forms from localflavor.us.models import USStateField, USZipCodeField # Create your models here. class Donor(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=254) address = models.CharField(max_length=30) city = models.CharField(max_length=30) state = USStateField() zip = USZipCodeField() superdonor = models.BooleanField(default=False) occupation = models.CharField(max_length=50, blank=True) about = models.TextField(max_length=1000, blank=True) def __str__(self): return ("%s %s" % (self.first_name, self.last_name)) I am trying to loop through the model and have it list everything in the database. Any help is greatly appreciated. Without looping though the database the Excel sheet will generate but I need to export the entire database. -
Django admin failing to login after upgrade to 2.1
After upgrading an old Django 1.8 to 2.1, when I try to login on my admin site, I get a 404 with message: Using the URLconf defined in <mysite>.urls, Django tried these URL patterns, in this order: [...] The current path, login/, didn't match any of these. Which I guess is true because it should be on __admin/login as in my urls.py I have: urlpatterns = [ ... path(r'__admin/', admin.site.urls), ... ] But: The GET request /__admin/login returns the login page as expected The problem happens only in production (with passenger WSGI on a VPS), not on localhost Unfortunately the upgrade happened at the same time as a migration in VPS machine so there may also be a problem with the database. -
Related model ID gets lost in validated_data even though it is present in request
I am working on my create() method for my webapp which uses Django REST framework for the backend API. In this case, I'm trying to create a new RECIPE, which has a foreignkey field to a related model STYLE... I am running into an issue when trying to associate my new recipe record with an existing related object via the ID. My serializers looks like this: class StyleSerializer(serializers.ModelSerializer): http_method_names = ['get'] class Meta: model = Style exclude = () class RecipeSerializer(serializers.ModelSerializer): hops = HopAdditionSerializer(many=True, read_only=True) fermentables = FermentableAdditionSerializer(many=True, read_only=True) style = StyleSerializer() yeast = YeastSerializer(read_only=True) class Meta: model = Recipe exclude = () def create(self, validated_data): style_data = validated_data.pop('style') style = Style.objects.get(pk=style_data.get('id')) reipce = Recipe.objects.create(**validated_data) recipe.style = style recipe.save(); return recipe You can see I'm trying to assign the new recipe object with a related Style object. On my POST request for a new recipe, I include the style, which is all of the related attributes including the field ID. I have verified this info is getting POSTED both in the request via dev console AND in the django viewset via terminal log. However, in my serializer create() method, the ID value is always missing from the dictionary object returned … -
How to strip whitespace off of a returned field from DRF model Serializer?
I have the following code for my DRF serializer: class ObjectSerializer(serializers.ModelSerializer): class Meta: model = models.MyModel fields = ('field1', 'field2') My query code looks like this: class MyAPI(ListAPIView): http_method_names = ['get'] serializer_class = ObjectSerializer def get_queryset(self): queryset = MyModel.objects.values('field1', 'field2').filter(someField='SomeValue').all() return queryset field1 is a char field with trailing whitespace. I am trying to remove all of that trailing whitespace in the query set. How can I go about doing that? I tried passing in the extra_kwargs = {"content": {"trim_whitespace": True}} statement into my serializer but it doesn't trim the whitespace on the field. Is what I am doing wrong obvious and I am just missing it? -
Django Inner join using ORM
I have the following tables in my sqlite3 database : PRAGMA table_info(auth_user); 0|id|integer|1||1 1|password|varchar(128)|1||0 2|last_login|datetime|0||0 3|is_superuser|bool|1||0 4|username|varchar(150)|1||0 5|first_name|varchar(30)|1||0 6|email|varchar(254)|1||0 7|is_staff|bool|1||0 8|is_active|bool|1||0 9|date_joined|datetime|1||0 10|last_name|varchar(150)|1||0 PRAGMA table_info(accounts_member); 0|id|integer|1||1 1|team_id|integer|1||0 2|user_id|integer|1||0 3|department_id|integer|1||0 and lastly : PRAGMA table_info(accounts_department); 0|id|integer|1||1 1|name|varchar(20)|1||0 2|description|varchar(255)|1||0 The above three tables are related to each other in the following manner : auth_user is the main table that links the tables . accounts_member references auth_user with foreign key user_id and also references accounts_department with the foreign key department_id. How can I achieve the following query in django ? select * from auth_user inner join accounts_member on accounts_member.user_id = auth_user.id inner join account_department on account_department.department_id = accounts_member.id i have different tutorials but most I get requires use of where function condition. -
Duplicating an Imagefield on save() - django
I'm working on a project in django, I need to duplicate a picture stored in one model and save it with a different name into another one, I've tried many of the responses I've found but nothing seems to work. This last try doesn't give me an error but is not duplicating the image, nor storing a copy with the name. I'm running Pillow and Django 3.X models.py: class Visualization(models.Model): kind = models.CharField(max_length=90) description = models.CharField(max_length=90) image = models.ImageField(upload_to='visualization', null=True, blank=True) class Order(models.Model): visualization = models.ForeignKey(Visualization, on_delete=models.CASCADE) hashed = models.ImageField(upload_to='hashedimages', null=True, blank=True) def safe(self): super().save() self.hashed = self.visualization.image self.hashed.name = 'randomothername.jpg'' self.hashed.save() -
too many values to unpack (expected 2) - Dictionary to JSON
I have a big dictionary with more than 50 items. I am trying to return this dictionary in the form of JSON. The code for that is:- return HttpResponse(json.dumps(responseData, indent = 0, default=str), content_type="application/json") There are some date fields in the dictionary and so I mentioned default=str to convert them to string. When I print the json.dumps, I do see proper values present in the json. But when I put it in HttpResponse, I get the below error:- too many values to unpack (expected 2) Could somebody tell me why exactly its happening and what is the workaround? -
Postgres10 - CREATE TABLE AS with partition
I have an existing Postgres9 table, where every time I make a query, the WHERE clause includes the id of the US state. I would love to use Postgres10 Declarative Partitions to make a new version of this table, but with a LIST partition based off of the 50 states. I am trying things like: CREATE TABLE partitioned_stuff AS TABLE stuff PARTITION BY LIST( state ); but this gives syntax error at or near "PARTITION" Do I have to recreate the stuff table schema manually? -
How can I get User at Validate in Serializer?
In my view(CreateView) I overriding my method def create, but in my validate I cant get logged user by self.context.get('request').user, so, how can I get the user logged in my validate? -
How to upload image and createview
I don't understand how to add this image object on view. please help me. models from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() image = models.ImageField(default='post.jpg', upload_to='image') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def save(self, *args, **kwargs): super().save() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) what i do for the image field is valid. I want to be able to upload an image file using CreateView and a LoginRequiredMixin but I can't get it working - it seems the form doesn't bind any file data after choosing a file. Here's the current content of the view views class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content','image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) any think i do jast show the default photo. home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }} </small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}"> {{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> <img … -
django rest framework nested objects JSON format
I'm facing a little problem right now with Django Rest Framework. I'm trying to post an object with nested objects in it. models.py class Car(models.Model): licence_plate = models.CharField(max_length=12, unique=True) vin = models.CharField(max_length=17, unique=True) car_brand = models.CharField(max_length=100, unique=True) class Place(models.Model): place_name = models.CharField(max_length=50) latitude = models.CharField(max_length=50) longitude = models.CharField(max_length=50) class Ride(models.Model): places = models.ManyToManyField(Place, through='RideStop') car = models.ForeignKey(Car, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True, blank=True) class RideStop(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, null=True) ride = models.ForeignKey(Ride, on_delete=models.CASCADE, null=True) dir = JSONField(null=True) serializers.py class RideSerializer(serializers.ModelSerializer): places = RideStopSerializer(many=True) car_id = CarSerializer() class Meta: model = Ride fields = '__all__' def create(self, validated_data): ride_stops = validated_data.pop('places') ride = Ride.objects.create(**validated_data) ride_stops_objects = [] for ride_stop in ride_stops: ride_stop_object = RideStop() ride_stop_object.ride_id = ride ride_stop_object.place_id = ride_stop['place_id'] ride_stop_object.ride = ride_stop['dir'] ride_stop_object.save() # RideStop.objects.bulk_create(ride_stops) return ride views.py class ListCreateRide(generics.ListCreateAPIView): queryset = models.Ride.objects.all() serializer_class = serializers.RideSerializer and I would like to post a JSON format like this: { "date":"21-14-17", "car":3, "ride_stops":[ { "place":4, "dir":"{ \"ahoj\":\"nazdar\"}" } ] }' Can anyone help me out please? -
Programmatically creating and uploading images in django
I'm using this method to create an image programmatically, def create_thumbnail(filename, letters, color): img = Image.new('RGB', (200, 200), color=color) d = ImageDraw.Draw(img) font = ImageFont.truetype("sans-serif.ttf", 48) d.text((0, 0), letters, (255, 255, 255), font=font) img.save("{}.png".format(filename)) This is my object creation logic, room, created = Room.objects.get_or_create(name=name, logo="", sport=sport,status=RoomStatus.ACTIVE,defaults={'team': team,'city': city,}) I've an override in the model to save the image to the correct folder. def image_upload_path(instance, filename): pattern = re.compile(r'\s+') filename = re.sub(pattern, '', filename) return 'images/rooms/logo/_{0}/{1}'.format(instance.id, filename) This works fine when handling a post request with the image data. My question is how do I create the image and upload it the correct folder using my image creation function. Any help appreciated. -
How to create an object for a model from the console similar to how Django made the createsuperuser command
I'm trying to create an object from the console but not sure how to set that up. This is my modelManager: class MajorManager(models.Manager): def __str__(self): return self.name def createMajor(self, name): try: name = name.lower() major = self.create(name=name) except IntegrityError: print("This major has already been created") And here is the model: class Majors(models.Model): name = models.CharField(max_length=30, unique=True) objects = MajorManager() Any help would be much appreciated. -
How to find out that external database is updated in Djangov (while manage=False)
I have a project that is connected to an external database and just have view access to it. So I created my models with managed=False flag. I was wondering how can I find out in django that any change in that database is happened. Is there any solution in django or I should find a method to communicate between that database and my django app. like socket, database triggers and ...? More details: Image my models is like this: class Alert(models.Model): key = models.CharField(max_length=20) class Meta: managed = False Now i want to be notified in django each time the database is updated. I want a signal to capture database updates and do something in django? -
Django: upload 4 files with same name-body and different extensions
I have 4 files (file1.ref, file1.bmp, file1.dat, file1.kfg). How to select only one file (".ref") and upload all four using Modelforms? views.py def results_import(request): if request.method == 'POST': form = ResultsForm(request.POST, request.FILES) if form.is_valid(): form.save() specimen = form.cleaned_data['specimen'] messages.success(request, f'Data for {specimen} is saved .') return render(request, 'ultra/results_import.html', {'form': form}) else: form = ResultsForm() return render(request, 'ultra/results_import.html', {'form': form}) forms.py class ResultsForm(ModelForm): class Meta: model = Results fields = ['specimen', 'pruefparameter', 'ref_file'] model.py class Results(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE) pruefparameter = models.ForeignKey(Pruefparameter, on_delete=models.CASCADE) ref_file = models.FileField(upload_to='Echograph/', null=True, blank=True, default=None) bmp_file = models.FileField(upload_to='Echograph/', null=True, blank=True, default=None) dat_file = models.FileField(upload_to='Echograph/', null=True, blank=True, default=None) kfg_file = models.FileField(upload_to='Echograph/', null=True, blank=True, default=None) def __str__(self): return str(self.specimen) results_import.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content %} <h2>Import Results</h2> <form method="POST" enctype="multipart/form-data" > {% csrf_token %} {{ form|crispy}} <button type="submit">Submit</button> </form> <p><a href="{url 'home' %}">Return to home</a></p> {% endblock content %} -
Adding emotion detection to my django website
I want to add emotion detection to my django website . I googled and found that i need to make an API and Json will help to send response to my site but I am still confused with it. How can I link my emotion detection code with my website? I am new to this so please help me out like how I go further. -
Django model DateField format in modelformset_factory
I'm trying to make a modelform_factory for my model named Book but the DateField is behaving strangely. class Book(models.Model): name = models.CharField(max_length = 50) date = models.DateField(max_length = 50) I have a function in my views that returns this: modelform = modelformset_factory(Book, fields = ( 'name', 'date', ), can_delete=True, widgets = { 'date': forms.DateInput(format='%d/%m/%Y'), }) In my template this modelform will render with a datepicker: $('.datepicker').datepicker({ format: 'dd/mm/yyyy' }); So far so good, and everything is working as expected to this point. But when I post my form to my view again, and save the modelformset, the dd/mm/yyyy date is wrongly converted to yyyy-mm-dd. if request.method == 'POST': formset = modelform(request.POST, request.FILES, queryset=Book.objects.filter(name=book)) if formset.is_valid(): formset.save() # This first deletes all instances that are checked for deletion f = formset.save(commit=False) # This filters the formset to only include filled in forms for form in f: form.save() return HttpResponse("success") Does someone has any clue how I can format this dd/mm/yyyy date to correctly enter my database? -
Why does Django CKeditor create an AWS s3 url that expires after 1hr?
I'm using Django Zinnia with CKeditor as the blog wysiwyg editor. I can upload images and connect to AWS S3 bucket perfectly. When I attach the picture to the blog post, it appears but expires and disappears from the post after 1hr. Why is that? I'm using: zinnia-wysiwyg-ckeditor==1.3 Django==2.1.2 django-s3-storage==0.12.4 boto3==1.9.54 botocore==1.12.54 Settings for Django s3 Storage AWS_QUERYSTRING_AUTH = False # Amazon S3 DEFAULT_FILE_STORAGE = 'django_s3_storage.storage.S3Storage' # The AWS region to connect to. AWS_REGION = "eu-west-3" # The AWS access key to use. AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] # The AWS secret access key to use. AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] # The optional AWS session token to use. # AWS_SESSION_TOKEN = "" # The name of the bucket to store files in. AWS_S3_BUCKET_NAME = os.environ['AWS_S3_BUCKET_NAME'] # How to construct S3 URLs ("auto", "path", "virtual"). AWS_S3_ADDRESSING_STYLE = "auto" # The full URL to the S3 endpoint. Leave blank to use the default region URL. AWS_S3_ENDPOINT_URL = "" # A prefix to be applied to every stored file. This will be joined to every filename using the "/" separator. AWS_S3_KEY_PREFIX = "" # Whether to enable authentication for stored files. If True, then generated URLs will include an authentication # token valid for `AWS_S3_MAX_AGE_SECONDS`. If … -
Django form wizard - how to prevent field values from resetting?
I am using Django form wizard to fill a multistep form, its taking in the inputs and saving to the database and all but the problem is when ever i am navigating through the steps using "previous" i am see the clear fields with no data in it. i just want the data to be displayed there for reference when i go back. here are my forms.py `class AppEditForm(forms.Form): #App Name applicationfullname = forms.CharField(label='Application Full Name: ', max_length=80, required = False) #Full Name applicationabbreviatedname = forms.CharField(label='Application Abbreviated Name: ', max_length=40, required = False) class AppEditForm1(forms.Form): #Business Sponser businesssponsoredwpersonid = forms.CharField(widget= autocomplete.Select2(url='WorkerDim_ac', attrs={'data-placeholder': 'Search values', 'data-width': '25em'}), required = False, label="Business Sponsor Name: ") #Application Owner applicationowneredwpersonid = forms.CharField(widget= autocomplete.Select2(url='WorkerDim_ac', attrs={'data-placeholder': 'Search values', 'data-width': '25em'}), required = False, label='Application Owner Name: ') #Business Owner businessowneredwpersonid = forms.CharField(widget= autocomplete.Select2(url='WorkerDim_ac', attrs={'data-placeholder': 'Search values', 'data-width': '25em'}), required = False, label='Business Owner Name: ') ` here is my html <!DOCTYPE html> {% extends "newapp/base.html" %} {% load i18n static %} {% load staticfiles %} {% load crispy_forms_tags %} {% block title %}Addapplication{% endblock title %} {% block head %} {{ wizard.form.media }} <link rel="stylesheet" href="{% static 'css/addapplication.css' %}"> <script type='text/javascript'>function formProcess(){ var capture = document.forms['input']['id_1applicationfullname'].value … -
How to tie mysql database in one container to another container running my django blog app (with docker-compose)
I have created a blog app with django and attached it to a mysql database stored on my local machine(localhost), which I manage through phpmyadmin. However, I switched to an ubuntu 18.04 LTS (previously on a windows machine) and wanted to deploy my app with docker containers. I want to run mysql database in one container, and my blog app in another container, and have them communicate with each other (I am using docker-compose to achieve this). Below is the DATABASES dictionary on my app: And here is docker-compose.yml file. After firing the docker-compose up command, I get this error: It says '(2006, "Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/mysql/lib/plugin/caching_sha2_password.so: cannot open shared object file: No such file or diectory")'. -
how to get id from Url in python django last v?
I want to get the id from url in Django for a python programming language but I face the problem page no found. I want the code for this in the last version in Django because I have it please help me -
DJango - Generic ModelAdmin definition
This is a newbie question. I have multiple models that I would like to show in admin view. I would like to show all model's fields when viewing a list of records for a model. I'd like to define a generic ModelAdmin subclass which will be able to list out all fields for a model. But not sure how to pass the class objects to it. admin.py looks like this class ModelFieldsAdmin(admin.ModelAdmin): def __init__(self, classObj): self.classObj = classObj self.list_display = [field.name for field in classObj._meta.get_fields()] admin.site.register(Candy, ModelFieldsAdmin) admin.site.register(Bagel, ModelFieldsAdmin) How can I pass the classObj (which would be one of the models Candy or Bagel) , and also ensure that the get_list_display() picks up the value from self.list_display ? -
Django - how to disable Referer check
I have put a Django-based web project (Cloudera Hue: https://github.com/cloudera/hue) behind nginx used for load balancing and SSL offloading. Getting stuck on 403 error with CSRF error. Log file contains 5:32:32 PM WARNING access 10.170.3.21 -anon- - "POST /accounts/login/ HTTP/1.1" -- Referer checking failed - https://hue-dev.discover.abc.com/hue/accounts/login/?next=/ does not match https://hue-dev.discover.abc.com:443/. Is there is a way to disable Referer check in a Django project? Referer check doesn't add any security as Referer in http header can be easily spoofed. https://security.stackexchange.com/questions/66165/does-referrer-header-checking-offer-any-real-world-security-improvement I already have following in nginx.conf proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host:$server_port; proxy_set_header X-Forwarded-Server $host; and also tried following changes regarding Referer http attribute: proxy_pass_header Referer proxy_hide_header Referer proxy_set_header $http_referer all of these options produce the same CSRF/Referer check error in Django/Hue backend. Again, for me it would be just easier to disable Referer check in Django. If it's not possible, then the issue is probably in Django code here: https://github.com/django/django/blob/22e8ab02863819093832de9f771bf40a62a6bd4a/django/middleware/csrf.py#L280 referer variable there is a urlparse object (see https://docs.python.org/3/library/urllib.parse.html ) which contains "netloc" property with a port. Notice the error again - netlocs don't match because one has a port (443) and another doesn't have it (443 port is default for … -
Query orm Django para obter a quantidade de um filtro
O que eu tenho, essa query no orm django retorna a quantidade de id numa sala views.py sala = Post.objects.all()\ .values('sala')\ .annotate(value_pk=Count('pk')) Eu tenho saida: "sala 25=30" models.py class Post(models.Model): nome = models.CharField(max_length=150) sala = models.CharField(max_length=20) confirm = models.BooleanField( default=False ) O que eu preciso que me retorne o valor de "confirm" de acordo com a sala O que preciso saida: "sala 25=30 confirm=17"