Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to perform multiple table join with Django?
I have a table like this: ID Parent_ID Name Geo 1 Null City A ABC1 12 1 District 1 ABC002 123 12 Ward 1 ABC002003 2 Null City B XYZ2 25 2 District 5 XYZ004 251 25 Ward 4 XYZ002006 Normally, I got the ID of the ward (third in the hierarchical). I need to to do query to get the GEO of the city (first in the herarchical). In query (PostgreSQL), I would do something like this : SELECT l1.Geo FROM routing.r_location l1 JOIN routing.r_location l2 ON l1.ID= l2.Parent_ID JOIN routing.r_location l3 ON l2.ID= l3.Parent_ID WHERE l3.ID= '123' Since, I am beginner with Django, I literally dont know how to do complex join table like this. Please help -
Django how to log loge page with id
I am new to Django and tried existing answers but did not work for me. I would appreciate your help! I can easily get to the general page when I enter the site, but how do I go to my profile when I log in? def login(request, pk=0): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) try: remember = request.POST['remember_me'] if remember: settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False except: is_private = False settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request, 'invalid credentials') return redirect('login') else: return render(request, 'registration/login.html') urls.py path('profile/<int:pk>/', views.profiles, name='profile'), -
Only friends posts are not showing
I am building a BlogPost Webapp, AND i am stuck on an Error. views.py def friends_posts(request,user_id): posts = Post.objects.filter(post_owner=user_id) profiles = get_object_or_404(Profile,user_id=user_id) p = request.user.profile you = p.user friends = p.friends.all() context = {'posts':posts,'profiles':profiles,'friends':friends} return render(request, 'friends_posts.html', context) urls.py path('friends_posts/<int:user_id>/',views.friends_posts,name='friends_posts'), friends_posts.html {% for user_p in friends %} {{ user_p.friends.posts.all }} {% endfor %} The Problem friends_posts page is not showing Friends post. It is showing all the information of friends but NOT showing the posts of friends. What i am trying to do I am trying to show all the posts of friends of request.user. I don't know what to do. Any help would be appreciated. Thank You in Advance. -
Pytest django url's tests
I saw some people writing url's test like this: def test_sample_url(): path = reverse('url_name', kwargs={'pk': 1}) assert resolve(path).view_name == 'url_name' As for me this test is not checking anything, because if I place 'url_name' in second line then in third it is obviously going to be equal to it. Am I wrong or missing something? -
How to hide certain json data from passing through if it doesn't meet a condition in Django rest framework?
Hello all I want to hide certain json data from passing through if it doesn't meet a condition in django rest framework, like I have a comment model and serializer, and I don't want the replies to pass through as comments since I have another field for replies which is nested along with the respective comments. These are the serializers: class CommentCreateSerializer(serializers.ModelSerializer): content = serializers.CharField() reply_id = serializers.PrimaryKeyRelatedField(source='reply',queryset=Comment.objects.all(), write_only=True, required=False) user = serializers.ReadOnlyField(source="user.username") class Meta: model = Comment fields = ['id', 'user', 'content', 'reply_id', 'timestamp'] class CommentSerializer(serializers.ModelSerializer): content = serializers.CharField() reply_id = serializers.PrimaryKeyRelatedField(source='reply',queryset=Comment.objects.all(), required=False) user = serializers.ReadOnlyField(source="user.username") replies = CommentCreateSerializer(many=True, read_only=True) class Meta: model = Comment fields = ['id', 'user', 'content', 'replies', 'reply_id', 'timestamp'] This is the json response: "count": 5, "next": null, "previous": null, "results": [ { "id": 2, "user": "testuser2", "content": "comment test!", "replies": [ { "id": 3, "user": "testuser3", "content": "ding", "timestamp": "2021-02-09T15:29:38.230933+01:00" } ], "reply_id": null, "timestamp": "2021-02-09T15:24:11.072502+01:00" }, { "id": 6, "user": "testuser2", "content": "Testing again", "replies": [], "reply_id": null, "timestamp": "2021-02-09T17:33:59.227425+01:00" }, { "id": 5, "user": "testuser2", "content": "Testing", "replies": [], "reply_id": null, "timestamp": "2021-02-09T17:28:41.992143+01:00" }, { "id": 3, "user": "testuser3", "content": "ding", "replies": [], "reply_id": 2, "timestamp": "2021-02-09T15:29:38.230933+01:00" }, { "id": 4, "user": … -
Strange error NameError: name '_mysql' is not defined on VSCode
I'm trying to using mysqlclient==2.0.3 for Django==1.11.17 and I am receiving this error when trying to start python manage.py runserver. The error is really strange because on macOS's terminal the commands works and everything is fine while the error appears only when using the same command from VSCode shell. In both I'm using zsh -
How to pass variable from Python API to Django template
I have been trying to work with this Python sports data api, Sportsipy. It’s pretty simple to set up and I can save data to a var and print it to the terminal but when I add it to context go to pass it through my Django template nothing shows up. I tried calling it on the HTML side several different ways but I still haven't been able to figure it out. Screenshot of API endpoint doc def games(request): """ View to return games page """ team_schedule = Schedule('PURDUE') print(team_schedule) for game in team_schedule: away_total_rebounds = game.boxscore.away_total_rebounds print(away_total_rebounds) context = { 'team_schedule': team_schedule, 'away_total_rebounds': away_total_rebounds, } return render(request, 'games/games.html', context) {% for rebound in away_total_rebounds %} <div> <h4 class="white">{{ rebound.away_total_rebounds }}</h4> </div> {% endfor %} -
Django foreign key rest framework
Is there any way to display the name of the user in the "likedBy" section of the view, instead of the user id? Using django rest framework From view I get , ignore comments [ { "id": 3, "title": "ddsa", "content": "dsadsa", "created": "2021-02-10T08:07:42.758400Z", "updated": "2021-02-10T08:07:42.758400Z", "author": 1, "category": [ { "pk": 1, "name": "Life" } ], "likedBy": [ 1 ], "comments": [ { "id": 2, "content": "ghfa", "created": "2021-02-10T08:08:02.407950Z", "post": 3, "author": 1, "likedBy": [ 1 ] } ] } ] Views.py class PostViewSet(FlexFieldsMixin, generics.ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer permit_list_expands = ['category', 'comments'] Models.py class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() category = models.ManyToManyField(Category, related_name='posts') author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) likedBy = models.ManyToManyField(User, related_name='posts', blank=True) class Meta: ordering = ['-created'] Serializers.py class PostSerializer(FlexFieldsModelSerializer): class Meta: model = Post fields = '__all__' expandable_fields = { 'category': ('blogApi.CategorySerializer', {'many': True}), 'comments': ('blogApi.CommentSerializer', {'many': True}), } Any ideas ?????????????????????????????????????????????????????????????????? -
"unhashable type: 'dict'" on saving data to JSONField
I am trying to create an instance to a model named A having a JSONField .but getting an error ` "unhashable type: 'dict'". sample_data = {"name":"test", "countries":[1,2,3]} models.py from django.db.models import JSONField class A(models.Model): name = models.CharField(max_length=100) countries = JSONField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py class AViewSet(viewsets.ModelViewSet): queryset = A.objects.all() pagination_class = StandardResultsSetPagination permission_classes = (IsAuthenticated,) http_method_names = ['get', 'post', 'put', 'delete'] filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ['name'] def create(self, request, *args, **kwargs): serializer = ASerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(APIResponseParser("success", data=self.request.data), status=status.HTTP_200_OK) serializers.py class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = '__all__' Don't know what is wrong...please help -
Modeling and query on many to many models with through
I thought about using the custom through to record the comments that users makes on objects and record the date in addition to the comment text. I tried to build this model but I think it's wrong. It's my first time with M2M rel. class Category(models.Model): name = models.CharField(max_length=30) class Obj(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) desc = models.CharField(max_length=200) name = models.CharField(max_length=64) class User(models.Model): name = models.CharField(max_length=64) comment = models.ManyToManyField(Obj, through='Comments') class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) obj = models.ForeignKey(Obj, on_delete=models.CASCADE) data = models.DateTimeField() text = models.CharField(max_length=500) I would like to make queries based on the object id that can get any comments made on that item, the username and date for each of them. Also doing this query qs=Comments.objects.all() returns empty queryset -
In Django is it possible to send data from a view to itself when a page is refreshed
Is there a way to know which buttons are pressed in a page when returning to a view in Django? I am trying to implement a filter on a list of values in a Django app. The page has a list of checkboxes and 3 buttons to decide which values to show in the list. For example: a list will consist of values: db-productA-1, db-productA-2, db-productB-1, db-productB-2 and db-productC-1, db-productC-2 and the buttons will be: ProductA, ProductB, ProductC When the page is loaded for the 1st time, all buttons are un-pressed and all 6 dbs are listed. I then press button ProductA to filter the list. Pressing the button runs the view and I want to know which buttons were pressed, so I can decide which values to list. If I continue and press ProductB, I'd like to know that both buttons were pressed. Is there a way to retrieve the state of the elements in the page in Django? -
Django login.html and base_generic.html locations
According to: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication and https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Home_page the base_generic.html file should be included in /locallibrary/catalog/templates/ (inside the application folder), but the login.html file should be included in /locallibrary/templates/registration/ (at project root directory level) The login.html use the base_generic.html to extend its code. It is strange (from my beginner point of view), to have the templates base folder "more inside" than the login one. What if we had other applications with different base files? Which base file would the login registration file extend in that case? locallibrary/ # Website folder manage.py # Script to run Django tools for this project (created using django-admin) locallibrary/ # Website/project folder (created using django-admin) catalog/ # Application folder (created using manage.py) templates/ # Application templates folder base_generic.html templates/ # Templates folder registration/ # Registration folder login.html -
Uploading large files using Django and Ajax
I am trying to upload two files (tableFile, and zipFile) in Django using ajax POST. This code works when the zipfile is small. But I need to upload a large zipFile (about 10 GB). Is this possible? As you see I have added enctype="multipart/form-data" to the form, but this does not work. I also tried to define the following parameters in the settings.py DATA_UPLOAD_MAX_MEMORY_SIZE = 9450908240 FILE_UPLOAD_MAX_MEMORY_SIZE = 9450908240 But this also does not work. I get the following error invalid form <ul class="errorlist"><li>zipFile<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Below is my code models.py class Project(models.Model): id = models.AutoField(primary_key=True) from django.core.files.storage import FileSystemStorage from django.conf import settings upload_storage = FileSystemStorage(location=settings.FS_IMAGE_UPLOADS, base_url=settings.FS_IMAGE_URL) # files tableFile = models.FileField(upload_to="..", storage=upload_storage, blank=True, null=True) zipFile = models.FileField(upload_to="..", storage=upload_storage,) forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project fields = [ "id", "tableFile", "zipFile", ] views.py from django.views.decorators.csrf import csrf_protect, csrf_exempt #@csrf_protect @csrf_exempt def CreateProject(request): if request.method == "POST": form = ProjectForm(request.POST, request.FILES) if form.is_valid(): print ('valid form') else: print ('invalid form') print(form.errors) return render(request, "create_project.html", {}) return render(request, "create_project.html", context) html <form id ="form_id" method="post" enctype="multipart/form-data"> {% csrf_token %} <table id="image_list_table" class="table table-condensed"> <tr> <th>tableFile</th> <td><input type="file" id="tableFile" name="tableFile" required /> </td> </tr> <tr> <th>zipFile</th> <td> <input … -
TypeError: static() got an unexpected keyword argument 'document_root' in Django
After review questions before mine and apply changes Im keep receiving this error, as below. I tried to change all recomendations but it doesn't work anyway. I have not issue to recover static images, the problem comes when I attempt catch dinamic image from database. TypeError: static() got an unexpected keyword argument 'document_root' setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static #from django.utils.text import slugify from django.contrib.auth.models import User from django.shortcuts import render from backoffice.views.section import * from backoffice.views.user import * import backoffice.views.home import frontoffice.views urlpatterns = [ path('admin/', admin.site.urls), path('backoffice/', backoffice.views.home.management, name="backoffice"), # all list area path('backoffice/all_sections', SectionListView.as_view(), name="all_section"), path('backoffice/all_users', UserListView.as_view(), name="all_users"), # all frontoffice area path('', frontoffice.views.home, name="home"), path('about/', frontoffice.views.about, name="about"), path('contact/', frontoffice.views.contact, name="contact"), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model class Profile(models.Model): """ Model Profile extending funcionalities from our user model""" user = models.OneToOneField(User, on_delete=models.CASCADE) section = models.ForeignKey(Section, on_delete=models.CASCADE) ceo = models.BooleanField() employee = models.BooleanField() seller = models.BooleanField() guess = models.BooleanField(default=True) photouser = models.ImageField( upload_to='backoffice/static/avatars', default='backoffice/static/avatars/', blank=True, null=True ) cargo = models.CharField(max_length=100) notas = models.TextField(blank=True) def __str__(self): """Returning username.""" return self.user.username html … -
ChainedManyToManyField not working properly in django
I am trying to make dependent drop down in django admin page for models : class ItemCode(models.Model): **Name=models.CharField(max_length=50,blank=True,null=True)** def __str__(self): return self.Name class Vendor(models.Model): first_name = models.CharField(_('first name'), max_length=150, blank=False) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), blank=False) PhoneNo=models.CharField(_('Phone No'),max_length=150, blank=False) # new **Item=models.ForeignKey(ItemCode,on_delete=models.CASCADE,verbose_name="Item** Code",blank=True,null=True) class Offer(models.Model): Auction_id=models.CharField(max_length=20,blank=False,null=False,verbose_name = "Auction ID") Item=models.ForeignKey(ItemCode, on_delete=models.CASCADE,blank=True,null=True,unique=False,related_name='itemcode') Vendor = ChainedManyToManyField( Ven, chained_field="Item", chained_model_field="Name") But Vendor is showing all the vendor instead of filtering Vendor list as per Item.Please help! -
How to add(set) the ES6 59 atom editor? W104 - 'let' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz)
enter image description here How to add(set) the ES6 59 atom editor? -
Django parsing json (from Webhooks)
I am trying to parse some json received from Mailchimp to a Webhook in my Django application. The format will look like this: { "type": "subscribe", "fired_at": "2009-03-26 21:35:57", "data": { "id": "8a25ff1d98", "list_id": "a6b5da1054", "email": "api@mailchimp.com", "email_type": "html", "ip_opt": "10.20.10.30", "ip_signup": "10.20.10.30", "merges": { "EMAIL": "api@mailchimp.com", "FNAME": "Mailchimp", "LNAME": "API", "INTERESTS": "Group1,Group2" } } } I have tried the following: def marketing_email_handler(request): if request.method == 'POST': reqtype = request.body['type'] reqdata = request.body['data'] reqemail = request.body['data']['email'] I received the error 'byte indices must be integers'. I've tried changing this to the below, however this results in an error 'TypeError: 'int' object is not subscriptable'. And doing request.json() also results in an error reqtype = request.body[0]['type'] reqdata = request.body[0]['data'] reqemail = request.body[0]['data']['email'] -
NoReverseMatch at / Reverse for 'singlepropa' with arguments '('mens-shirt-1',)' not found. 1 pattern(s) tried
I am trying to pass 2 parameters from html tag to the urls in django. But I am getting error: NoReverseMatch. If I pass only one parameter then it is working fine but it is generating error whenever i am passing 2 parameters. I have read the documentation for this but I am not clear about that,,and I have also searched for this issues. But nothing is working. Can You please help me to figure it out how I can I fix this? My href in html tag is: <a href='{% url "update_cart" product.slug qty=10 %}' class="float-right">Add to Cart</a> My urls.py is: urlpatterns = [ path('', home.Index.as_view(), name='homepage'), path('signup', signup.SignUp.as_view(), name="signup"), path('login', login.Login.as_view(), name="login"), path('logout', login.logout , name="logout"), path('basket', basket.Basket.as_view() , name="basket"), path('singlepropa/<str:slug>/<int:qty>', singlepropa.SinglePropa.as_view() , name="singlepropa"), path('s/', search.Search.as_view() , name="search"), path('update_cart/<str:slug>', basket.update_cart , name="update_cart"), ] The method for the mapped url is: from django.shortcuts import render, redirect, HttpResponseRedirect from django.views import View from MStore.models.cartModel import Cart, CartItem from MStore.models.productModel import ProductModel from django.urls import reverse # login class class Basket(View): def get(self, request): try: the_id = request.session["cart_id"] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {'cart': cart} else: empty_msg = "Your Cart is empty. Please keep shopping!" … -
Using models / queryset to generate questionnaire or django-survey
I am assuming I won't be the first one to ask this or a similair question, however I do think an answer on this question could help multiple people. the idea: create an online portal (django backend, js frontend, incl rest-framework API). As I would like this app to be accesible by other companies and also to communicate via API with other endpoints, I started to create several models, mapped them, etc. the question: what would be the best way (memory/deployment/security) to include a questionnaire in the front end (keeping in mind the requirements)? To be more specific, should i create a userform and map these directly to the API, or can i use something as https://github.com/Pierre-Sassoulas/django-survey? Does anyone has experience with such sort of apps hosted on github? It seems that packages like this make use of the admin panel and therefore I would probably need to map these which would be an extra step from my view. Feel free to bring up any other points of attention or your own questions. -
How to get the value of Queryset in Django
How to get this value covid_id and convert it to list? in QuerySet? <QuerySet [{'covid_id': 1653718671360'},{'covid_id': '1624728932475'}]> Expected output ['1653718671360','1624728932475'] sample sample= Person.objects.filter(pk__in=product_ids).values('covid_id') #output<QuerySet [{'covid_id': 1653718671360'},{'covid_id': '1624728932475'}]> print(sample) -
Can anybody please explain why I am facing this error [closed]
C:\Users\Najeebullah Tahir\PycharmProjects\PyShop>PyShop $django-admin startproject pyshop. 'PyShop' is not recognized as an internal or external command, operable program or batch file. -
unable want to check length of list, i want to check list length greater than 0 than loop over it and render each element
Trying to loop over a list , and then show each element of that list in span element, but its not working first I want to check if length of that list is greater than 0 than loop over the list , I am not familiar with syntax , need help . code: {%if len(prediction)>0%} {%for predict in prediction%} <span>{{predict}}</span> {% endfor %} -
Django Order QuerySet by Min Value from Child Table
I am trying to create a specific complex query in Django that I am struggling with. I am using pagination to display a list of cakes on the index page. I want to sort them by different attributes. Below is a screenshot of my index page. Name (A-Z) & Name (Z-A) are implemented by simply ordering the Cake queryset by 'name' or '-name' which I am getting as POST from the form at the top of the page. cakes_list = Cake.objects.all().order_by('name') However I am struggling to order the queryset by minimum price. Each cake is available in different dimensions which have different prices (dimensions and prices between cakes are different). These are stored in Dimension with a foreign key pointing to the Cake they belong to. I want to find out the cheapest option for each cake and order my list of cakes that is used in the pagination based on that (both min price asc and desc). I have also created a method from_price which returns the price of that cake. Which I use in my template to display each cake name together with the minimum price. But I cannot seem to be able to implement that into my … -
MultipleChoiceField only with choices, not with ManyToManyField
I have a problem with a MultipleChoiceField, I can not save it. Model: class Companyd(models.Model): months_recurrence_options = ( ("1", "Enero"), ("2", "Febrero"), ("3", "Marzo"), ("4", "Abril"), ("5", "Mayo"), ("6", "Junio"), ("7", "Julio"), ("8", "Julio"), ("9", "Septiembre"), ("10", "Octubre"), ("11", "Noviembre"), ("12", "Diciembre") ) months_recurrence=models.CharField(max_length=100,choices=months_recurrence_options, blank=True,null=True) Forms: class CompanyFormAdmin(forms.ModelForm): months_recurrence = forms.MultipleChoiceField(required=False,widget=forms.CheckboxSelectMultiple, choices=Company.months_recurrence_options) class Meta: model = Company fields = [... months_recurrence ... ] Views form = CompanyFormAdmin(request.POST or None, request.FILES or None, instance=obj) if request.method == 'POST': if form.is_valid(): form.save() When I save the form, I have this problem: {'months_recurrence': [ValidationError(["Escoja una opción válida. ['5', '7', '10'] no es una de las opciones disponibles."])]} -
while using dependency dropdown list in django the correct list is displayed only when save button is hit
I am new to Django. Tried with the example mentioned in the below link for getting dependency dropdown. But I am not sure where i am wrong the correct dropdown is getting loaded after hitting the save button. https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html Could you please help me in resolving this. Regards, Sindhu Sumukha