Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change list view output field in django rest framework
I'm new to the Django and the Django Rest Framework, and having some issues figuring this one out. I've got a Model of Workouts, which contains a title and a many to many relationship field exercises. When making the api for the model, I'm inheriting the viewsets.ModelViewSet class - which from my understanding setups the common uses for a rest api (List, Create, Update etc.). This is fine however, when accessing /api/workouts/ I get a list of all the workouts including all the exercises assigned to the workout, I feel it's a bit of a waste to pull in all that exercise data and the user might never see it. I would prefer to have a the /api/workouts/ not return exercises and it only does so if a user accesses a workout with /api/workouts/1 the exercises will show up. My serializer class, class WorkoutSerializer(serializers.ModelSerializer): exercises = ExerciseSerializer(read_only=True, many=True) class Meta: model = Workout fields = ('id', 'title', 'exercises') My view, class WorkoutView(viewsets.ModelViewSet): queryset = Workout.objects.all() serializer_class = WorkoutSerializer def list(self, request): workouts_list = self.get_queryset().defer('exercises'); serializer = self.get_serializer(workouts_list, many=True) return response.Response(serializer.data) My latest attempt is to overwrite the list method and remove the field with the queryset, but it seems anything … -
How to display Foreignkey table Data in Django?
I have Customer and CustomerProfile models, and customer have some information in customerprofile model, i want to get the data from CustomerProfile models, Please let me know how i can get the data. Here are my models.py file... class Customer(models.Model): name=models.CharField(max_length=50, blank=True, null=True) type=models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name class CustomerProfile(models.Model): product=models.ForeignKey(Customer, default=None, related_name='product_info', on_delete=models.CASCADE) title=models.CharField(max_length=50, null=True, blank=True) number=models.IntegerField(default=None) def __str__(self): return self.title Here is my single customer views.py file.. def customer_info(request, name): customer=Customer.objects.get(name=name) context={'customer':customer} return render(request, 'customer/profile.html', context) Here is my profile.html file.. <h1>{{customer.name}}</h1> <h1>{{customer.email}}</h1> <h1>{{customer.mobile}}</h1> <h1>{{ustomer.title}}</h1> <h1>{{ustomer.number}}</h1> I am unable to display the title and number, please let me know how i can display. -
Cannot open jpg images with PIL or open()
I am testing to save ImageField in Django, but for some reason all the *.jpg files I've tried don't work while the one png I had works. If I do with open(): # this has no error f = open('loko.jpg', 'rb') #if I do f.read() # it shows only b'', like its empty # this saves the field but the image is 0 bytes and cannot be open object.image.save('name', File(f)) If I do with PIL: from PIL import Image # this shows error # PIL.UnidentifiedImageError: cannot identify image file 'loko.jpg' img = Image.open('loko.jpg') With the .png image I've tried, both methods work great. What could be the problem? -
Django IntegrityError: UNIQUE constraint failed
I was trying to run the blog website, so I created some classes in models.py to do so. However, I kept getting this django.db.utils.IntegrityError: UNIQUE constraint failed: new__my_app_post.author_id error every time I tried to migrate the models.py... I did lots and lots of research, and tried lots of things to fix this, nothing worked... I saw someone said it was the issue with OnetoOneField, so I changed my user to ForeignKey, didn't work I also tried to go to shell, import the modelsname and did the objects.all.delete(), didn't work I understand that this error is caused because I already have an author object with the user id, but I have no idea how I should go about fixing this... My models.py User = get_user_model() class PostView(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return self.user.username class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username class CategoryBlog(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() content = RichTextUploadingField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) # comment_count = models.IntegerField(default=0) # view_count = models.IntegerField(default=0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField(upload_to='pictures') categories = models.ManyToManyField(CategoryBlog) featured = models.BooleanField(null=True) previous_post = models.ForeignKey('self', related_name='previous', … -
Django Rest Framework: How to get instance of related foreign key
Note: IF INFORMATION BELOW IS NOT CLEAR TO UNDERSTAND - PLEASE ASK ME, I WILL UPDATE AND POST INFORMATION YOU NEED | It is important for me In Warehouse(models.Model) I have amount attribute and in ChosenProduct(models.Model) - quantity I'm trying to get amount in Warehouse through chosen_products instance in App_formSerializer to add the quantity of chosen_product But I can not get the chosen_products objects from instance --> below Out: class WarehouseSerializer(serializers.ModelSerializer): category_name = serializers.ReadOnlyField( source='category_product.category_name') posted_user = serializers.ReadOnlyField( source='posted_user.username') class Meta: model = Warehouse fields = ['id', 'category_product', 'category_name', 'condition', 'product_name', 'amount', 'barcode', 'f_price', 'created_at', 'updated_at', 'posted_user'] class ChosenProductSerializer(serializers.ModelSerializer): product_info = WarehouseSerializer(source='product', read_only=True) period_info = Product_periodSerializer(source='period', read_only=True) class Meta: model = ChosenProduct exclude = ('app_form',) class App_formSerializer(serializers.ModelSerializer): chosen_products = ChosenProductSerializer(many=True) def update(self, instance, validated_data): instance.terminated = validated_data.get('terminated', instance.terminated) if instance.terminated == True : print('-----------TRUE--------------------') print(instance.chosen_products) print('-----------PRINT--------------------') instance.save() return instance class Meta: model = App_form fields = '__all__' Out -----------TRUE-------------------- creditapi.ChosenProduct.None -----------PRINT-------------------- -
How can I allow a user to tap on words in an article and upgrade the article model in Django?
I am actually asking if anyone is so kind to get me out of this hole. I am learning python /django/posgres and I got to a point where I don't really know what to do next and I would appreciate some direction! I am designing this webapp for my students. The idea is that they can read texts and be able to tap on the words and mark them as learnt (for example: red for unknown words and green for known words) and I want every user to keep their modified text. At first I tought of jquery (which seems to be an old tool) but of course data is not overwritten. One of the approaches I tought of was some kind of post request as if it were a form... make every word to behave like a button. I dunno. I think I am somehow wrong in my approach. How would you approach this? What do you suggest me to read? I am not only trying to solve this but I am also trying to learn . Thanks in advance. This is what I did so far: https://billsiosoreadingposgres.herokuapp.com/ I was inspired by the following webpage: https://www.lingq.com/ Part of My … -
Not able to apply a custom image class with css in Django
I am new to Django, html, and css :). I have a general and a specific img style in ./static/css/style.css as follow: img { max-width: 100%; height: auto; max-height: 400px; margin-left: auto; margin-right: auto; } img.logo{ width: 20px; } And I add the site logo in the body in ./templates/base.html like this: <body> <a href="{% url 'home' %}"> <img class="logo" src="../static/images/logo.png"> </a> ... However, the image only inherits the base class information img, and is not using the width from the logo class. What am missing? -
RecursionError: maximum recursion depth exceeded while calling a Python object - Django framework
I am using below libraries snowflake-connector-python==2.2.9 gevent==1.3.4 boto3==1.7.58 requests==2.22.0 When I was trying to upload a file to S3 using python(Django framework), it is throwing below exception. super(SSLContext, SSLContext).options.__set__(self, value) [Previous line repeated 299 more times] RecursionError: maximum recursion depth exceeded while calling a Python object Below is the complete traceback of the error: I have already spent a fair amount of time in resolving this issue but no luck. Many threads are talking about "monkey patch all" but I don't have a clear idea on it. Can someone please help? Traceback (most recent call last): File "/home/ec2-user/NitrogenAI/Nitrogenai/middle-tier/business/services.py", line 2241, in downloadCorrelationDetails data = s3.Object('correlation-details', fileName).put(Body= csv_buffer.getvalue()) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/boto3/resources/factory.py", line 520, in do_action response = action(self, *args, **kwargs) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__ response = getattr(parent.meta.client, operation_name)(**params) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/botocore/client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/ddtrace/contrib/botocore/patch.py", line 71, in patched_api_call result = original_func(*args, **kwargs) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/botocore/client.py", line 599, in _make_api_call operation_model, request_dict) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/botocore/endpoint.py", line 148, in make_request return self._send_request(request_dict, operation_model) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/botocore/endpoint.py", line 177, in _send_request success_response, exception): File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/botocore/endpoint.py", line 273, in _needs_retry caught_exception=caught_exception, request_dict=request_dict) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/botocore/hooks.py", line 227, in emit return self._emit(event_name, kwargs) File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/botocore/hooks.py", line 360, in _emit aliased_event_name, kwargs, stop_on_response File "/home/ec2-user/NitrogenAI/nitrogenai_env/lib/python3.6/site-packages/botocore/hooks.py", … -
Django says pillow is not installed yet it is installed to latest version
I used an imagefield and when I made migrations it showed this error (venv) C:\Users\Eli Heist\PycharmProjects\Vector Final>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: vector.Project.pic: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". I ran the command and It was satisfied already (venv) C:\Users\Eli Heist\PycharmProjects\Vector Final>python -m pip install Pillow Requirement already satisfied: Pillow in c:\users\eli heist\pycharmprojects\vector final\venv\lib\site-packages (7.2.0) What could be the problem Even django and pip are up to date -
Getting variables and assigning them in a loop
I am trying to get 10 variables from an HTML form. All variables in HTML are in format (v1, v2.....v10) I can do it like following without a problem var1=request.GET.get("v1") var2=rquest.GET.get("v2") ... This is very repetitive. I am trying to get them in a list with a loop. var=[] for i in range(10): placehold="var"+str(i) var[i]=request.GET.get(placehold) This is not working. How can I get those 10 variables into a list using for loops? In addition, even if I get all values in a manual way I can't put them in a list in a for loop newlist=[] for i in range(10): combined="var"+str(i) newlist.append(combined) is not working. What am I doing wrong? -
Embedded Videos on other sites are working, but not on my (Django)
so i try to embed youtube videos on my website: http://mario3011.pythonanywhere.com/video (looks bad i know) and i doesnt work. It always says Video is not available. But if i check on this site: http://mesdomaines.nu/eendracht/youtube_embedding_check/youtube_embedding_check.html#:~:text=The%20only%20sure%20way%20to,video%20can't%20be%20embedded the videos i wanna embed are workin? so what am i doing wrong? This is the code: <iframe width="560" height="315" src="{{ obj.0 }}" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen>{{obj.0}}</iframe> and this is another version with the django-embed-video api: {% video obj.1 '940x705' %} -
Django get_media_prefix with trailing slash to Javascript url
I'm having problems getting my MEDIA_URL (which is something like https://example.com/media/) to use in Javascript. I can use the get_media_prefix template tag as var media_prefix = {% get_media_prefix %}; to fetch my MEDIA_URL but it gives me an unexpected token ':' error, which makes sense because the URL has a ':' after the https part. I tried converting it to a String with var media_prefix = String({% get_media_prefix %}); but then the error is the String function does not see the closing ')' as it is escaped by the trailing slash in the URL. Same problem if I try var media_prefix = new URL({% get_media_prefix %}); How can I resolve my trailing slash problem? -
Make a unique form for each individual user
I need to make a unique form for each individual user but I'm not exactly sure how. My thought process is to have a list of possible fields and an admin checks the boxes on whether or not he wants the field to show up in the rendered form. When the form is rendered it could pull the list of fields the user is able to see and render a form based on that list. Is this possible or do I need to make a form for each user? -
Sending an email to a user to open a specific url in django
I am developing a Django Application right now. I have a signup and login feature setup on my site. My website currently has a "special" group of users that would require to access an additional page. This page, for design reasons, should only be accessed by that specific user. I wouldn't want to have that URL be public and be accessed by merely typing it in the browser (Very similar to a password reset design). How do I go about doing this, considering that I would want to send an email with the link? Would this involve a token authentication? -
How to Make Wordpress / Shopify static settings but for a Django Project?
I'm not at all sure that I worded this right, but couldn't think of how else to explain it. I'm wanting to make a front-end settings (similar to Wordpress or Shopify) where you could add default information to the site, like for example I'd like to add updateable: Contact Information Menu Links Logo Image etc. from the django admin area. Really I'm not even sure how I'd start coding something like this. I have an idea of making a complicated sections model, for example I have a base app where I keep all my defaults and create something like this inside: # base/models.py # Will use lists for choices for example for explaination purposes class Section(models.Model): # Choices PAGE_CHOICES = ['About', 'Contact', 'Home'] ELEMENT_CHOICES = ['Navbar Menu', 'Footer Menu', 'Site Phone number', 'Etc.'] # Fields name = models.CharField(max_length=50, help_text="What do you want the title of this section to be?") page = models.CharField(max_length=50, choices=PAGE_CHOIES) element = models.CharField(max_length=50, choices=ELEMENT_CHOICES) def __str__(self): return self.name Something like that, but I would assume that it'd have to be somehow able to be preloaded to the project and only be able to updated, even be empty, but not deleted or created. Has anyone ever done something … -
Copying a list of Model Fields instances in Django Rest Framework
I find myself stuck with this problem and I might have phrased the title wrong but will explain what I want to do and what I am willing to accomplish. I have a model for attedance and on a daily basis a teacher has to mark an attendance Register. I wouldnt want a situation where when generating a register data has to be captured on a daily basis but I would like were a table like form with a copy of all students in a class created with only status being the fields to be edited and saved, thus on save of each student their day attendance record is created. My model is like as follows: class StudentAttendanceTimeSheet(models.Model): DAILY_ATTENDANCE_STATUS_CHOICES = [(1, 'Present'), (2, 'absent'), (3, 'sick')] student = models.Foreignkey('Student', related_name='attendances', on_delete=models.CASCADE) attendance_status = models.CharField(max_length=50, choices=DAILY_ATTENDANCE_STATUS_CHOICES, default='1') date = models.DateField(default=datetime.today()) class = models.ForeignKey('Class', related_name='class_timesheets, on_delete=models.CASCADE) I would like to make a step form where by when I hit the select button a copy would be made with those fields prepopulated with database data for a specific class. Thus a list of all students enrolled in that class. May someone help me with how they would create a Django Rest Create View … -
How to customize the rest auth in django
I want to erase username, password2 field from rest auth and add nickname and profile image. So we made the code as follows, but Nickname and profile image were added normally, but username and password2 were not erased. How can I erase them? Here is my code. models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, profile, nickname, password): user = self.model( email=self.normalize_email(email), nickname=nickname, profile=profile, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) nickname = models.CharField(max_length=10) profile = models.ImageField(default='default_image.jpeg') objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] serializers.py from rest_framework_simplejwt.serializers import TokenObtainSerializer from .models import User from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from django.utils.translation import ugettext_lazy as _ class CustomRegisterSerializer(RegisterSerializer): nickname = serializers.CharField(required=True) profile = serializers.ImageField(use_url=True) def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with … -
Not able to work out the update_or_create method in django in posting data to the database
I am having a model that has several fields. This is my views.py: def person(request): customer=request.user.customer if request.method == "POST": hobbies=request.POST['hobbies'] sports=request.POST['sports'] school=request.POST['school'] swimming=request.POST['swimming'] details=Details.update_or_create(hobbies=hobbies,sports=sports,school=school,swimming=swimming) details.save() Whenever a customer enters the respective details in the form in html I want it to be saved if he is entering for the first time and if he already has his details entered earlier but wishes to edit them I want to update the same object instead of creating a new one. I tried using update_or_create method but its giving me error. Please help me. Thnx -
how to skip first element from from loop in django
this is my home.html {% for i in ind %} {{ i.state }}<br> {% endfor %} in this for loop i do not want first data coming from ind, i want all data except first data then how to iterate this for loop, this is Django project this is my views.py res = requests.get("https://api.covid19india.org/data.json") ind = res.json()['statewise'] the data of ind variable is going to for loop but i do not want first data of ind variable -
Django, saving image to ImageField saves empty image
I am trying to make thumbnails of images while keeping the original image. I was testing how it works in django shell: from PIL import Image from ads.models import Ad ad = Ad.objects.get(pk=1) ## relevant field: ## thumbnail = models.ImageField(default='ad_thumbnails/default.png', upload_to='ad_thumbnails') # i have some test image: loko.jpg in project root f = open('loko.jpg', ['w','r+','rb','wb+']) # tried them all file = File(f) ad.thumbnail.save('name', file) It save to the desired place and in the database, but the thumbnail is 0 bytes, cannot be opened. Irfanview says "uknown format" What am I missing? -
Error 'image' object has no attribute 'file' in Django
I want to implement the feature when deleting data from the database, and all related images in the "media" folder are deleted. and this is my code from django.db import models from django.dispatch.dispatcher import receiver import os class imageCategory(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) img = models.ImageField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title @receiver(models.signals.post_delete, sender=imageCategory) def auto_delete_file_on_delete(sender, instance, **kwargs): if instance.file: if os.path.isfile(instance.file.path): os.remove(instance.file.path) @receiver(models.signals.pre_save, sender=imageCategory) def auto_delete_file_on_change(sender, instance, **kwargs): if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).file except sender.DoesNotExist: return False new_file = instance.file if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) class image(models.Model): title = models.ForeignKey(imageCategory, default=None, on_delete=models.CASCADE) img = models.ImageField(null=True) @receiver(models.signals.post_delete, sender=image) def auto_delete_file_on_delete(sender, instance, **kwargs): if instance.file: if os.path.isfile(instance.file.path): os.remove(instance.file.path) @receiver(models.signals.pre_save, sender=image) def auto_delete_file_on_change(sender, instance, **kwargs): if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).file except sender.DoesNotExist: return False new_file = instance.file if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) But I get the error 'image' object has no attribute 'file', We look forward to everyone's guidance Thank you -
Get html text-input element from django-form in template
Given a {{ form }} in a template for a model with a models.TextField called text, is there a way to access the html text-input field inside the same template directly from the form ? I need something like document.getElementById() but don't know what id to pass. -
How to create a named url for Django documentation created using Sphinx
In my Django project I created a rudimentary documentation using Sphinx. Now what I wanted to test was calling the documentation index page (index.html) as I would for a standard Django view using named url. I have been browsing for quite a while but it seems that without some 3rd party app (such as django-docs) it is not possible to create the scenario (I hope I am wrong). I am trying to avoid using a hardcoded link for the purpose. Is there a way I may call the documentation from anywhere in my Django app using a dynamic link (preferably using a shortcut)? -
TypeError at /wiki/HTML
When I try to load my title.html template this TypeError occurs. My logic is simple: If an entry is requested that does not exist, the user should be presented with an error page indicating that their requested page was not found. If the entry does exist, the user should be presented with a page that displays the content of the entry. The title of the page should include the name of the entry. My urlpatterns (inside encyclopedia/urls.py): urlpatterns = [ path("", views.index, name="index"), path("wiki/", views.title, name="title"),] My views (inside encyclopedia/views.py): def title(request, title_name): return render(request, "encyclopedia/title.html",{ "entry": util.get_entry(title_name), "title": util.get_page_name(title_name) }) And of course the util.py as follows: def get_entry(title): try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None def get_page_name(title): try: name = os.path.basename(f'entries/{title}') return name except TypeError: return None For more info regarding the title.html: {% extends "encyclopedia/layout.html" %} {% block title %} <p>{{ title }}</p> {% endblock title %} {% block body %} <p> {{ entry }}</p> {% endblock body %} Since I get a TypeError at /wiki/HTML title() got an unexpected keyword argument 'title' my guess is that the template I wrote doesn't do the job? -
Api request timeout issue on django server
Django server is running inside an ubuntu docker container.Sometimes api are not reachable and throwing request timeout error but django server is running and there is no traceback at the time of timeout issue. After sometime api are accessible without restarting server. Getting this issue 3 to 4 times in day.