Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change FileField in Django Model
I want to update the pre-created model field which is FileField; this file is stored in the server, not in request.FILES. My Model config is: class File(models.Model): fileID = models.AutoField(primary_key=True) apkToolFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APKTOOL_DIR_BASE')))) apkFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APK_DIR_BASE')))) appPackage = models.CharField(null=True, max_length=30) appName = models.CharField(null=True, max_length=30) appIcon = models.FileField(upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APP_ICON_DIR'))),null=True) appVersion = models.CharField(null=True, max_length=20) hashFile = models.CharField(null=True,max_length=64) jadxFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'JADX_DIR_BASE')))) def __str__(self): return "FileName: {apkFile} - HashFile: {hashFile}".format( apkFile = self.apkFile, hashFile=self.hashFile ) And my Model serilazer is: from rest_framework import serializers from .models import File class FileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = File fields = [ 'fileID', 'apkToolFile', 'apkFile', 'appPackage', 'appName', 'appIcon', 'appVersion', 'hashFile', 'jadxFile' ] I want to update appIcon with the file which is stored in the server storage. How can i do this? Tank you -
FATAL: password authentication failed for user "siteadmin"
I am trying to run python manage.py makemigrations to initiliaze the data fields in my database, but I keep getting this error. Siteadmin is the user on my server, not even a user on my postgres database. I am trying to use the user "dbadmin" to create these datafields. local_settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cramnation_prod', 'User': 'dbadmin', 'PASSWORD': 'abc123!', 'HOST': 'localhost', } } Dbadmin is a user in my postgres with sudo privileges and I have made sure that the passwords match. Why is it trying to use the name of my server user "siteadmin" instead of my postgres user "dbadmin"? -
User ModelForm not getting saved in database (Django)
I have a ModelForm that creates an instance of a custom user (AbstractUser model). Whenever I try to submit the form, nothing happens except a reload of the page (because of the action), and nothing is getting saved in the database. The code is as following: def sign_up(request): if request.method == 'POST': print("test") form = UserForm(request.POST) if form.is_valid(): form.save() data = form.cleaned_data user = authenticate( username=data['username'], password=data['password'] ) user_login(request, user) else: form = UserForm() return render(request, 'schedules/signup/signup.html', {'form':form}) class ClientUser(AbstractUser): classes = models.ManyToManyField(ScheduleClass) personal_changes = models.TextField(name="personal_changes", default="none") schedule = models.ManyToManyField(Schedule) def get_classes(self): return self.classes class UserForm(forms.ModelForm): class Meta: model = ClientUser fields = ['username', 'password', 'classes', 'schedule'] <form method="post" action="http://127.0.0.1:8000/"> {% csrf_token %} {{ form }} <input type="submit"> </form> For some reason, it's also not even printing the line I wrote on line 3 of the sign_up func, even when I post. Is there something I am doing wrong? -
How to use Django's session engine with subdomains?
I need to access a user's sessionid from within a subdomain on my site, so I can enable "single sign-on", but I can't seem to get it to work, despite changing SESSION_COOKIE_DOMAIN = '.localtest' in my settings. MRE You need to modify /etc/hosts to include localtest if you want to reproduce the error. Also note that this is only tested on macOS, so YMMV. urls.py: from django.contrib.auth import views from django.contrib.auth.decorators import login_required from django.urls import path @login_required def home_view(request): raise Exception('user was logged in') urlpatterns = [ path('login', views.LoginView.as_view(), name='login'), path('home', home_view, name='home'), ] settings.py: BASE_DOMAIN = 'localtest' SESSION_COOKIE_DOMAIN = '.' + BASE_DOMAIN LOGIN_URL = '/login' LOGIN_REDIRECT_URL = '/home' When I attempt to log a user in via the builtin LoginView, the login is successful, and the user is redirected to /home (which is on the same domain as the login). After the login redirect, the user's session gets dropped, and the login_required triggers, sending the user back to the login page. Why is this happening? Is this a bug, or am I missing something? If you want to reproduce this on your machine, here is a repo. The database has a test user set with the username root … -
How to create score from multiple choice site using Django, and then allow user to see their current/progressive score?
to programming and Django here. I'm creating a multiple choice quiz using Python and would like to calculate and keep track of the score. Also the user should be able view their current score from one question to the next (.html). Score to add 10 points for each correct answer selected. Total 10 questions, with each multiple choice question having 4 choices. What would be the best way to go about this? -
Django: Pass paramter to view funciton, but not in url
What I'm trying to do is allow my login page to be told whether to show an alert by through reverse without using the url from a redirect from another view function. My login view function looks like: def login(request, alert=False): ... context = generate_basic_context(request) if (alert): context['alert'] = { 'type': 'danger', 'text': 'You need to be logged in to do that!' } return render(request, 'login.html', context) My urls.py: urlpatterns = [ ... path('login/', views.login, {'alert': False}, name='login'), ... ] And my reverse (function is called from other view functions): def makeauthenticate(): return HttpResponseRedirect(reverse('login', kwargs={'alert': True'})) Error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' with keyword arguments '{'alert': True}' not found. 1 pattern(s) tried: ['dashboard/login/$'] -
Things don't appear to be working at the moment. Please try again later. django-paystack
Im am getting this error; "Things don't appear to be working at the moment. Please try again later." It might be configuration settings but so far I don't what I'm missing, the documentation specifies 2 settings. django-paystack settings; I added the sendbox business email generated by paypal to PAYPAL_RECEIVER_EMAIL but I get the above error. PAYPAL_TEST = True PAYPAL_RECEIVER_EMAIL = '' Here is the views I'm testing out with. def process_payment(request): paypal_dict = { "cmd": "_xclick-subscriptions", "business": settings.PAYPAL_RECEIVER_EMAIL, "amount": "10000000.00", "item_name": "name of the item", "invoice": "unique-invoice-id", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('user_profile:success')), "cancel_return": request.build_absolute_uri(reverse('user_profile:cancelled')), # noqa "custom": "premium_plan", form = PayPalPaymentsForm(initial=paypal_dict, button_type="subscribe") return render(request, 'user_profile/process_payment.html', {'form': form}) } -
Django Formset - Update Value in Views.py before saving
I am trying to set a value on each form in the formset to a single value. I am not sure how to accomplish this... views.py function below: def customer_contacts(request, id): ContactFormSet = modelformset_factory(AppContactCnt, can_delete=True, fields=( 'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt'), max_num=3, extra=3) formset = ContactFormSet(queryset=AppContactCnt.objects.filter(idcst_cnt=id), prefix='contact') if request.method == 'GET': context = {'formset': formset} return render(request, 'customer_contacts.html', context=context) if request.method == 'POST': formset = ContactFormSet(request.POST, prefix='contact') if formset.is_valid(): print("we're updating contacts for " + str(id)) # formset.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Display django registration form errors
I want to display registration errors when the user is trying to register but he does somthing wrong like typing an existing email address or the two passwords don't match or when one of the django's default password validator is not considred like typing a short password, and be able to style each error with bootstrap alert as i'm showing below in the template the user model in models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.conf import settings class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email",max_length=250, unique=True) username = models.CharField(max_length=30, unique=True, null=True) date_joined = models.DateTimeField(verbose_name='Date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='Last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) full_name = models.CharField(verbose_name="Full name", max_length=150, null=True) profile_pic = models.ImageField(null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = MyAccountManager() def __str__(self): return self.full_name # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): return True the view that has the sign up/registration form in views.py def home(request): user = request.user # for rendring texts form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): obj = form.save(commit=False) author … -
Breaking Sting data into multiple display columns with Django
I have a string from dns zone file something like this: example.com. 98465 IN A 127.0.0.1 anotherExample.com. 98464 IN B 127.0.0.2 I use pre tag to split them into lines because i need to show them in a web page for users. <pre> <p> {{ dnsFileString }}</p> </pre> And I need to split them to show them in a nice way something like this: example.com. 98465 IN A 127.0.0.1 anotherExample.com. 98464 IN B 127.0.0.2 An Example how it should looks like: https://help.dyn.com/how-to-format-a-zone-file/ Is there is any way to make that? -
Django send POST request to views.py with CSRF token, then redirect page
I originally had an AJAX call to my view, then I realized I can't return render(request, 'my/new/template.html, context) So I came upon this related question, which led me to what I show below: Redirect to new page after receiving data from Javascript However I'm having trouble getting the CSRF token to work, it's giving me a 403 error. As a side note, I am also using shell_plus to use a secure connection, but I don't think that is contributing to the issue. Here is my call to the view function: submitForm.addEventListener('submit', function (e) { const form = new FormData(e.target); // const csrf_token = form.get("csrfmiddlewaretoken"); // instead using var csrf_token = {{ csrf_token in template }} e.preventDefault() instance.requestPaymentMethod(function (err, payload) { var url = '/shop/payment/'; var newForm = '<form action="' + url + '" method="post">'; newForm += '<input type="hidden" name="csrf_token" value="' + csrf_token +'" />' newForm += '<input type="hidden" name="paymentMethodNonce" value="' + payload.nonce + '" />' newForm += '<input type="hidden" name="orderTotal" value="' + order_total + '" />' newForm += '<input type="hidden" name="address" value="' + $('#address-select').val() + '" /> newForm += '<input type="hidden" name="first-name" value="' + form.get("first-name") + '" />' newForm += '<input type="hidden" name="last-name" value="' + form.get("last-name") + '" />' newForm … -
RelatedObjectDoesNotExist at / User has no customer
RelatedObjectDoesNotExist at / User has no customer. I am getting this error (RelatedObjectDoesNotExist at / User has no customer.) after I register a user and attempt to sign in. I am only able to sign in with a superuser I created but not with a new user I register. views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): #saving the registered user form.save() username= form.cleaned_data.get('username') messages.success(request, f'Your Account has been created! You can now log in') return redirect('login') else: form = UserCreationForm() #creates an empty form return render(request, 'store/register.html', {'form': form}) #THIS IS THE ERROR IT LEADS ME TO def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() # getting all the products context = { 'products': products, 'cartItems': cartItems } # allows us to use in our template return render(request, 'store/store.html', context) #models.py class Customer(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=50, null=True) email=models.CharField(max_length=200) def __str__(self): return self.name #this will show on our admin panel [yellow page error][1] [1]: https://i.stack.imgur.com/mfKgq.png -
Can a ThreadPoolExecutor be used as a DB connection pool for Django's ORM?
I have an async python application that uses Django's ORM and executes concurrent queries. For the concurrent queries I am using a ThreadPoolExecutor with 10 worker threads. I set django's CONN_MAX_AGE setting to 5 minutes, so the database connection will be open during that time. All queries are wrapped in a try/finally block that closes old connections by calling django.db.close_old_connections() like: import asyncio from django.db import close_old_connections def async_query(...): async def decorator(...): try: return await asyncio.get_running_loop().run_in_executor(...) finally: close_old_connections() return decorator Is that the right way to make a connection pool? I am using Python 3.7.7, Django 2.2.12 and MySQL 8. -
Django Generic views not working for PUT , GET , UPDATE , PATCH
I have RetrieveUpdateDestroyAPIView view like this. class TaskRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): lookup_field='id' serializer_class = TasksSerializer def get_queryset(self): query_set=Task.objects.get(id=self.kwargs['id']) def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) and my urls like this path('task_detail/<int:id>', TaskRetrieveUpdateDestroyAPIView.as_view(), name="get_task"), I am trying to PUT , PATCH , GET but getting same error { "detail": "Not found.", "status_code": 404 } -
Django Video File
I have a problem when I try to display a video in a post. It won't display it HTML FILE {% if post.video %} <video width="400" height="300" controls > <source src={{post.video.url}}" type="video/mp4" > </video> {% endif %} Models.py class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now ) #one user can have multiple posts, but one post can only have one author author = models.ForeignKey(User, on_delete = models.CASCADE) image = models.ImageField(blank = True, null=True, upload_to='post-images') video = models.FileField(blank=True, null=True, upload_to='post-images') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home') how can I solve this -
Is it possible convert an serializer Field to array
While using DRF I need create a list of values inside my API response which I could not manage yet. For my User and Media serializers, I have come by this solution. class UserMediaSerializer(serializers.ModelSerializer): thumb = HyperlinkedSorlImageField( '40x40', options={"crop": "center"}, source='image', read_only=True ) # A larger version of the image, allows writing image = HyperlinkedSorlImageField('1024') src=serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = [ "thumb", "image", "src"] def get_src(self, obj): src = get_thumbnail(obj.image, '200x200', crop='center', quality=99).url return src class UserDisplaySerializer(serializers.ModelSerializer): thumbnail = HyperlinkedSorlImageField( '40x40', options={"crop": "center"}, source='image', read_only=True ) middle_thumbnail = HyperlinkedSorlImageField( '75x75', options={"crop": "center"}, source='image', read_only=True ) big_thumbnail = HyperlinkedSorlImageField( '120x120', options={"crop": "center"}, source='image', read_only=True ) media = serializers.SerializerMethodField(read_only=True) # A larger version of the image, allows writing image = HyperlinkedSorlImageField('1024') class Meta: model = User fields = [ "username", "big_thumbnail","middle_thumbnail", "thumbnail","image", "media"] def get_media(self, instance): user = User.objects.get(username=instance) serializer = UserMediaSerializer(user, read_only=True) return serializer.data and my views: class TeacherListView(APIView): queryset = User.objects.filter(is_active=1) serializer_class = UserDisplaySerializer lookup_field = "username" def get(self, request, format=None): users = User.objects.filter(is_active=1).filter(is_teacher=1) serializer = UserDisplaySerializer(users, many=True) return Response(serializer.data) now my API response: #api_view HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "username": "ytsejam", "big_thumbnail": "/media/cache/98/82/9882fa018db6f63c56f095d39729bdc8.jpg", "middle_thumbnail": … -
python codes dosent work in template django
I don't know why but my code doesn't work I don't know where the problem is .please help my product doesn't appear on the template although I have saved products in the database > {% for product in products %} > <div class="col-md-6 col-lg-3 ftco-animate"> > <div class="product"> > {% if product.ImgProduct %} > <a href="#" class="img-prod"><img class="img-fluid" src="{{ product.ImgProduct.url }}" alt="Colorlib > Template"> > <div class="overlay"></div> > </a> > {% endif %} > <div class="text py-3 pb-4 px-3 text-center"> > <h3><a href="#">{{ product.product_name }}</a></h3> > <div class="d-flex"> > <div class="pricing"> > <p class="price"><span>{{ product.product_price }}</span></p> > </div> > </div> > <div class="bottom-area d-flex px-3"> > <div class="m-auto d-flex"> > <a href="#" class="add-to-cart d-flex justify-content-center align-items-center text-center"> > <span><i class="ion-ios-menu"></i></span> > </a> > <a href="#" class="buy-now d-flex justify-content-center align-items-center mx-1"> > <span><i class="ion-ios-cart"></i></span> > </a> > <a href="#" class="heart d-flex justify-content-center align-items-center "> > <span><i class="ion-ios-heart"></i></span> > </a> > </div> > </div> > </div> > </div> > </div> > > {% endfor %} -
Django Rest Framework User List Is Missing 1 User
In Django i have a view that list all the user using Serializer by Django Rest Framework. class UserListView(generics.ListAPIView): def get_queryset(self): return UserListSerializer.Meta.model.objects.all() renderer_classes = (JSONRenderer,) permission_classes = (IsAuthenticated,IsAdminUser) serializer_class = UserListSerializer pagination_class = StandardResultsSetPagination I got all the user from the view except 1, lets say with the username noobmaster. And then i use Django shell to check it manually. UserListSerializer.Meta.model.objects.all() the result of that is including noobmaster. I even try this UserListSerializer(<User: noobmaster>) and it worked. I dont understand what happenned to the view, why it doesnt index noobmaster. any clue? -
Django get related objects in ManyToMany relationship
I have Post and each post contains list of categories The problem is when i get a Post its returning for me the Categories by its ids and i need the whole Category Object Post Model class Post(models.Model): title = models.CharField(max_length=50) notes = models.TextField() image = models.ImageField(upload_to="post_image") time = models.CharField(max_length=50) steps = models.ManyToManyField(Step) categories = models.ManyToManyField(Category) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title @api_view() def get_all_posts(request): all_posts = Post.objects.all() data = JobSerializer(all_posts , many = True).data return Response({"data" : data}) and this is the response { "data": [ { "id": 1, "title": "asdfasdsdasd", "notes": "asdasd", "image": "/post_image/117336221_134077201701397_2783193147332010898_o_oPPEef1.jpg", "time": "12:41", "created_at": "2020-09-24T01:06:58Z", "steps": [ 2 ], "categories": [ 1 ] } ] } -
Using Django with AWS DynamoDB
according to the Django documentation: ENGINE Default: '' (Empty string) The database backend to use. The built-in database backends are: 'django.db.backends.postgresql' 'django.db.backends.mysql' 'django.db.backends.sqlite3' 'django.db.backends.oracle' You can use a database backend that doesn’t ship with Django by setting ENGINE to a fully-qualified path (i.e. mypackage.backends.whatever). How can I use DynamoDB with Django? What is the fully-qualified path? Thank you. -
Django search among specific user
I'm looking for how to filter the model with the characteristic is_sugar = True. As I use filter for the search fields I don't really understand how to do it. class UserProfile (models.Model): ... is_sugar = models.BooleanField(default=False) def get_queryset(self): query = self.request.GET.get('q', None) if query is not None: self.update_search_query(query) nutriscore = Post.objects.filter( Q(title__icontains=query) | Q(slug__icontains=query) ).distinct() user = UserProfile.objects.filter( Q(pays__icontains=query) | Q(town__icontains=query) | Q(user__username__icontains=query) ).distinct() catego = Catego.objects.filter( Q(name__icontains=query) ).distinct() #UserProfile.objects.filter(is_sugar=True) I don't know how to manage with two filters usersugar = UserProfile.objects.filter( Q(pays__icontains=query) | Q(town__icontains=query) ).distinct() results = chain(nutriscore,user,catego,usersugar) -
is there a way to use an npm package within django without a bundler?
hi I have a Django project which depends on a Django package editorjs, the only way I could get it to work was with npm, but I need it to run without npm, my browser supports type = "module for script tags and i don't need it to be compatible with other browsers, this is my code right now: <script type="module"> import EditorJS from "@editorjs/editorjs"; import Header from "@editorjs/header"; import List from "@editorjs/list"; const editor = new EditorJS({ holder: "editorjs", tools: { header: { class: Header, inlineToolbar: ["link"], }, list: { class: List, inlineToolbar: true, }, embed: { class: Embed, config: { services: { youtube: true, coub: true, }, }, }, }, }); let saveBtn = document.getElementById("savebtn"); saveBtn.addEventListener("click", function () { editor .save() .then((outputData) => { console.log("Article data: ", outputData); }) .catch((error) => { console.log("saving failed: ", error); }); }); </script> and I load the library from a CDN: <script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script> the editorjs object works even without explicitly importing it, but none of the others do (header, list, embed, and a couple of other ones I tried) any help would be greatly appreciated thanks in advance -
How to return ordered by date QuerySet with unique field
I have a news aggregator based on Django REST + PostgreSQL. In my view I want to return distincted by link articles (source, title, text, link fields) and sorted by import_date desc. Here is my code: class ArticleViewSet(viewsets.ModelViewSet): """list of news by subscription for authorised users only""" permission_classes = [permissions.IsAuthenticated] def get_queryset(self): """filter news by current user subscriptions""" subs = self.request.user.profile.subscriptions return Article.objects.filter(source__in=subs) \ .order_by('-import_date', 'link') \ .distinct('import_date', 'link') \ def get_serializer_class(self): """news with preview text when listing""" if self.action == 'list': return ArticleListSerializer return ArticleSerializer So I expect to get the list of unique articles sorted by date desc. But my query works only for 'import_date', links not unique. If I swap positions: def get_queryset(self): """filter news by current user subscriptions""" subs = self.request.user.profile.subscriptions return Article.objects.filter(source__in=subs) \ .order_by('link, '-import_date') \ .distinct('link', 'import_date') \ Then sorting by date doesn't work. I concluded that distinct works with only one parameter. My question: how to finally get my unique list of articles sorted by date? Don't understand how to make distinct() work for 2 values. Thanks! -
How to send Push Notifications at Specific times listed in a Django Model
I am looking to use my django rest framework project along with django push notifications to send notifications to iOS users. I want these notifications to be sent at times specified in my django models. What would be the best way to achieve something like this? -
render method returns html code not showing page in django
I am implementing google-sso from login.html and after successful login, it should render to dashboard.html file but, in response render() is giving only HTML code of dashboard rather than showing on the browser. and my dashboard.html file is in dashboard app. so basically I have two app abc and dashboard. Is there anything I am doing wrong? abc/views.py def google_sso(response): return render(response,"abc/login.html",{}) def abc(request): return render(request,"dashboard/dashboard.html",{}) urls.py from django.contrib import admin from django.urls import path, include from abc import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('abc',views.abc, name="abc"), path('',include('dashboard.urls')), ] login.html <html> {% csrf_token %} <script> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; function onSignIn(googleUser) { console.log("Sign in successful! Yay!"); let id_token = googleUser.getAuthResponse().id_token; let xhr = new XMLHttpRequest(); xhr.open('POST', 'http://localhost:8000/abc'); xhr.responseType = 'document'; xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function () { }; let send_params = 'provider=google-oauth2&code=' + id_token; xhr.send(send_params); } </script> </html> dashboard/dashboard.html <html> <head> Welcome!! </head> <title>Welcome!!</title> <html>