Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building Django model form JSON file
I'm new to django and am trying to build a model from a JSON object that I'm receiving from a third party API call. At the moment, I manually created the model with my best guesses for data type as some of the fields come in null. Is there a way to create this model from the data so that there is no human error? models.py import datetime from django.db import models from django.utils import timezone from django.contrib.postgres.fields import ArrayField # Create your models here. class Address(models.Model): city = models.CharField(max_length=200) neighborhood = models.CharField(max_length=200) state = models.CharField(max_length=200) street_address = models.CharField(max_length=200) zipcode = models.CharField(max_length=10) class Phone(models.Model): prefix = models.CharField(blank=True, null=True, max_length=3) area_code = models.CharField(blank=True, null=True, max_length=3) number = models.CharField(blank=True, null=True, max_length=4) class Phone2(models.Model): prefix = models.CharField(blank=True, null=True, max_length=3) area_code = models.CharField(blank=True, null=True, max_length=3) number = models.CharField(blank=True, null=True, max_length=4) class ContactRecipients(models.Model): agent_reason = models.IntegerField(blank=True, null=True) zpro = models.CharField(blank=True, null=True, max_length=200) recent_sales = models.IntegerField(blank=True, null=True) review_count = models.IntegerField(blank=True, null=True) display_name = models.CharField(blank=True, null=True, max_length=200) zuid = models.CharField(blank=True, null=True, max_length=200) rating_average = models.IntegerField(blank=True, null=True) badge_type = models.CharField(blank=True, null=True, max_length=200) phone = models.ForeignKey(Phone, on_delete=models.CASCADE) image_url = models.CharField(blank=True, null=True, max_length=2000) class ListedBy(models.Model): agent_reason = models.IntegerField(blank=True, null=True) pro = models.BooleanField() recent_sales = models.IntegerField(blank=True, null=True) review_count = models.IntegerField(blank=True, null=True) … -
JSONField unexpected token inside javascript
im working with django 3.0.2, and I need to store a json, I installed django-jsonfield, I managed to save json data, but when I load values from this field I get unexpected tokem error, Ive tried parsing inside js the js script, |safe and |escapejs in the field tag, but still I get this error Uncaught SyntaxError: Invalid or unexpected token pointing to the first ' in the loaded json also I tried loading the jsonify tag as the domcumentation on django-jsonfield says, but I got an unrecognized tag error isnt better to store json as textfield and then parsing on javascript?? -
django rest framework serialized add an auto generated field when getting data
i want to automatically generate a field when data comes out of the database. here is an example serializer i have. class SaleSerializer(serializers.ModelSerializer): class Meta: model = Sale fields = '__all__' i want this serialized to have two extra fields that dynamically generate one called username which has a string username of the user obejct and the other shop name that has the name of the shop object her is the model of sale that the serializer uses. class Sale(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.DO_NOTHING) reciept = models.TextField() date_time = models.DateTimeField(auto_now_add=True) def __str__(self): return f"reciept number {self.pk}" -
Permissions Django how do custom
I develop app in Django and have question about permissons. I have name course -> modules in course If my user click on button i want to show him certain course with all modules. How can i do this ? -
How to add comments under each post in ReactJs + Django
I want to ask; if I render specific content or post to users and they can add reply to this post, in order to allow them to add reply, they must provide the Id for the post when they submit but I have problem to deal with it; Below: first extract slug that will bring content based on user choice, and then assign => let IdPost = data.posts.id to match with comment const { slug } = useParams(); const [data, setData] = useState({ posts: [] }); useEffect(() => { axios.get(slug).then((res) => { setData({ posts: res.data }); console.log('a single post', res.data); // author, content, id, image, published, slug, title }); }, [slug]); let IdPost = data.posts.id and here for type comment and submit it: const createComment = Object.freeze({ body: '', }); const [postComment, updateComment] = useState(createComment); const handlerOnChange = (e) => { updateComment({ ...postComment,[e.target.name]: e.target.value }); }; const handlerOnSubmit = (event) => { event.preventDefault(); let formComment = new FormData(); formComment.append('body', postComment.body); axios.post(`http://localhost:8000/comment/create/`, formComment, { headers: { Authorization: `JWT ${localStorage.getItem('token')}`, 'Content-Type': 'application/json' } }) }; this code to list comments: const [Comments, setComments] = useState([]); useEffect(() => { axios.get("http://localhost:8000/comment/list").then((res) => { const allComments = res.data; setComments(allComments); }); }, [setComments]); const filterComments = … -
how do I adjust the size of a container in the following page? (bootstrap, django)
I'm a beginner in web development and creating a simple website. I'd like to adjust the red container behind the contact form so it's not visible all over the page.. in fact I'd like it to be just a bit bigger then the form so I can use it as a background. Here is the codes that I've been working on. I'd appreciate it for any tips, advice and corrections. thank you. {% extends "pages/base.html" %} {% block header %} <header> <div class="p-4 text-black rounded-3 bg-danger"> <form> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label for="Email">Email address</label> <input type="email" class="form-control" id="Email" placeholder="name@example.com"> </div> </div> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label for="FirstName">first name</label> <input type="name" id="FirstName" class="form-control placeholder="first name"> </div> </div> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label for="Number">Number</label> <input type="number" class="form-control form-control-sm" id="Number" placeholder="01-2345-6789"> </div> </div> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label for="Select"> Select an inquiry</label> <select class="form-control" id="Select"> <option> 1. Do you like Ullie? </option> <option> 2. Do you hate Ullie? </option> <option> 3. Do you think Ullie is cute? </option> <option> 4. Do you think Ullie is stupid? </option> <option> 5. Ullie is een stupid hond </option> </select> </div> </div> <div class="row d-flex justify-content-evenly"> <div class="col-md-5"> <label … -
Is there any way to connect the Yahoo Finance API to Django?
I've been looking through how to use the data from Yahoo Finance API in my Web Application, but I didn't really find an answer on the Internet. Using the yfinance module only in Python is pretty straight forward but I wanna make a connection between this API and Django, so I can display for example the line chart for a certain company, and some basic financial info. Also, is there any possibility to make this extraction dynamic so the metrics can change in real time if I change the start and the end date? One last question, I would like to not download the data, I wanna call it from the API if it's possible. Thanks -
kswapd0 is high CPU in ubantu 20.04
I have a droplet in digital ocean. My application was running there from last 1 year smoothly. suddenly there is in increase of CPU due to kswapd0(all most 200%) In the application there were huge number of file stored in /media folder . To clear the CPU deleted all most all the media files. but still the problem persists. any help will be appreciated. Thanks in advance. TOP view from the server. PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1231 xxxxx 20 0 2919964 2.3g 2936 S 199.7 59.6 189:30.26 kswapd0 1 root 20 0 168560 12712 8420 S 0.0 0.3 0:02.52 systemd 2 root 20 0 0 0 0 S 0.0 0.0 0:00.00 kthreadd 3 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 rcu_gp 4 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 rcu_par_gp 6 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 kworker/0:0H-kblockd 9 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 mm_percpu_wq 10 root 20 0 0 0 0 S 0.0 0.0 0:00.18 ksoftirqd/0 11 root 20 0 0 0 0 I 0.0 0.0 0:00.72 rcu_sched 12 root rt 0 0 0 0 S … -
Python PIL save method rotates image
I have a little issue with saving image with PIL. In my Django project I have the following save method: from PIL import Image class Photo: image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/', help_text='Photo') def save(self, *args, **kwargs): super(Photo, self).save(*args, **kwargs) image = Image.open(self.image) image.save(self.image.path) So, here I open the image with PIL and just save it in its default path. But looks like depending on image's EXIF data (metadata) PIL rotates the image before saving it. For example, I took a picture of a person (I was holding the phone vertically, as normal) and when I saved it, the picture was rotated by 90 degrees to the left. What could be the matter here? It works only if the Orientation was vertical, nothing bad happens to images taken horizontally. Please help and huge thanks in advance! Original image, Saved image -
Django / DRF: annotate a model with extra (computed) information
I'm adding a very simple roadmap voting feature to my website, where people can add feature requests, and people can then vote on each other's suggestions. The basics are pretty simple: # models.py class FeatureRequest(models.Model): title = models.CharField(max_length=50) description = models.TextField() author = models.ForeignKey(User, editable=False, on_delete=models.CASCADE) is_implemented = models.BooleanField(default=False, editable=False, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Vote(models.Model): feature = models.ForeignKey(FeatureRequest, editable=False, on_delete=models.CASCADE) user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ["feature", "user"] #views.py class RoadmapController(viewsets.ModelViewSet): permission_classes = (AuthorOrReadOnlyPermission,) serializer_class = FeatureRequestSerializer def get_queryset(self): return FeatureRequest.objects.filter(is_implemented=False) def perform_create(self, serializer): return serializer.save(author=self.request.user) # serializers.py class FeatureRequestSerializer(serializers.ModelSerializer): class Meta: model = FeatureRequest fields = "__all__" There is also a separate view for actually posting and deleting votes, but that's not needed here for my question. What I want is that the response of the feature request list includes the number of votes for each one, and a boolean if the logged-in user has voted for it: [ { "title": "This is a feature request", "description": "Foo bar", "author": 1, "number_of_votes": 1, "has_my_vote": true } ] I already figured out that I can change my queryset to FeatureRequest.objects.filter(is_implemented=False).annotate(number_of_votes=Count("vote")), add number_of_votes = serializers.ReadOnlyField() to the serializer, … -
group_concat alternative in django
I have 2 models with many-to-many relationship: class Tag(models.Model): name = models.CharField(max_length=100, unique=True) class TagName(models.Model): name = models.CharField(max_length=6, unique=True) tags = models.ManyToManyField(Tag) I have a drop-down list that allows multiple selections of Tags. I want to check if TagName with selected Tags exists. I don't want to use GROUP_CONCAT and raw sql. I found this solution, but it doesn't work with variable number of Tags, e.g. it returns TagNames associated with Tags [1,2,3,4,5] and [1,2,3,4] in case of selecting Tags [1,2,3,4]. TagName.objects.filter(tags__pk__in=[1, 2, 3, 4]).annotate(num_attr=Count('tags')).filter(num_attr=len([1, 2, 3, 4])) Is there any way to do it using only Django methods? Thank in advance! -
How to use Utils from Chartjs on Django
I have a simple Django project that display some charts on a determined page, so when I try to replicate some examples from Chartjs I see that they make use of a Utils module file, when I make this same call in my views.py file it ends up returning errors since Utils is not defined anywhere @staff_member_required def chart(request, year): persons = Persons.objects.filter(time__year=year) grouped_purchases = purchases.annotate(price=F('item__price')).annotate(month=ExtractMonth('time'))\ .values('month').annotate(average=Sum('item__price')).values('month', 'average').order_by('month') sales_dict = get_year_dict() for group in grouped_purchases: sales_dict[months[group['month']-1]] = round(group['average'], 2) DATA_COUNT = 7; NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100} return JsonResponse({ 'title': f'Persons {year}', 'data': { 'labels': Utils.months({count: 7}), 'datasets': [{ 'label': 'Amount ($)', 'backgroundColor': Utils.CHART_COLORS.red, 'borderColor': colorPrimary, 'data': Utils.numbers(NUMBER_CFG), }] }, }) this is the header of the html file <head> <title>Statistics</title> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-v4-grid-only@1.0.0/dist/bootstrap-grid.min.css"> </head> I know that Utils is a JavaScript file which I can't import in Python, there is a way to solve this? -
django-crispy-forms ModuleNotFoundError but can import in console
i've been trying to get crispy forms working for 3 hours now it's driving me nuts, please help! (or suggest another/better way to style forms in django?!) i have added crispy_forms to installed apps as: INSTALLED_APPS = [ ... 'crispy_forms', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' i'm on windows 10, using pycharm-pro with a venv. the interpreter works fine for everything else i have installed. in terminal i can run python then import crispy_forms with no errors, but pycharm throws a ModuleNotFoundError if i try to makemigrations, or run the server. i tried toggling 'add contents and source root to system path" but honestly i don't really understand, and in any case it didn't help... thanks!! terminal outputs: PS E:\Dev\Spotify\spo_djangos> pip show django-crispy-forms Name: django-crispy-forms Version: 1.14.0 Summary: Best way to have Django DRY forms Home-page: https://github.com/django-crispy-forms/django-crispy-forms Author: Miguel Araujo Author-email: miguel.araujo.perez@gmail.com License: MIT Location: c:\users\ryzen\appdata\local\programs\python\python310\lib\site-packages PS E:\Dev\Spotify\spo_djangos> python Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import crispy_forms >>> python traceback: E:\Dev\Spotify\spo_djangos\.venv\python.exe E:/Dev/Spotify/spo_djangos/manage.py runserver 8000 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "E:\Dev\Spotify\spo_djangos\.venv\lib\threading.py", line 1009, in … -
How do you set filenames using Python's requests when uploading files to Django Rest Framework?
I'm using the Django Rest Framework. If I have a simple Django model: class MyModel(models.Model): file_field_1 = models.FileField(...) file_field_2 = models.FileField(...) And a simple serializer: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = models.MyModel fields = '__all__' I can upload files to this API endpoint using Python's requests like this: requests.post( URL, files={ "file_field_1": pathlib.Path("some_file.txt").read_bytes(), "file_field_2": pathlib.Path("some_other_file.txt").read_bytes(), }, headers={ "Authorization": "Token {MY_TOKEN}", } ) This works, but the filenames that Django saves are file_field_1 and file_field_2. I think there might be a way have requests tell Django what each file's filename should be using the Content-Disposition header, but I can't seem to get it working. How would I go about doing this? -
Only 1 image instance is displaying
I installed a logo next to the page title. Using the runserver command in the terminal, the logo image shows up on the homepage, but on subsequent pages (it just displays the alt text for when the image is not working). Any idea why I am running into this error, is it an issue with the html,urls, or view file? Homepage Not Homepage base.html: <img src="logo.jpg" alt="Logo">&emsp;Robo Depot url.py: from django.urls import path from . import views from .views import RegisterViewnew , product_list ,LoginView , logoutUser app_name = 'shop' urlpatterns = [ path('register/', RegisterViewnew.as_view(), name="register_user" ), path('login/', LoginView.as_view() , name="login_page"), path('logout/', logoutUser, name="logout"), path('', product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail,name='product_detail'), ] -
Django- cannot import ReCaptchaField from captcha.fields
I am trying to import ReCaptchaField from captcha.fields. However I am getting this error- ImportError: cannot import name 'ReCaptchaField' from 'captcha.fields' -
Taking an error 'no module named forms 'while trying to use django ratings
here is the link to how to use ratings in django enter link description here and I did what is necessary(added djangoratings to the settings.py and already install djangoratings) however I'm getting an error called 'no module named forms' here is the sample code in models.py and the ss of the error from django.db import models from djangoratings.fields import RatingField class Movie(models.Model): name = models.CharField(max_length=60) Music = RatingField(range=5) Story = RatingField(range=5) I'm getting and error File "C:\Users\asdas\.conda\envs\cultact\lib\site-packages\djangoratings\fields.py", line 4, in <module> import forms ModuleNotFoundError: No module named 'forms' What I'm doing wrong ? -
how to get json object out of django paginator value
am trying to get a Json value out of Django Paginator object so that i can return it back to html file as a json response via JsonResponse method.Please help Heres my Code users=User.objects.all().order_by("id") book_paginator=Paginator(users,10) page_num=request.GET.get('page') // say page==2 page=book_paginator.get_page(page_num) retutn JsonResponse({'data':page) I know it wont work but you get the point of what am trying to archieve. Please help Thank you. -
./manage.py runserver does not run server, opens manage.py file instead
I'm using Vscode to build a Django project and I've been using the ./manage.py + command for weeks now. It's worked fine until recently, if I now enter ./manage.py runserver it opens the manage.py file and creates a runserver text file, but it does not run the server. Strangely enough the command works if written like so: python manage.py runserver. I thought that ./ was meant to be a shortcut for python in that command, have you encoutered that problem? Have a nice day everyone! -
How to convert month number to roman?
Any ideia how to convert month number to roman ? Eg: 4 => IV I already get month number, i user date = datetime.date.today() month = date.month For the next step, any ideia how to convert to roman number? Thank you -
Django import export keep reading blank line
I'm using django import export. But sometimes I got an error when importing xlsx file. The error is simple actually. It keeps reading the blank row so it generates an error. For example, in my xlsx file, there are only two rows (one for the table header and one for the data). I don't know why but it also read the second and the third row even though there is no data in it. The error is something like this: Line number: 2 - 'NoneType' object has no attribute 'lower' None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None Of course, the data is all none, because I only want to import only one data so the second row is empty. How to fix this? Thanks. -
Test for custom ModelAdmin function with GET parameters
I'm trying to write a test for the following modelAdmin function: def response_add(self, request, obj, post_url_continue=None): """ Redirects to the public profile details page after creation if return=true """ if request.GET.get('return'): return redirect(reverse('public_profile_details', kwargs={'id': obj.id})) else: return redirect('/admin/public/publicprofile/') The purpose of this is when staff access the admin panel from the webpage via an "Edit" link (rather than from the admin panel directly), I want to return them to that page once the object is saved. I do this by attaching ?return=True to the admin link. However, I'm having trouble writing a test to cover this. This is the closest I've gotten: def test_admin_functions(self): self.login_privileged_user() self.GET = {'return': True} public_profile_model_admin = admin.PublicProfileAdmin(model=models.PublicProfile, admin_site=AdminSite()) response = self.client.get('/admin/public/publicprofile/1/change/?return=True') public_profile_model_admin.response_add(self, response, models.PublicProfile.objects.get(id=1)) However, this returns the following error: AttributeError: 'TemplateResponse' object has no attribute 'id' I can manipulate it slightly (changing from self.client.get to self.client.post) and get various other errors such as HttpResponse error, HttpResponseRedirect error, etc. But all of them have the same error of "object has no attribute 'id'". I know I could use Selenium to do this, but I'm trying to avoid that for my smaller tests as much as possible. -
Django models - Adding an item which the prices are different for different amounts
Basically i wish to add a product which has a collection of prices relating to different amounts i.e : bananas 1 for 1, 2 for 1.50, 3 for 2 I want to know how to add this data into my models -
How to open a terminal inside a sub-directory from django
I am learning django. I am stuck with this problem. I want to open a new terminal and execute a command in it. Here is the code that I used to do it. run(["gnome-terminal", "--", "sh", "-c", f"espeak -ven+m1 -f {file_name.name} -w {fbh}.wav "]) I have written the above code in my views.py file. Here, {file_name.name} is the name of the text file I take as input from the user {fbh} is the name of the generated audio file. Everything works perfectly but the problem is that the terminal opens in auto_generation directory but I want that it should open in media directory. media is a sub-directory of the auto_generation directory. Can someone please suggest me what changes I should do to the above command so that the new terminal opens in media directory instead of auto_generation directory? As I already said I am new to django and some help will be appreciated. -
permission based on the action/url in Django rest framewrok
I have a Modelviewset class that has several functions inside it like list(), destroy, partial_update() and also other custom functions like def get_examples(self,request). The thing is different functions have different permissions based on the user types. I have a separate permission class inside a permission file. Now I need to access the action inside the has_permission function. I know it can be done inside the get_permission function inside modelviewset class. But how can we do it inside has_permission function?? My View: class ExampleView(viewsets.ModelViewSet): queryset = Example.objects.all().order_by("-created_at") serializer_class = ExampleSerializer pagination_class = ExampleNumberPagination def list(self, request, *args, **kwargs): def partial_update(self, request, *args, **kwargs): def custom_fuctin_1(self,request,*args,**kwargs): def custom_fuctin_2(self,request,*args,**kwargs): def destroy(self, request, *args, **kwargs): Now permission file: class ExampleClassPermission(BasePermission): def has_permission(self, request, view): user =request.user if request.method == 'GET' or request.method == 'POST': return True elif request.method == 'DELETE' and (user.role == 'manager' or user.role == 'admin'): return True elif request.method == 'PUT': return True else: return False Here in this permission class, I want to set permission for custom function_1 and 2 in the view class. I cant do self.action == ''? just like in the get_permission.Can I??