Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get error messages in django_rest_framework in a json format
I want to get an error message { "phone": [ "user with this phone already exists." ] } in a JSON format like {"error": "user with this phone already exists."} from the response HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "phone": [ "user with this phone already exists." ] } but what I am getting is just VM8:1 POST http://127.0.0.1:8000/users/ 400 (Bad Request) Here is my code: Serializers.py class UserCreateSerializer(UserCreateSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'email', 'phone', 'stream', 'school', "password", ) -
Update or create does not update and only creates
@require_http_methods(["POST"]) @login_required def edit_question(request): req = json.loads(request.body) question_no = req["question_no"] guided_answers=req["guided_answer"] for guided_answer in guided_answers: obj, created= models.ModelAnswer.objects.update_or_create( question_id=models.Questions.objects.get(pk=question_no), model_ans= guided_answer["model_ans"], answer_mark=guided_answer["answer_mark"], defaults={ 'answer_mark':guided_answer["answer_mark"], 'model_ans':guided_answer["model_ans"], } ) return success({"res": True}) What i am trying to do is update or create based off checking whether the model answer already exist or not in the database however everytime i try to update an existing model answer it creates it into a new one, i do not understand why it does not filter out if it exists or not,i do not know whether it is my filter or my defaults that is wrong -
How to solve POST http://127.0.0.1:8000/bkash/payment/create 403 (Forbidden) ?(Django + ajax)
I used "django-bkash-integration 0.3" https://pypi.org/project/django-bkash-integration/ with my project to integrate bkash payment gateway. Bkash also provide me BKASH_APP_KEY = // bkash app key BKASH_APP_SECRET = // bkash app secret BKASH_APP_USERNAME = // bkash app username BKASH_APP_PASSWORD = // bkash app password BKASH_APP_VERSION = // bkash app version BKASH_APP_BASE_URL = // bkash app base url According bKash Checkout Script https://developer.bka.sh/docs/bkash-checkout-script connect it from the frontend. template link: https://github.com/MdNazmul9/bkash-front-end-problem/blob/main/templates/bkash_index.html I always get POST http://127.0.0.1:8000/bkash/payment/create 403 (Forbidden). How can I solve it ? -
django argon2password hasher behaves weird
screenshot of pip list and error I have already installed argon2password hash in virtual environment and by pipenv list it shows that already there, also while re-installing it shows already have met the requirements. But while giving password for login it shows ValueError at /login/ Couldn't load 'Argon2PasswordHasher' algorithm library: No module named 'argon2' what's the actual problem?? I couldn't resolve it. -
Custom validation error message in django rest framework ImageField
I'm trying to create my custom validation error messages in django rest framework. I have a productSerializer like the below code: class ProductSerializer(serializers.ModelSerializer): # validation name = serializers.CharField(error_messages={'blank': 'Please fillout the product name!'}) price = serializers.FloatField(error_messages={'blank': 'Please fillout the product price!'}) slug = serializers.SlugField(error_messages={'blank': 'Please fillout the product slug!'}) size = serializers.CharField(error_messages={'blank': 'Please fillout the product size!'}) description = serializers.CharField(error_messages={'blank': 'Please fillout the description!'}) image = serializers.ImageField(error_messages={'blank': 'Please upload a photo image!'}) # validation category = serializers.StringRelatedField(read_only=False) productType = serializers.StringRelatedField() user = serializers.StringRelatedField() class Meta: model = Product fields = "__all__" and my views.py be like: class ProductsList(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def post(self, request): serializer = ProductSerializer(data=request.data) category = Category.objects.get(name=request.data['category']) productType = ProductType.objects.get(name=request.data['productType']) user = User.objects.get(username= request.user.username) if serializer.is_valid(): serializer.save(category=category, productType=productType, user=user) return Response("SUCCESS!!!!!!", status=200) else: return Response(serializer.errors, status=400) The problem: I want the image field error message to be what I've written, when it's blank. But I always face the message "No file was submitted." Question: How can I validate the image field being blank? -
How to change success url?
Url File. Here a red mark where I want to put my success url. what should change in my code ? views.py -
Django ipware environment variable for proxy_trusted_ips
I want to make an environment variable for a list of IP addresses for django-ipware's proxy_trusted_ips. I am testing on localhost before going to production. Whatever IP address I put inside of proxy_trusted_ips, it returns None plus the traceback below. Example change get_client_ip(request, proxy_trusted_ips=['177.139.233.133']) to get_client_ip(request, proxy_trusted_ips=settings.PROXY_TRUSTED_IPS) JSON file of environment variables: "PROXY_TRUSTED_IPS":"127.0.0.1,127.0.0.1", settings.py: PROXY_TRUSTED_IPS = config['PROXY_TRUSTED_IPS'].strip('"').split(',') views.py: ip, is_routable = get_client_ip(request, proxy_trusted_ips=settings.PROXY_TRUSTED_IPS) print(ip) if (ContactSpamModel.objects.filter(email=contact_email).exists() or ContactSpamModel.objects.filter(ip_address=ip).exists()) and ContactSpamModel.objects.filter(inserted__gt=timezone.now() - timezone.timedelta(seconds=int(settings.SPAM_TIMEOUT_SECONDS))): current_time = datetime.datetime.now() diff = current_time.timestamp() - time.mktime(datetime.datetime.fromisoformat(ContactSpamModel.objects.filter(ip_address=ip).values(result=Cast('inserted', TextField())).first()['result']).timetuple()) seconds_diff = divmod(diff, int(settings.SPAM_TIMEOUT_SECONDS)) x,seconds_remaining = divmod(diff, int(settings.SPAM_TIMEOUT_SECONDS)) remaining = (int(settings.SPAM_TIMEOUT_SECONDS) + 60 - seconds_remaining) // 60 if seconds_diff[0] < 1: if str(int(remaining)) == '1': messages.info(request, "We received a contact message from you recently. Please wait " + str(int(remaining)) + " minute and try again.") return HttpResponseRedirect(request.path_info) else: messages.info(request, "We received a contact message from you recently. Please wait " + str(int(remaining)) + " minutes and try again.") return HttpResponseRedirect(request.path_info) else: ContactSpamModel.objects.filter(inserted__lt=timezone.now() - timezone.timedelta(minutes=1)).delete() ContactSpamModel(email=contact_email,ip_address=ip).save() Models.py: class ContactSpamModel(models.Model): email = models.EmailField() inserted = models.DateTimeField(auto_now_add=True) ip_address = models. GenericIPAddressField() Traceback: Traceback (most recent call last): File "/home/name/.local/share/virtualenvs/project_name/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/name/.local/share/virtualenvs/project_name/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL … -
I am getting an error while using Django ManyToManyField
in view.py def watchlist(request, item_id): list=get_object_or_404(Listing, id=item_id) wc=WatchCount(user=request.user) if WatchCount.objects.filter(user=request.user, listing=list).exists(): wc.listing.remove(list) else: wc.listing.add(list) return HttpResponseRedirect(wc.get_absolute_url()) in models.py class WatchCount(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) listing = models.ManyToManyField(Listing, blank=True, related_name="watchcount") def __str__(self): return f"{self.user.username}" def count(self): return self.listing.count() def get_absolute_url(self): return reverse('list', kwargs={'item_id': self.pk}) ERROR: "<WatchCount: jeelen>" needs to have a value for field "id" before this many-to-many relationship can be used. -
How to set the time out in Django Rest Framework?
How to set the time out in Django Rest Framework. is it from the settings file. -
Token based authentication using Authentication header giving 403 forbidden error
I have the following code in my react app: I am sending an update request to rest backed which requires a user to be authenticated to perform PUT/POST/DELETE requests. const update = (e) => { e.preventDefault() const formData = new FormData(form.current); console.log('Token ' + localStorage.getItem("token")) // valid token const requestOptions = { method: 'PUT', headers : { // 'Authorization': 'Basic ' + btoa('user:password') // basic authentication works "Authorization": 'Token ' + localStorage.getItem("token"), }, body: formData }; fetch(url, requestOptions) .then(async response => { const data = await response.json(); if(!response.ok){ const error = (data && data.message ) || response.status; return Promise.reject(error) } alert('member updated') history.push("/members") }) .catch(error => console.error('Some error ', error)) } Unfortunately, I'm getting these in console logs: PUT http://localhost:8000/uskindia/56/ 403 (Forbidden) Some error 403 And this in backed logs: Forbidden: /uskindia/56/ [... *:*:*] "PUT /uskindia/56/ HTTP/1.1" 403 58 ``` Trying to solve this for the last 24 hours but not getting it right. -
How to add two more Columns in the USER model in djan
How to add these columns(dob, and one more) in User Model, and if we want to add one or more field like a phone number so can id add to the User model or not ?? views.py def register(request): if request.method == "POST": # Get the post parameters username = request.POST['username'] email = request.POST['email'] fname = request.POST['fname'] lname = request.POST['lname'] dob = request.POST['dob'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check for errorneous input if User.objects.filter(username=username).exists(): messages.error(request, 'This Aadhaar is Already Used') return redirect('home') if User.objects.filter(email=email).exists(): messages.error(request, 'This Email is already Used') return redirect('home') if (pass1 != pass2): messages.error(request, " Passwords do not match") return redirect('home') # Create the user myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname myuser.dob = dob myuser.save() messages.success(request, "You are successfully registered") return redirect('home') else: return HttpResponse("404 - Not found") -
How to create a view for a model
How do I build a function for this model to display team.name for members in my team on page and list my teams.members for members in my team ? class Team(models.Model): name = models.CharField(max_length=255) members = models.ManyToManyField(User, related_name='teams') created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) plan = models.ForeignKey(Plan, related_name='teams', on_delete=models.SET_NULL, null=True, blank=True) -
how to use OpenCV lib on a python host cpanel?
I have django project that I need to use OpenCV lib in it. I have no error or problem as long as I run the project on a localhost on my computer. However, when I push my project on a real host on internet (The host uses Linux as OS) I face some errors that I cannot solve them. at the first level this error shows up when I import cv2 (I have already installed numpy lib): OpenBLAS blas_thread_init: pthread_create failed for thread 30 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 31 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 32 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 33 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 34 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 35 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 36 of 46: … -
Why does this hacky way of specifying installed_apps in Django work, but not the proper way?
My file structure is like this: and the INSTALLED_APPS in settings.py looks like this: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "nstv_fe", "django_tables2", ] With this setup, running a script that imports a model from nstv_fe (from nstv_fe.nstv_fe.models import Show), I get the following error: # If "not ready" is due to unconfigured settings, accessing # INSTALLED_APPS raises a more helpful ImproperlyConfigured # exception. settings.INSTALLED_APPS > raise AppRegistryNotReady("Apps aren't loaded yet.") E django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. ../../venv/lib/python3.8/site-packages/django/apps/registry.py:135: AppRegistryNotReady Most of the stackoverflow questions about this are answered by setting the DJANGO_SETTINGS_MODULE environment variable to the settings file - so I tried setting it to nstv_fe.nstv_fe.settings and nstv_fe.settings, but neither worked. What I find odd is that if I go into django/apps/registry.py and manually create a list: installed_apps = ['nstv_fe'] in the Apps class, it'll run the test for the script that imports the model no problem. But if I don't manually add that line, it'll give me the AppRegistryNotReady error. This leads me to believe that nstv_fe isn't getting picked up properly in the installed apps somehow, but I'm not sure where I'm going wrong because I have it in the INSTALLED_APPS list in settings.py. How can … -
How to give an object multiple ratings (on different aspects) with django-star-ratings app?
The django-star-ratings is a nice package that can add ratings to any Django model with just a few lines of code in an existing project. However, the default app only supports 1 rating on an object by a specific user. Considering giving multiple ratings to an object in various aspects, such as 1. Ease of use; 2. Value; 3. Quality etc., do anyone know what's the easiest way to accomplish this? -
Usar múltiplas database no DJANGO
Bem, comecei estudar django esse ano e veio uma dúvida e não consegui arrumar. O problema é que tenho várias database no mysql e algumas possuem relações entre elas. Quando quero mapear uma única database, por exemplo: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatabaseName1', 'USER': 'DatabaseUserName', 'PASSWORD': 'DatabaseUserpassword', 'HOST': 'localhost', 'PORT': '5432', }, é facinho, uso python manage.py inspectdb tab1 tab2 > my_app/models.py e vai. Ai tenho outra database que faz relação com essa DatabaseName1, mas já deu ruim :( kk Já tentei: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatabaseName1', 'USER': 'DatabaseUserName', 'PASSWORD': 'DatabaseUserpassword', 'HOST': 'localhost', 'PORT': '5432', }, 'segunda': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatabaseName2', 'USER': 'DatabaseUserName', 'PASSWORD': 'DatabaseUserpassword', 'HOST': 'localhost', 'PORT': '5432', } } O user, password, host e port são os mesmo, isso é possível? -
Wagtail upgrade from 2.12 to 2.13 -- migrations not applying
I have a Wagtail project using the following: Wagtail 2.12.4 Django 3.1.11 Python 3.8.5 Postgres 12.6 I tried to upgrade Wagtail to version 2.13. When I run python manage.py migrate after the upgrade, the migrations appear to complete successfully, and they show as having completed when I run python manage.py showmigrations. However, the database tables targeted by the migrations remain unchanged, and the migrations do not appear in the django_migrations table of the database. This problem persists even if I run the specific migration with python manage.py migrate wagtailusers 0010. I have looked online for similar issues, but I haven't been able to find anything. Any advice on how I can find what is causing this issue to happen? -
User account activation url not found in Django
I'm trying to activate a user account in django but I'm getting 404 error, and the error is due to the fact that django is unable to get the activation url. urls.py urlpatterns = [ path('activate/<slug:uidb64>/<slug:token>)/', views.account_activate, name='activate'), ] views.py def account_activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('account:dashboard') else: return render(request, 'account/registration/activation_invalid.html') template {% autoescape off %} Great {{ user.user_name }}! Please click on the link below to activate your account http://{{ domain }}{% url 'account:activate' uidb64=uid token=token %} {% endautoescape %} I have spent a couple of hours trying to figure out where my mistake is but I haven't been able. Please I want some insight on this. -
Stripe integration with Django rest and Angular/Cli
I want to create a stripe payment integration using Django Rest Framework as backend and Angular/Cli as frontend. And also I want to confirm the payment using stripe webhooks. I could not able to find Angular documentation just for the only frontend. And also the Stripe docs are generally has written for flask and not for the rest framework. Any help will be appreciated. Thank you in advance. -
Read More js in django for loop
I tried to apply this post to integrate read more/read less JS into a django template. I want to limit my post app. 200 characters and providing the user the option to Read More. This script seems to work fine... not so much in my case. It displays the Read More option but once clicked no event it triggered. That is, it doesn't open the entire text. It displays a colored test 'Read More' but noting else happens. Here's the answer provided in that post: {% for post in posts %} {% if post.content|length > 150 %} <p class="half-content" id="half-{{post.id}}">{{ post.content|truncatechars:150 }}<a data-id="{{post.id}}" href="javascript:void();" class="show-hide-btn">read more</a></p> <p class="full-content" id="full-{{post.id}}" style="display: none;">{{ post.content }}</p></div> {% else %} <p>{{ post.content }}</p> {% endif %} {% endfor %} <script> $(document).ready(function(){ $(".show-hide-btn").click(function(){ var id = $(this).data("id"); $("#half-"+id).hide(); Any input is highly appreciated. -
Django convert Date of Birth model field to Age
I have a Django class to convert the date of birth (dob) field in my model to age and annotate the result to a queryset. class CalculateAge(Case): def __init__(self, model, field, condition=None, then=None, **lookups): today = date.today() obj = model.objects.first() field_object = model._meta.get_field(field) field_value = field_object.value_from_object(obj) bornyear = field_value.year bornmonth = field_value.month bornday = field_value.day # something is wrong with the next two lines age = [today.year - bornyear - ((today.month, today.day) < (bornmonth, bornday))] return super().__init__(*age, output_field=IntegerField()) however when I try to pass the result to my queryset queryset = Person.objects.all().annotate(age=CalculateAge(Person, 'dob') I get the error Positional arguments must all be When objects. How can I get this to work? -
Getting ERROR... {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} django
I have created a ajax function to accept the request for my project but when i am trying to accept it is giving me 200 but does nothing and goes to error in my ajax. here is my ajax function acceptMatchRequest(match_request_id, uiUpdateFunction){ var url = "{% url 'accept-match-request' match_request_id=53252623623632623 %}".replace("53252623623632623", match_request_id) $.ajax({ type: 'GET', dataType: "json", url: url, timeout: 5000, success: function(data) { console.log("SUCCESS", data) if(data['response'] == "Match request accepted."){ // ui is updated } else if(data['response'] != null){ alert(data['response']) } }, error: function(data) { console.error("ERROR...", data) // console.log(data) alert("Something went wrong.") }, complete: function(data){ uiUpdateFunction() console.log(data) } }); } Here is my JS function onMatchRequestAccepted(){ location.reload(); } function triggerAcceptMatchRequest(match_request_id){ acceptMatchRequest(match_request_id, onMatchRequestAccepted) } My views.py def accept_match_request(request, *args, **kwargs): user = request.user print(user) payload = {} if request.method == "GET" and user.is_authenticated: match_request_id = kwargs.get("match_request_id") if match_request_id: match_request = MatchRequest.objects.get(id=match_request_id) # confirm that is the correct request if match_request.receiver == user: print(match_request) if match_request: # found the request. Now accept it match_request.accept() payload['response'] = "Match request accepted." else: payload['response'] = "Something went wrong." else: payload['response'] = "That is not your request to accept." else: payload['response'] = "Unable to accept that Match request." else: # should never happen payload['response'] = "You … -
Display Item requested by user in template (django)
I have a simple borrowing items request app, which the user would log in and fill out a form with the following: Item Location Start date End date This is stored in a database Record stored in database Then I have a return page where the user will confirm that has returned the item by just clicking return. I want to show the only the related items with the user logged in to the page, (so just the request the user made: the current item and the previous ones.) I have the following model for the Request Table: class Request(models.Model): shootkit_id = models.ForeignKey(Shootkit, on_delete=models.CASCADE) username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) request_start_date = models.DateField('Start Date') request_end_date = models.DateField('End Date') location = models.ForeignKey(Location, on_delete=models.CASCADE) The following def in views: def return_form(request): form = shootkitForm request_db = Request.objects.all return render(request, 'return_form.html', {'form':form, 'request_db':request_db}) And the following on the template return: {% for shootkit in request_db %} <div class="callout-info">Hi {{ user }}, you currently have the {{ shootkit.shootkit_id }}</div> {% endfor %} Obviously this is showing every single record on the table (if I ahve more that one record). I would like to only display the item (in this case a shootkit #5) linked … -
How to get clicked item in view
I am relatively beginner in django. In one of my template, I am creating list of items stored in database. With following template.html code: <ul> {% for item in items %} <li> {{ item.name }} </li> {% endfor %} </ul> Rendring from view.py code: def category_view(request): list = Category.objects.order_by('name') context = {'items': list} return render(request, "template.html", context=context) Now, I want to get name of the list item (category) on which user has clicked, so I can show user sub-categories on next page depending upon selected one in previous page. Kindly, share idea how to get clicked item and flow to send dependent list to next page. -
Django Rest Framework & Vue.js; login via Google account; "User is already registered with this e-mail address."
I have some trubbles with loggin to my web site via Google account. I created registarion via Google (using vue-google-login then sending that data to my backend to dj-rest-auth/google/) and thats work fine. But if I'm trying to log in user I get a response from my backend server "user is already registered with this email address". What can I do to make users sign in into my web app via Google account? How can I log in user but not register? I would be grateful if somebody give answers because I loose too much time debuging and searching the answers. I'll put my code below. If you need more info - just let me know. Thank you! # authenticate.views from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from dj_rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter #authenticate.urls from django.urls import path from . import views urlpatterns = [ path('google/', views.GoogleLogin.as_view(), name='google_login') ] #backend_main.urls from django.contrib import admin from django.urls import path, include from django.conf.urls import url from authentication.views import GoogleLogin from backend_main.api_views import get_router_urls urlpatterns = [ path('admin/', admin.site.urls), path('hr-api/', include(get_router_urls())), path('demo-hr-api/', include('backend_main.urls')), path('accounts/', include('allauth.urls'), name='socialaccount_signup'), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/google/', GoogleLogin.as_view(), name='google_login'), ]