Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django routing sending me to the wrong URL
I'm in the process of creating a small poll app with Django and the main page has a button that allows the user to create new polls and another one that allows them to delete polls. My delete route should send the user to a confirmation page that would be located at /polls/:id/delete. When I type it in the URL it works but when I try to access the confirmation page via button click it sends me to the wrong URL. I've tried changing information in the deletePoll class and in the Path but neither work. Any idea what I'm doing wrong? #this is my form on the page: <form action="{% url 'polls:delete' pk=question.id %}"method="GET"> {% csrf_token %} <input class="btn btn-default btn-danger" type="submit"value="Delete"/> </form> #this is my class inside of views.py class PollDelete(DeleteView): template_name = 'polls/delete.html' # can specify success url # url to redirect after sucessfully # deleting object def get_object(request): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/delete.html') #this is my polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ # ex: /polls/ path('', views.IndexView.as_view(), name='index'), # ex: /polls/5/ path('<int:pk>/', views.DetailView.as_view(), name='detail'), # ex: /polls/5/results/ path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, … -
Djanjo Unique Constraint - Upload BUT Skip Duplicates
I have a django unique constraint where im using the django admin site to import .csv files. The constraint is working as expected but I would like to just skip over the duplicates and still add the valid records. Is there a method to get this behavior? -
Django/slite3 manage.py migrate not working after a table has been dropped and re-created
So I'm developing an app & just changing the models a lot. Using SQlite for dev. I create a Product table, played around with it, and needed to do major changes to the fields, and since it's only play data there was no point in keeping that original table. So I did: python manage.py dbshell sqlite> .table auth_group django_admin_log auth_group_permissions django_content_type auth_permission django_migrations auth_user django_session auth_user_groups products_produit auth_user_user_permissions sqlite> DROP TABLE products_produit ...> ; sqlite> .table auth_group auth_user_user_permissions auth_group_permissions django_admin_log auth_permission django_content_type auth_user django_migrations auth_user_groups django_session So the table products.produit is indeed gone. Then I also delete the migration files (e.g. 000X_.py), since they relate to a table I don't have anymore and the model is completely changed. So in that application (products) there is indeed no more migration files under /migration/, only the init.py. Then I updated my model, and re-ran make migrations: Migrations for 'products': products/migrations/0001_initial.py - Create model Produit Process finished with exit code 0 Sounds good there - it created the migration, I open it up & see all the expected fields. However, when I ran migrate, nothing happened: Operations to perform: Apply all migrations: admin, auth, contenttypes, products, sessions Running migrations: No migrations to apply. … -
How this logic of share posts with users in twitter and facebook work in Django
I am winder to know how the logic of retweet in twitter and share in Facebook work how I can let the users share the posts with each other in Django -
Django Filefield paths into javascript variable
I've been struggling with this issue for some time now, I'm trying to get the path of a filefield from my 'Music' model , into a javascript variable , the js is for a music player the variable inside 'trackUrl lists url's for the tracks, I need to grab the django queryset and place it into this variable, the javascript code is in my profile.html page, how could I do this ? , I've thought about using django rest framework, but is this the easiest way of achieving this. Currently inside of the profile.html JS code in the 'trackUrl' variable I have put {{records}}, which is taken from my_profile.views using json.dumps , but this doesn't work. I'm still learning django so could you explain with some detail how I could do this. Thanks profile.html {% extends "feed/layout.html" %} {% load static %} {% block searchform %} <div class="row"> <div class="col-xl-8 col-md-10 m-auto order-xl-2 mb-5 mb-xl-0"> <div class="card card-music"> <h3>MUSIC</h3> <a class="btn btn-secondary track-upload-button" href="{% url 'music-upload' %}">Upload</a> <div id="app-cover"> <div id="bg-artwork"></div> <div id="bg-layer"></div> <div id="player"> <div id="player-track"> <div id="album-name"></div> <div id="track-name"></div> <div id="track-time"> <div id="current-time"></div> <div id="track-length"></div> </div> <div id="s-area"> <div id="ins-time"></div> <div id="s-hover"></div> <div id="seek-bar"></div> </div> </div> <div id="player-content"> … -
Django admin many-to-many witdet - how to extend?
For establishing many-to-many relationships, django admin has a nice widjet called filter_horizontal. The problem is - it only displays primary key of the related table. How do i add other fields from the related table? For example, if I have a many-to-many relationship in my Order model with User model, in Order django admin I can only see User's primary key(id). How do I add their name into the widget? -
How to execute two update statements in one transaction so they won't run into unique constraint in Django ORM?
Given models from django.db import models class RelatedTo(models.Model): pass class Thing(models.Model): n = models.IntegerField() related_to = models.ForeignKey(RelatedTo, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=['n', 'related_to'], name='unique_n_per_related_to' ) ] and >>> r = RelatedTo.objects.create() >>> thing_zero = Thing.objects.create(related_to=r, n=0) >>> thing_one = Thing.objects.create(related_to=r, n=1) I want to switch their numbers (n). In update method of my serializer (drf) I was trying to @transaction.atomic def update(self, instance, validated_data): old_order_no = instance.order_no new_order_no = validated_data['order_no'] Thing.objects.filter( related_to=instance.related_to, n=new_n ).update(n=old_n) return super().update(instance, validated_data) but it still runs into constraint. select_for_update doesn't help either. Is it possible not to run into this DB constraint using Django ORM or do I have to run raw sql to achieve that? Django==3.1.2 postgres:12.5 Error duplicate key value violates unique constraint "unique_n_per_related_to" DETAIL: Key (n, related_to)=(1, 1) already exists. -
Django response giving CORS error for an AJAX request
I'm a beginner in Django and WordPress and I'm making an API request from HTML-Javascript code which is added to my WordPress page. API request was successfully sent and processed in Django-rest-framework backend, but the response is giving me CORS errors Errors on console Access to XMLHttpRequest at 'http://127.0.0.1:8000/videogen/' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. POST http://127.0.0.1:8000/videogen/ net::ERR_FAILED send @ jquery-3.5.1.min.js:2 ajax @ jquery-3.5.1.min.js:2 paraSubmit @ (index):373 onsubmit @ (index):435 XHR failed loading: POST "http://127.0.0.1:8000/videogen/". send @ jquery-3.5.1.min.js:2 ajax @ jquery-3.5.1.min.js:2 paraSubmit @ (index):373 onsubmit @ (index):435 HTML CODE BLOCK IN MY WORDPRESS PAGE <script> function paraSubmit(event){ event.preventDefault(); // creating JSON data to send.. $.ajax({ url : 'http://127.0.0.1:8000/videogen/', type: "POST", crossDomain: true, data: data, dataType : "json", success : function(response){ console.log(response); alert("Video generated and sent!!"); }, error : function(response){ console.log(response); // alert("Video not created" ); } }); } </script> <form onsubmit="paraSubmit(event)" id="paragraph-form" > <input type="text" id="para-name" name="name" placeholder="Name" required/> <input type="text" id="para-email" name="Email" placeholder="Email" required/> <textarea id="paragraph" placeholder="Enter Paragraph here" required></textarea> <button type="submit" class="btn btn-small">Submit</button> </form> settings.py on Django backend CORS_ALLOWED_ORIGIN_REGEXES = [ r"^http://127.0.0.1:[0-9]{1,4}$", r"^https://127.0.0.1:[0-9]{1,4}$" ] The Request is processed and the result is successfully generated on the … -
Iterate over items in array Django serializer
I have the following JSON data: "guests": [ { "id": "1", "title": "Mrs", "last_name": "Helen" }, { "id": "2", "title": "Ms", "last_name": "Susan" } ], Inside my serializer, I have the following array available for me via: guests = request.data['data']['guests'] However, on the response back, I'm trying to return a different format: "idN": "1", "title_N": "Mrs", "last_name_N": "Helen" Which I can do without the editions, via: return Response({data: { 'guests': guests ... What would be the easiest way to target the field changes, even if the array has 100+ items inside? -
How can update user in django
I am trying to update username and email from User model and pic from other model for existing user when i click on save changes but nothing happened View.py class updateUser(TemplateView): template_name = 'changeInfo.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): if 'SESSION_KEY' in request.session: if request.method == 'POST': data = self.request.POST.get users = User.objects.update( request.user, username=data('username'), email=data('email') ) pic = Profile.objects.update( request.user, profile_pic=(request.POST, request.FILES) ) users.save() pic.save() return HttpResponse('done', 200) return redirect('changeInfo') Template {% extends 'home.html' %} {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <p>Change profile </p> <label for="newusername">newusername <input type="text" id="newusername" name="newusername" placeholder="Enter username"> </label> <label for="email">email <input type="email" id="email" name="email" placeholder="Enter email"> </label> <label for="profile_Pic"> <input type="file" alt="pic"> </label> <button type="submit">save changes</button> </form> {% endblock %} -
daphne django nginx - Websockets not correctly upgraded?
We are trying to run our Django setup with both gunicorn and daphne. Daphne for the Websocket handling and gunicorn for normal HTTP requests. We are using graphene for GraphQL and are testing /ws/graphl for subscriptions. The connection to gunicorn works fine. The connection for websockets with daphne doesn't. There are a couple of issues: Daphne is not logging correctly, even though debug is specified we try to log everything into stdout because Docker it is a bit unclear what the issue is with the websocket requests Could the issue be related to not correctly upgrading the http request to websocket? in the nginx access log we only see: 172.29.0.1 - - [02/Mar/2021:15:08:58 +0000] "GET /ws/graphql HTTP/1.1" 500 5 "-" "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Mobile Safari/537.36" The docker container sessions with daphne running does not log anything to stdout apart from some environment variables that are loaded correctly. We can see the correct loading of subscriptions in our GraphiQL testing interface, however executing the subscription leads to the error as seen in the chrome developer tools. We tried moving to unix sockets and share them with docker volume mounts between containers, however … -
How to extend Django model manager for Djongo?
I want to define a model manager for my Django application which uses Djongo to connect Django to MongoDB. I want to define commonly used operations on a model table inside a custom model manager like so class MyManagerQuerySet(models.query.QuerySet): // example queryset def recent(self): return self.order_by("-updated", "-timestamp") ... class MyManager(models.Manager): def get_queryset(self): return MyManagerQuerySet(self.model, using=self._db) def new(self, x, y): ... return created, obj but I also need to be able to use the Djongo manager for making use of the pymongo collection API. How can I modify this "classic" django model manager and queryset to use the djongo manager too? -
Get all users against a permission of group in django
I have created two groups[group_a,group_b] in my django project. I have assigned permission_1 and permission_2 to group_a and group_b respectively. After that, I have assigned users to both groups. Now I want to find all users against permission_1. what will be django model query for this? -
How to call method and pass it to a field from another class model in django?
I am creating an e-commerce web application. I am done with add to cart and currently constructing the cashout views. I am having a problem getting the total amount of price for the ordered item. Models.py class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.OneToOneField(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price def get_final_price(self): return self.get_total_item_price() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) total_price = models.IntegerField(default=0) def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() return total def save(self, *args, **kwargs): self.total_price = self.get_total() return super().save(*args, **kwargs) I tried to override the save function for the Order class to pass through the total amount of price to the total_price fields. I did not get any error message, but the field won't update. It still showing the default value instead of the total amount of price. Views.py class OrderSummaryView(LoginRequiredMixin, DetailView): def get(self, request, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'ecommpage/order_summary.html', context) except ObjectDoesNotExist: messages.error(self.request, "You do not have an active order") return … -
Cannot install apache-airflow-providers-mysql==1.0.0 and apache-airflow-providers-mysql==1.0.1 package versions have conflicting dependencies
I am trying to install apache-airflow-providers-mysql I have use the following command pip install apache-airflow-providers-mysql But I a, getting an error like this -
Django-mptt just works with recursion relation?
Guys I using the Django-mptt package to create hierarchies questions, I have a problem with it, should I write my model relation as recursion? or It works with other tree structures?? -
The current path, accounts/login/", didn't match any of these
i am working on blog project and almost done. but this bug in 'login' driving me crazy and cant debug it. I am getting this traceback, when I'm trying to access my project (local): Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='post_list'] about/ [name='about'] post/<int:pk> [name='post_detail'] post/new/ [name='post_new'] post/<int:pk>/edit [name='post_edit'] post/<int:pk>/remove [name='post_remove'] post/<int:pk>/publish/ [name='post_publish'] drafts/ [name='post_draft_list'] post/<int:pk>/comment/ [name='add_comment_to_post'] comment/<int:pk>/approve/ [name='comment_approve'] comment/<int:pk>/remove/ [name='comment_remove'] accounts/login/ [name='login'] accounts/logout/ [name='logout'] The current path, accounts/login/", didn't match any of these. Main/urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth import views from django.contrib.auth.views import LoginView urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('accounts/login/', views.LoginView.as_view(), name='login'), path('accounts/logout/', views.LogoutView.as_view(), name='logout', kwargs={'next_page':'/'}), ] project/urls.py from django.urls import path from blog import views urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), path('post/<int:pk>',views.PostDetailView.as_view(),name='post_detail'), path('post/new/',views.CreatePostView.as_view(),name='post_new'), path('post/<int:pk>/edit',views.PostUpdateView.as_view(),name='post_edit'), path('post/<int:pk>/remove',views.PostDeleteView.as_view(),name='post_remove'), path('post/<int:pk>/publish/',views.post_publish,name='post_publish'), path('drafts/',views.DraftListView.as_view(),name='post_draft_list'), path('post/<int:pk>/comment/',views.add_comment_to_post,name='add_comment_to_post'), path('comment/<int:pk>/approve/',views.comment_approve,name='comment_approve'), path('comment/<int:pk>/remove/',views.comment_remove,name='comment_remove'), ] settings.py import os ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES … -
displaying django admin instead of my html
I am trying to do a password change in Django. The problem is that instead of my html template, it uses Django admin. How do I make my template go over, and not the admin? urlpatterns = [ path('', index, name='index'), path('registration/', registration, name='registration'), path('accounts/', include('django.contrib.auth.urls'), name='login'), path('accounts/', include('django.contrib.auth.urls'), name='logout'), path('accounts/password_reset/', PasswordChangeView.as_view(template_name="password_change.html"), name='password_reset'), ] enter image description here -
Deployment script to apache, permissions problem
I'm developing a Django application that is being deployed to an apache server. I'm using two servers right now. In one server I have the Development and Staging instances for which I use a bash shell script to deploy, and in the other server the Production instance in which I use a mina-deploy script. The problem comes after deploying since the permissions on the /var/www/... folder are not correct after the deployment, this wont allow apache to serve the website. I was wondering if there is anyway I can deploy this code without making any change to permissions. For both I'm not using a root user but an user with SUDO permissions. -
Django Rest Framework not updating ImageField with UpdateAPIView
All other fields are being correctly updated except the ImageField which also does not throw any errors. In the database I can see the image URL being updated, but on the file system there is no changes to the media/ folder. When I use the model with admin.site.register everything works perfectly (hence I should have properly configured MEDIA_ROOT and MEDIA_URL) and I see file uploaded in the media folder. views.py class ProfileView(generics.UpdateAPIView, generics.RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def put(self, request): print(request.data) print(request.FILES) p = Profile.objects.get(user=request.user) serializer = ProfileSerializer(p) serializer.update(p, request.data, request.user) return Response(serializer.data) def get(self, request): p = Profile.objects.get(user=request.user) serializer = ProfileSerializer(p) return Response(serializer.data) models.py class ProfileView(generics.UpdateAPIView, generics.RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def put(self, request): print(request.data) print(request.FILES) p = Profile.objects.get(user=request.user) serializer = ProfileSerializer(p) serializer.update(p, request.data, request.user) return Response(serializer.data) def get(self, request): p = Profile.objects.get(user=request.user) serializer = ProfileSerializer(p) return Response(serializer.data) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('firstName', 'lastName', 'dob', 'desc', 'gender', 'image', ) #TODO: write validators def update(self, instance, validated_data, user): p = Profile.objects.filter(user=user) p.update( firstName=validated_data['firstName'], lastName=validated_data['lastName'], dob=validated_data['dob'], gender=validated_data['gender'], image=validated_data['image'], ) -
How to set log files to have write access to apache while creation of the log file from a python file?
I have a python file on my backend that does some tasks and has to create and write to .log file for debugging purposes, for each individual post request by the user. The files are being created, but the code is not being able to write to that file, and the file does not inherit the permissions of the parent folder while creation. How can I fix this? -
Electron Problem runing manage.py runserver
I'm developing a web app, but just yesterday when i try to run manage.py wiht runserver appeared to me this error "(electron) Sending uncompressed crash reports is deprecated and will be removed in a future version of Electron. Set { compress: true } to opt-in to the new behavior. Crash reports will be uploaded gzipped, which most crash reporting servers support." I don't know why appear, I don't changue nothing, I only tunr off my computer. Can anyone help me whit this? Problem Image -
Django elasticsearch filtering and ordering
I'm pretty new to elastic search and couldn't find what I want in documentation. I have a following model class Fruit(Model): name = CharField() description = TextField() And user wants to search apple grows. How to make a query that filter records that have all terms in either of fields? For example apple in title and grows in title works, apple in title and grows in description works How to perform contains query? For example, if person queries appl, it should give a title Green Apple. Is elasticsearch smart enough for queries like applegrows (I mean can it split)? How to order by relevance? For example, first results that have all terms in title, then in description, then in either. I read about multi_search, but without any success: Document.search().filter("multi_match", query='apple grows', fields=['title', 'description']) -
Django REST: ViewSet custom dictionary
My goal is to retrieve a dictionary where the key is the id of a target group object, and the value is the corresponding target group object. Additionally I want a custom field "enabled" which represents whether the target_group is paired to the given category (cat_id). The url would be for example: http://localhost:8000/api/ctg/?cat_id=61 Example of resulting dictionary: { 1: { id: 1, name: "target group name", employer: 175, enabled: false, }, 5: { id: 5, name: "another target group name", employer: 175, enabled: true, }, ... } The way I do it currently: I first retrieve all target groups for an employer (user). I retrieve the target groups which are connected to the given category id. Programmatically I make a dict which results in the above example, but obviously this is very very inefficient. If possible I would like to retrieve the dictionary which I can use right away in my front end, could someone point me in the right direction as to how to achieve this? ViewSets: # get all target groups class TargetGroupViewset(viewsets.ModelViewSet): queryset = TargetGroup.objects.all() serializer_class = TargetGroupSerializer def list(self, request): queryset = TargetGroup.objects.filter(employer=self.request.user.pk) serializer = TargetGroupSerializer(queryset, many=True) return Response(serializer.data) # get target groups which are connected … -
TypeError at /api/products/1 save() missing 1 required positional argument: 'self'
So I'm trying to make rest API using django rest framework, I want to make it so that when I make a patch request, I can update the model or objects but when I try to do that, I get TypeError at /api/products/1 save() missing 1 required positional argument: 'self' error views.py class DetailView(APIView): def get(self, request, id ,format=None): product = get_object_or_404(Product, pk=id) serializer = ProductSerializer(product) return Response(serializer.data) def patch(self, request, id, format=None): product = get_object_or_404(Product, pk=id) serializer = ProductSerializer(Product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)