Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf-spectacular: Add description to HTTP_204
@extend_schema( request=MyRequestSerializer, responses={200: MyResponseSerializer(many=True), 204: None, }, examples=[ OpenApiExample( '204', status_codes=['204'], summary="My documentation summary", description="My documentation description", response_only=True, ), ....] This is what I have tried, but what I get is -
Django migrate works but doesn't reflect on live site
I made some updates to a project: add 1 admin model, add 1 template I'm using wagtail. I pulled the updates to my server, ran migrations, got success. I restart nginx and gunicorn, I even rebooted the server. When I go to the wagtail admin, my adminmodel is missing (it exists locally). when I go to create a new page, my template is available, but when I select it I get taken to a wagtail 404 page. Ubuntu 20.04 ngnix gunicorn django/wagtail digital ocean vpc digital ocean postgres database cluster The site works like normal, only a template is available I can't select, and the Model, that migrated, isn't available and isn't showing up in admin. my local version is working perfectly, with no differences. it seems like the server is both updating and not updating. I don't get it. running makemigrations or migrate returns no changes. even when running on the specific app. Do I need to do something to rebot the database? -
Apache did not serve my Django project templates correctly
This index.html showed the apache default page. when I cd the /var/www/html and ls it, it showed the index.html which is the apache default index page. My question is: What should I do to change my own templates to be the page index page, should I cp the templates folder to this /var/www/html, or should I do something in the project.conf, or should I change the chown/chmod to the templates directory inside my project so that I achieve it? This is my sites-available/project.conf: <VirtualHost *:80> ServerAdmin root@localhost ServerName Server_IP ServerAlias Server_IP DocumentRoot /var/www/html #maybe the problem of this line Alias /static /home/ME/project/static <Directory /home/ME/project/static> Require all granted </Directory> Alias /media /home/ME/project/media <Directory /home/ME/project/media> Require all granted </Directory> <Directory /home/ME/project/Project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log </VirtualHost> ps. When I tried to change the documentroot to /home/ME/project_1/templates, the page showed the error of I don't have permission to access the file. -
Manipulating and passing JSON from back to front end in Django
From my DB, I am : Catching all the posts that my users posted. Order them from newest to oldest and ... Try to pass the load into JSONResponse so that my Front end Javascript can handle it. The idea is that for each post, it displays a DIV containing the data. def allpoststest (request, posttype): if posttype == "allposts": allposts_ever = Post.objects.all() allposts_ever = allposts_ever.order_by("-timestamp").all() # Serialize the QuerySet into JSON (This strings it) json_data = serializers.serialize("json", allposts_ever) # DeString it the data into JSON data (LIST) json_data = json.loads(json_data) # Try to turn list into numpy.ndarray json_data = np.array(json_data) # Context it context = {'json_data': json_data} # Pass the JSON formatted data to the Front End return JsonResponse(context, safe=False) document.addEventListener('DOMContentLoaded', function() { document.querySelector('#trigger').addEventListener('click', () => load_allposts('allposts')); }) function load_allposts(posttype) { fetch(`/test/${posttype}`) .then(response => response.json()) .then(response => console.log(response)) .then(json_data => { console.log(json_data); json_data.forEach(post => { const div = document.createElement("div"); div.innerHTML = ` <div class="card" style="width: 100%;"> <div class="card-body"> <h5 class="card-title">Posted by ${ post.user }</h5> <h6 class="card-subtitle mb-2 text-muted">Posted on ${ post.timestamp }</h6> <p class="card-text" style="text-align: center;">${ post.post }</p> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group mr-2" role="group" aria-label="First group"> <button id="likebtn" class="btn btn-info" type="button">Like</button> <button id="unlikebtn" class="btn … -
How can I join a table with an external API using Django?
I have a table in my database where I save the movies viewed by some user. It's something like this: tmdb_id view_date user_id 464052 15/02/2021 1 602269 14/02/2021 2 The field tmdb_id is the id of the movie in The Movies Data Base webpage. I can get the datails of this movie using his API and sending this ID as a parameter. In Django I have this view: class MovieViewView(APIView): permission_classes = (IsAuthenticated,) def get(self, request, format=None): queryset = MovieView.objects.all() serializer_class = MovieViewSerializer(queryset, many=True) return Response(serializer_class.data) When I request a GET to this view I obtain something like that: [ { "tmdb_id": "464052", "view_date": "2021-02-15", "user": 1 }, { "tmdb_id": "602269", "view_date": "2021-02-14", "user": 2 } ] But I would like to get something like this using TMDB API: [ { "title": "Wonder Woman 1984", "view_date": "2021-02-15", "user": 1 }, { "title": "The Little Things", "view_date": "2021-02-14", "user": 2 } ] I know how to get this data individually using Requests here but I want to know how to join it with my table. Is it possible? -
how to group divs with same date in django
I'm trying to make a match fixtures website and i want want all the games with the same date to be grouped together and above them the current date like this Feb. 14, 2021 game 1 game 2 game 3 Feb. 15, 2021 game 4 My Current html that display date above every game, (matches is a list of dictionaries), and the dates are already sorted {% for match in matches %} <div class="the_date"> {{match.date}} </div> <div class="match"> // match info </div> {% endfor %} I wanted to solve this problem by making a changing variable in a Django loop like this, but i couldn't find a way to do it in Django template last = {{ //null_date }} {% for match in matches %} {% if match.date == last %} <div class="match"> // match info </div> {% else %} <div class="the_date"> {{match.date}} </div> <div class="match"> // match info </div> last = {{match.date}} {% endif %} {% endfor %} -
Django: Authentication credentials not povided error as access and refresh tokens are set as HttpOnly cookies without Authorization header
I have set SimpleJWT access and refresh tokens as HttpOnly cookies. Therefore, I thought that I don't need to use the 'Authorization' header anymore, so I removed it. Now, when I'm making requests it's showing: {"detail": "Authentication credentials were not provided."} Here, I think I need to set the Authorization header to access token in the view. So far I have written this code but it is not working. I want it to set the Authorization header to the request and proceed: def list(self, request): access = request.COOKIES.get('access') request.META['Authorization'] = f"Bearer {access}" print(request.META.get('Authorization')) serializer = self.serializer_class(instance = self.request.user) return Response(serializer.data) How do I send the Authorization header with the request if it's not coming from the client? -
Retrieve Select2 multi values in Django Views to use in backend
I have a working Select2 Multi Dropdown in my html, but how do I bring these value back to Django to use in the backend? For example in my html, I have: <script> $(document).ready(function() { $("#ddlselect").select2({ placeholder:'Select from List', closeOnSelect:false }); }); </script> I then fill the dropdown with the following code: <select id="ddlselect" multiple="multiple" style="width: 250px;"> {% for item in mylist %} <option> {{ item }} </option> {% endfor %} </select> This works and I can choose from the dropdown. I can retrieve the values using the following in html: <script> function myFunction() { alert("Selected value is: "+$("#ddlselect").select2("val")); } </script> Now, how do I bring these values back to my Django Views? I have tried the following - class newoption(TemplateView): template_name = 'home/page.html' def get(self, request): return render(request, self.template_name, dict) def post(self, response): a = response.POST['ddlselect'] I get an error trying to return a to use on the backend. How do I retrieve the selected values from the select2MultiSelect? -
Serializing multiple levels in django
I am running a django application and I want to return a big JSON for my model structure. The problem is I always get the following error: Got AttributeError when attempting to get a value for field XXXX on serializer XXXXX. The serializer field might be named incorrectly and not match any attribute or key on the XXXX instance. Original exception text was: 'XXXX' object has no attribute 'XXXXX'. My model structure is a bit complex: class ModelHighest(models.Model): name = models.CharField( max_length=120, primary_key=True, unique=True, ) class ModelSecondHighest(models.Model): model_highest = models.ManyToManyField( ModelHighest, default=None, blank=True, ) model_third_highest = models.ManyToManyField( ModelThirdHighest, default=None, blank=True, ) class ModelThirdHighest(models.Model): name = models.CharField(max_length=120) Now inheritance comes into play: class ModelSuper(models.Model): class Meta: abstract = False name = models.CharField( max_length=120, ) class ModelFourthHighest(ModelSuper): third_highest_relation = models.ForeignKey( ModelThirdHighest, on_delete=models.CASCADE, related_name="fourth_highest_objects", ) What I want is a big nested JSON of everything: ├── ModelHighest ├── ModelSecondHighest ├── ModelThirdHighest ├── ModelFourthdHighest I can get until ModelThirdHighest but I can't serialize the last one. My serializers look like this: class FourthHighestSerializer(serializers.ModelSerializer): """...""" class Meta: model = ModelFourthHighest fields = ( "name" ) class ThirdHighestSerializer(serializers.ModelSerializer): """...""" fourth_highest_objects = FourthHighestSerializer(many=True) class Meta: model = ModelThirdHighest fields = ( "name", "fourth_highest_objects", ) class SecondHighestSerializer(serializers.ModelSerializer): """...""" … -
Using sendgrid domain authentication sends email to spam in Django
I am trying to send email from my Django application. For this, I have used Twilio SendGrid service. Though my application can send the email, it ends up in spam folder. So, I have followed this tutorial to authenticate my domain which I bought from AWS route 53. In sendgrid, the domain authentication status shows 'verified' but the emails are still sent to spam folder. I have not created any MX or TXT record in DNS setting as the tutorial says it was created automatically during domain authentication in sendgrid. One thing I have noticed that the email still shows, 'via.sendgrid.net' message (attached an image below) with the email. Whereas it should be my authenticated domain name. I have created sendgrid account with an outlook email and using that address to send email from Django app. Is this the reason my emails are going to spam? Or can anyone please help me to find a solution for this problem? Thanks in advance. FYI: I have done 'Single Sender Verification' in sendgrid during developing this app. But now I have deployed it in aws. I guess this feature is still working instead of 'Domain Authentication'. -
Python Preview Generator FileNotFoundError
I want to generate a thumbnail of attachment uploaded by user, I'm using Python Generator but for some reason I get the following error FileNotFoundError: [Errno 2] No such file or directory: '/media/tenant-2cadb939-306a-43f2-aa53-eb086a4f74b9/AssignedCampaign/2021-2/53676e7d-c95d-4348-a_581e4TM.png' if a.attachment: # get path of attachment without the attachment name cache_path = a.full_path.replace('/'+a.full_path.split('/')[-1], '') + '/preview_cache' log.info('>>>>>>>>>> %s', cache_path) preview_manager = PreviewManager(cache_path, create_folder=True) preview = preview_manager.get_jpeg_preview(a.full_path, width=100, height=200) -
How to refresh cart span or cart div after add product to cart AJAX / Django?
The product is successfully added to the cart but the div containing the cart value is not up to date. You will have to refresh the page so that the div is up to date. I tried the load() and html() methods. How to refresh cart container when I add the product to the cart ? I need a help please. Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> JS Code $(".form-order").on('submit', function(e){ e.preventDefault(); var product_id = $(this).attr('data-id') var quantity = $(this).find("#id_quantite").val() console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', dataType: 'json', data: data, success: function(data){ $("cartval").load(); … -
Django-admin autocomplete of select-box doesn't work
When I send additional context data to admin.site.urls . Autocomplete in select box gives 500 internal server error. My project's urls.py: My select box in admin page: Error page: But whenever I remove context data from urls it works properly. -
How to design database for saving data into table [closed]
By using API calculating Distance between two Zip codes(post codes) But Here is my question. When user loading page always running API is not good coding so, I want to save that into one table and show that data into classifieds page( items listings). So, Here We are calculating distance between logged in user zip code and Ad posted by user Zip code. In classifieds page we have number of ads so, How can I achieve this Can any one help me to achieve this Thank you. -
Pip says it installs mysqlclient successfully, but cannot find it or uninstall it
I am running into the following issue trying to install mysqlclient as part of getting a Django project up and running on an AWS EC2 instance. In a python 3.8.5 virtual environment: (venv3)$ which pip ~/venv3/bin/pip (venv3)$ pip --version pip 21.0.1 from /home/ec2-user/venv3/local/lib/python3.8/dist-packages/pip (python 3.8) (venv3)$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.3-cp38-cp38-linux_x86_64.whl Installing collected packages: mysqlclient Successfully installed mysqlclient-2.0.3 I try running the Django Shell: (venv3)$ python manage.py shell ...full trace stack truncated for brevity... django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? So I tried to find where pip installed it, and it seems to not actually be installed or be a trace of it anywhere: (venv3)$ pip show mysqlclient WARNING: Package(s) not found: mysqlclient (venv3)$ pip freeze | grep -i mysqlclient <nothing> (venv3)$ sudo find / -name mysqlclient <nothing> Then as a sanity check I apparently successfully install it but then pip can't find it to uninstall it: (venv3)$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.3-cp38-cp38-linux_x86_64.whl Installing collected packages: mysqlclient Successfully installed mysqlclient-2.0.3 (venv3)$ pip uninstall mysqlclient WARNING: Package(s) not found: mysqlclient Other things I have tried/verified Making sure python is the 64-bit version Checking pip outside of the virtual environment Nuking the virtual … -
What does it mean attempted relative import beyond top-level package?
Traceback File "", line 5, in <module> from ..books.models import Commen ImportError: attempted relative import beyond top-level package forms.py from ..books.models import Comment Maybe problem in urls.py? There is the structure of my project enter image description here -
Update a model after deleting a row in another model in Django
I have two models UserProfile and ChatUser. ChatUser.models.py class ChatUser(models.Model): chat = models.ForeignKey(ChatRoom,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) UserProfile.models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) phone_number = models.IntegerField(default=0) image = models.ImageField(upload_to='profile_image',blank=True,default='prof1.jpeg') gender = models.CharField(max_length=10) joined = JSONField(null=True) ChatRoom.models class ChatRoom(models.Model): eid = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=100) location = models.CharField(max_length=50) vehicle = models.CharField(max_length=50) brand = models.CharField(max_length=50) max_limit = models.IntegerField() joined in UserProfile is an array consisting room ids of the chatrooms model. Now when I delete a ChatRoom row, it automatically deletes the Foreign Key referenced ChatUser object since I am using on_delete=models.CASCADE. But how to update the joined in UserProfile model. I want to remove the id of the deleted ChatRoom from UserProfile.joined -
Trying to iterate through a dict linked in another dict from a Python API
I am trying to figure out how to get data out of this API endpoint. It is the Sportsipy API. In the Boxscores endpoint it returns a dictionary of a list of games with basic info, one of the values in that dictionary is a list to 'boxscore' which has all the stats from that individual game. When I try dot notation it just returns an error saying the dict has no attribute boxscore. If I try a for loop it says its not iterable. Source Code 'Boxscores' endpoint which then links to the 'boxscore' endpoint. Boxscore Boxscores import requests from django.shortcuts import render from datetime import datetime from sportsipy.ncaab.boxscore import Boxscore from sportsipy.ncaab.boxscore import Boxscores def management(request): games = Boxscores(datetime(2021, 2, 13)) print(games.games) <--- Prints out the dictionary that shows boxscore is there print(games.games.boxscore) <--- Error: dict has no attribute 'boxscore' context = { 'games': games } return render(request, 'management/management.html', context) -
How to order and sort queryset with pagination
I have a bookshop where I would like users to filter the books by their category, and then order the filtered queryset in order of price/most recent etc. I would like to do all of this with pagination too. The issue I have is that whenever I order the filtered queryset, the initial filter is lost. I also lose the filter and ordering when I click the next paginated page, so there are really two issues here. views.py def bookshop_search(request): filter_form = FilterForm() bookresults = Book.objects.all() query_name = '' my_filter = Q() # CATEGORIES FORM if "category" in request.GET: form = CategoryForm(request.GET) if form.is_valid(): queries = form.cleaned_data queries = {k: v for k, v in queries.items() if v is not False} queries = dict.fromkeys(queries, True) query_name = '' for query in queries.keys(): query = '\'' + query.title().replace('_', ' ') + '\', ' query_name += query for query in queries: my_filter |= Q(**{query:queries[query]}) bookresults = Book.objects.filter(my_filter) else: form = CategoryForm() # FILTER FORM if "filter" in request.GET: filter_form = FilterForm(request.GET) if filter_form.is_valid(): if filter_form.cleaned_data['filter_method'] == 'low_to_high': bookresults = Book.objects.filter(my_filter).order_by('price') if filter_form.cleaned_data['filter_method'] == 'high_to_low': bookresults = Book.objects.filter(my_filter).order_by('-price') if filter_form.cleaned_data['filter_method'] == 'recent': bookresults = Book.objects.filter(my_filter).order_by('-pub_date') else: filter_form = FilterForm() # PAGINATION page = … -
headers not being added to aiohttp
Headers aren't being added to aiohttp get/post/put, and I'm very confused The code is like this @classmethod async def http_request(cls, url, message: Message, method, headers={}, **kwargs): headers.update(cls.header) cls.__update_headers(headers, message) async with method(url=url, headers=headers, **kwargs) as response: print(headers) resp = json.loads(await response.text()) resp['status_code'] = response.status if response.status >= 300 and message: await Messages.fail_reply(message, fields=[cls.__handle_errors(resp)]) return None return resp headers being printed is like this {'HTTP_DISCORD_API_KEY': 'token', 'Command_Guild': 'guild', 'Command_User': 'user'} none of the headers are being added and I am very confused.. method is session.get/post/put Django middleware uses the headers with request.headers (I tried adding HTTP_ prefix, and without prefix, both didn't show up on pycharm debug for the headers) PasswordHasher().verify(settings.DISCORD_BOT_HASH, request.headers["DISCORD_API_KEY"]) -
How to invoke table-valued function defined in django
I have created table-valued function instead of stored procedure on database for fetching data on certain condition. How will I invoke that function in django? -
Multiple choice of instances of another model
I have a Car model where one of the properties is horsepower. I also have a Horsepower model. I want my car model to choose from a list of Horsepower instances. class Horsepower(models.Model): title = models.CharField(max_length=255) ... class Car(models.Model): ... horsepower = models.ManyToManyField(Horsepower) I don't want to use ManytoManyField because there should only be one selection. -
How to add related table column in sql to_tsvector?
I am working on a django API in which I need to implement a search-as-you-type feature. At first I wanted to use Django SearchVector and SearchQuery but they seem to perform poorly when query terms are incomplete (which is not ideal for the "as-you-type" part) so I went for the SQL approach. I need to be able to search on first_name and last_name of a contact as well as on the email of the user related to that contact. I used the following to create a search_vector on contact and to add an index on this column. This works great to search on first and last name. ALTER TABLE contact_contact ADD COLUMN search_vector tsvector; UPDATE contact_contact SET search_vector = to_tsvector('english', coalesce(first_name, '') || ' ' || coalesce(last_name, '')); CREATE INDEX mc_idx2 ON contact_contact USING GIN (search_vector); I would like to add the user email to this search_vector, something like: ... SET search_vector = to_tsvector('english', coalesce(first_name, '') || ' ' || coalesce(last_name, '') || coalesce(user.email::text, ''); ... I cannnot figure out the correct syntax or process to do that. Any help is greatly appreciated! -
When i create usercreationform in django the username field is auto selected and how can i fix it
Greeting, I am new in django. Username is auto selected when i reload the page why is this and how can i fix it. -
update_or_create django admin imports
I have an app contains these models class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = .. income_period = .. property_market_rent =.. number_of_family_group = .. cruser = .. prop_id = .. state = .. group =.. class FamilyGroup(models.Model): name = models.CharField(.. transaction =models.ForeignKey(Transaction,.. ... class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, .. family_group = models.ForeignKey(FamilyGroup.. name = models.CharField.. date_of_birth = models.DateField.. .... Im trying to make Imports app that will accept xlsx files with some certain format. after i imported the models from the other apps, therefore i've created a model that have a field for each field i n the above models , i removed a lot so it look readable. im trying to make it update_or_create since i think its the best approach to do, since maybe in future maybe i want to update some fields. I have created the first update_or_create for Transaction but since family_group and family_member are childs of Transaction and Inlines i cant figure out how to apply this. the main idea is i have a transaction contains family_groups and family_members inside it . class Batch(models.Model): batch = models.CharField(max_length=50) transaction_chp_reference = models.CharField(unique=True) transaction_rent_effective_date = models.DateField(.. transaction_property_market_rent = models.DecimalField(.. transaction_number_of_family_group = models.PositiveSmallIntegerField(.. family_group_name = models.CharField(.. family_group_family_type = models.CharField(.. …