Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django a simple query makes me crazy ''int' object is not iterable'
I have two Models: class MasterData(models.Model): ID = models.AutoField(primary_key=True) Companyname = models.CharField('Companyname', max_length=128, blank=True, null=True) UserID = models.IntegerField('UserID') class Prefixes(models.Model): ID = models.AutoField(primary_key=True) UserID = models.ForeignKey('MasterData', on_delete=models.CASCADE) InvoiceNoPrefix = models.CharField('InvoiceNoPrefix', max_length=5, blank=True, null=True) No I want in my view a make a simple objects.get_or_create if you visit the site the first time and no records exist should it create one. @login_required(login_url='/backend/') def edit_prefixes(request): user_id = request.user.id userfrommasterdata = MasterData.objects.filter(UserID__in=user_id) prefixes_data = Prefixes.objects.get_or_create(UserID=userfrommasterdata) And all what I get is a: 'int' object is not iterable What do I miss? On my MasterData view it's working perfectlit: @login_required(login_url='/backend/') def edit_masterdata(request): user_id = request.user.id # stamdata_data = get_object_or_404(Stamdata, pk=user_id) stamdata_data, _ = MasterData.objects.get_or_create(UserID__iexact=user_id, UserID=user_id) -
Managing post data from external API (callback URL)
I have a Django app in the MENA region and can't use Stripe as the payment gateway there, I'm relying on a payment page created on the site as a response to my payment request ( I'm not hosting the payment form on my own site ) this is the response I get when my server sends the payment page creation {'callback': 'https://example.com/mycallback', 'cart_amount': '{amount}', 'cart_currency': '{currency}', 'cart_description': 'Subscription 123', 'cart_id': '4244b9fd-c7e9', 'redirect_url': 'https://payment-gateway.com/payment/page/9B8E682', 'tran_ref': 'TST2109500134074', 'tran_type': 'Sale'} and when the user proceeds to the payment form gets redirected to my callback URL with a HTTP POST like this: acquirerMessage=&acquirerRRN=&cartId=4244b9fd-c7e9&customerEmail=user@email.com&respCode=G95839&respMessage=Authorised&respStatus=A&token=&tranRef=TST2109500134074&signature=c93f8f98c46e8bf972b8848f4a59f81583304f125bd7e4d136fd8b4432baf7b3 and based on this response my callback view will handle the user data. If you supplied a callback URL, then the Payment gateway will send the transaction results to that URL using a HTTP POST. This will be a purely server-to-server request, the customers browser will not be involved. Your systems should provide HTTP response with response codes 200 or 201. how should I handle this in the callback URL how can I grap this data ? -
why the Django rest framework ModelSerializer. create and ModelSerializer.validate not working properly?
I am developing an authentication system for User registration through Django rest framework. serializers.py from rest_framework import serializers from .models import NewEmployeeProfile class RegistrationSerializers(serializers.ModelSerializer): ''' We need to add the password2, as its not the part of the NewEmployeeProfile model. So, we need to make it manually. ''' password2 = serializers.CharField(style={'input_type: password'}, write_only=True) class Meta: model = NewEmployeeProfile fields = ('email', 'first_name', 'last_name', 'employee_code', 'contact', 'dob', 'password', 'password2') extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): """ before we save the new user, we need to make sure that the password1, and password2 matches. In order to do that, we need to override the save() method. """ password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': f'password must match..'}) return NewEmployeeProfile.objects.create(**validated_data) def validate(self, attrs): if attrs: account = NewEmployeeProfile( email=self.validated_data['email'], first_name=self.validated_data['first name'], last_name=self.validated_data['last name'], employee_code=self.validated_data['employee code'], contact=self.validated_data['contact'], dob=self.validated_data['dob'], ) account.save() return account views.py class UserRegisterView(ListCreateAPIView): create_queryset = NewEmployeeProfile.objects.all() serializer_class = RegistrationSerializers(create_queryset, many=True) permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = RegistrationSerializers(data=request.data) if serializer.is_valid(): newUser = serializer.save() serializer = RegistrationSerializers(newUser) return Response(data={"status": "OK", "message": serializer.data}, status=status.HTTP_201_CREATED) return Response(data={"status": "error"}, status=status.HTTP_400_BAD_REQUEST) models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, … -
Uploading and Retrieving Images to MongoDB Atlas using Django Rest (HELP)
I'm having trouble uploading images to Mongo and retrieving them using Django Rest. I am using GridFS and I'm simply trying to upload a profile picture of a user.This what my api looks like after uploading my image It does not show me a viable link to access it. It just points me back to the create view for some reason. I checked my Mongo Atlas page and it seems like the images are being stored. How can I properly retrieve my images? Here is the code I wrote: settings.py BASE_URL = 'http://127.0.0.1:8000/' models.py grid_fs_storage = GridFSStorage(collection='myfiles', base_url=''.join([settings.BASE_URL, 'myfiles/'])) class ProfilePic(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='users', default='avatar.png',storage=grid_fs_storage) serializers.py class ProfilePicSerializer(serializers.ModelSerializer): class Meta: model = models.ProfilePic fields = ('id', 'profile_pic') views.py class ProfilePicView(viewsets.ModelViewSet): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = models.ProfilePic.objects.all() serializer_class = ProfilePicSerializer -
is there a better way of checking if multiple key exists in a dictionary and assigning multiple values to a variable based on the key found
is there a better way of checking if multiple key exists in a dictionary and assigning multiple values to a variable based on the key found in the dictionary. instead of multiple ifs?? name = None type_of_transaction = None customer = None transaction_id = None for key, value in data_value.items(): if "unique_element" in key: customer = value if "type" in key: type_of_transaction = value if "product_name" in key: name = value if "transactionId" in key: transaction_id = value -
A form submit returns {"error": "'action'"}
I have a form submit that crashes in production with the following error {"error": "'action'"}, but for some weird reason does not happen in local way. The input with id="btnEditar" is the one that push the error. The error is displayed in a white page. Nothing appears in the console of the browser and as far as the error doesnt ocurr in local no messages appears in the backend. I have tried to reload js in several browsers but with the same results... running on Django local dev server the form is submitted OK and the data is updated as well, but in pythonanywhere prod server the error mentionated error comes up. hope you can help me to figure it out!! Here is the template code: {% extends 'core/home.html' %} {% load static %} {% load bootstrap %} <!doctype html> <html lang="es"> <head> </head> <body class="text-center"> {% block content %} <form method="post"> {% csrf_token %} <div style="visibility: hidden;" id="HiddenId">{{ object.id }}</div> <div style="visibility: hidden;" id="HiddenFecAnt">{{ object.start_time }}</div> <div class="container mb-4" style="margin-top: 10px;"> <div class="row justify-content-center"> <div class="card w-24" style="height: 7rem; width: 14rem; margin: 2px"> <div class="card-header" style="height: 2.5rem;" > Fecha de Reprogramación </div> <div class="card-body"> <div class="row justify-content-center"> {{form.start_time|bootstrap}} </div> … -
Give access to my Google Drive to the users of my website
I am developing an application in django and I need that the users who enter my website have access to my Goolge Drive, I am trying to save the google accesses in the user's session, but it does not work SCOPES = ['https://www.googleapis.com/auth/drive'] credentials = Credentials.from_authorized_user_file('token.json', SCOPES) request.session['credentials'] = {'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes } -
How do I force my heroku django project to use https?
I have a django site hosted by Heroku (tachlisgeredt.com), but I am having a weird problem. Basically, for anyone going to my site going to 'tachlisgeredt.com' doesn't work, only going to 'tachlis.herokuapp.com', and even that shows 'not secure'. However, going to 'https:/www.tachlisgeredt.com' works, and it shows 'secure'. So basically, how do I force my django site hosted by Heroku to use https? -
Django DRF create new object with primary key "id: null" after axios post method
Summary I'm using django and django rest framework as backend and vue3 as frontend to build a website. I also use axios to post data to the backend and it works fine except that every object created in the backend has a primary key "id: null" instead of auto increment id field. id: null Detail I know that django will automatically create auto increment primary key for you so I didn't declare this field in my models.py. And it works because I can get the primary key id and display it in the frontend when reading data from the backend. So I think I can post data without a id field and let django do the work to provide this new instance with an auto incremented id field. However, every time the object is created and every time "id: null". Here is my serializer for the model: class MaterialSerializer(serializers.ModelSerializer): class Meta: model = Material fields = "__all__" Here is the object list view code that receives the request: class MaterialList(generics.ListCreateAPIView): queryset = Material.objects.all() serializer_class = MaterialSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] Here is my post request from vue3 using axios: const addNewMaterial = (payload) => { axios.post(store.state.backendAPIs.coreAPI, payload.data) .then(_ => console.log('...')) .catch(err … -
React rest-hooks how to Authentication
I am trying to build the authentication part of my frontend project so it can communicate with the DRF API. I decided also to use rest-hooks to fetch and send data from / to the API. I am reading rest-hooks auth documentation as a guide but I can't find the "proper way" to implement it in my project. Everything I have read so far is using resources to fetch and send data to the API. In the backend I have this /api-auth endpoint that after sending username & password parameters it returns a token to use as a header while fetching, I guess this is the "easy" part. Despite I am trying to understand the rest-hooks documentation I can't figure out how to bring this together using DRF API + rest-hooks. And plus, besides everything I have said above, I have tried this anyway, and is not working... Attempts I created this AuthResource to attach to the login form. With the fetch approach: import { Resource } from '@rest-hooks/rest'; import { API_URL } from '../utils/server'; export default class AuthResource extends Resource { static getFetchInit = (init: RequestInit) => ({ ...init, credentials: 'same-origin' }); } Error: Class static side 'typeof AuthResource' … -
How to fix UnboundLocalError in Django website
I am getting this error, "local variable 'stu_details' referenced before assignment". How can i fix it please. views.py def assignment_page(request): if request.method == "POST": get_course_name = request.POST.get('get_course_name') add_courses_get = add_courses.objects.get(Course_Name=get_course_name) stu_course_all_stu = add_courses.objects.filter(Course_Name=add_courses_get) for all_stu_details in stu_course_all_stu: for stu_details in all_stu_details.student.all(): id_ = stu_details.student_ID name = stu_details.student_name context3 = {"stu_details":stu_details, "id_":id_, "name": name, 'stu_course_all_stu':stu_course_all_stu} return render(request, 'assignment_page.html', context3) else: return redirect('/') -
can't load bundle.js using webpack-loader and Vue.js
I'm working on a small project using Django and Vue.js i have installed django-webpack-loader and everything works fine for me since i followed a udemy course, i have just one problem is Failed to load resource: net::ERR_ADDRESS_INVALID and exactly bundle.js This is my vue.config.js file : const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" otherwise http://0.0.0.0:8080/ publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, // uncomment before executing 'npm run build' // css: { // extract: { // filename: 'bundle.css', // chunkFilename: 'bundle.css', // }, // } }; By the way, I'm running my application on Ubuntu Server. -
Improving accuracy in Python Tesseract OCR
I am using pytesseract along with openCV in a simple django application in Python to extract text in Bengali language from image files. I have a form that lets you upload an image and on clicking the submit button sends it to the server side in an ajax call in jQuery to extract the text from the image to serve the purpose of OCR (Optical Character Recognition). Template part : <div style="text-align: center;"> <div id="result" class="text-center"></div> <form enctype="multipart/form-data" id="ocrForm" action="{% url 'process_image' %}" method="post"> <!-- Do not forget to add: enctype="multipart/form-data" --> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-success">OCRzed</button> </form> <br><br><hr> <div id="content" style="width: 50%; margin: 0 auto;"> </div> </div> <script type="text/javascript"> $(document).ready(function(){ function submitFile(){ var fd = new FormData(); fd.append('file', getFile()) $("#result").html('<span class="wait">Please wait....</span>'); $('#content').html(''); $.ajax({ url: "{% url 'process_image' %}", type: "POST", data: fd, processData: false, contentType: false, success: function(data){ // console.log(data.content); $("#result").html(''); if(data.content){ $('#content').html( "<p>" + data.content + "</p>" ) } } }) } function getFile(){ var fp = $("#file_id") var item = fp[0].files return item[0] } // Submit the file for OCRization $("#ocrForm").on('submit', function(event){ event.preventDefault(); submitFile() }) }); </script> The urls.py file has: from django.urls import path, re_path from .views import * urlpatterns … -
Check if token exist
How can i check if the token i'm sending to django exist? does jango rest framework has a built-in function to check this? Currently i've the login and i'm creating the token each time a user logs in c86177ae21c1c0b83a5c0354e742334ef2f376f3 -
Django Mysql string convertion utf8 and unicode?
Well, I have a django model that stores the name of a music band. So new trouble arises when a band called '✝✝✝ (Crosses)' attempts to be stored in a TextField. This is the error: django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xE2\\x9C\\x9D\\xE2\\x9C\\x9D...' for column 'album_name' at row 1") But this becomes weird because I have another table that stores a JsonField with the band info. The same name '✝✝✝ (Crosses)' is stored correctly. the JsonField was a TextField that stored json.dumps(dict_with_band_info) ... So in the database is stored something like { "name": "✝✝✝ (Crosses)" ...}. And repeat, this was a TextField before and works as expected. So why attempting to add "name": "✝✝✝ (Crosses)" to the db Textfield shows that error but not in the other table no? I'm using pdb.set_trace() to see what are the values before do the save(). I would like to mention again that that error doesn't appear even when the JsonField was TextField in my band info table, but the error appears in the TextField of the band_name and exactly in the instance.save(). with this, I can deduct that my text_fields are ready to receive unicode, because in the band info table, the jsonfield shows the … -
I raise two validationerror but if anyone of them is triggered it always gives me the same validation error output
I raised two validationerror messages but if anyone is triggered it gives me the same message of one of the the message is "User has already a current profile model try to update it not creating a new one" here is the code class CurrentProfileSerializer(serializers.ModelSerializer): class Meta: model = CurrentProfile fields = '__all__' read_only_fields = ('user', ) def create(self, validated_data): try: c_profile = CurrentProfile(**validated_data) if c_profile.profile.owner != c_profile.user: raise serializers.ValidationError('You can only use profiles that the user created') c_profile.save() return c_profile except: raise serializers.ValidationError('User has already a current profile model try to update it not creating a new one') the try and except block is made because i mad a OneToOne realtionship in my model CurrentProfile with the user model so it will trigger an error if i tried to add more than one instance of the CurrentProfile Model with same user. the validation error in the if block is made to ensure that the profile selected is created by the same user not just any random profile created by another user the weird thing is that if i remove the try and except block it works fine but when add it again in both cases it gives me the … -
How to use Ajax in Django to change image url
I'm using Django with Ajax ,I have already used Ajax to upload image successfully. Now I want to figure out how to use Ajax direct change the image url. Html: {% block content %} <div class="row"> {{user.username}} {{user.avatar.url}} <p id="error"></p> <div class="col-md-2"> <img class="avatar" src="{{user.avatar.url}}" width="60px" height="60px" /> </div> <div class="mb-2"></div> {% if request.user.username == profile_user.username %} <form enctype="multipart/form-data" class="form-horizontal" method="post"> {% csrf_token %} <label for="avatar" class="change-avatar" >更换头像/change avatar</label> <input type="file" id="avatar" style="visibility:hidden;"> <input type="button" class="btn" value="保持更改/save"> </form> <script> $(".btn").click( function(){ var formdata = new FormData(); formdata.append("avatar",$("#avatar")[0].files[0]); $.ajax({ url:"", type:"post", contentType:false, processData:false, data:formdata, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success:function(data){ console.log(data) var error = data.error var avatar = data.avatar var s =`<div> ${error} </div>` var t = '${avatar}' var src = $(".avatar").attr('src').replace('avatar','avatar') $(".avatar").attr('src', src); $("#error").prepend(s); } }) } ) </script> {% endif %} </div> {% endblock content %} views: @login_required def user_detail(request, username): profile_user = get_object_or_404(User, username=username) form = UserAvatar(request.POST, request.FILES, instance=request.user) response = {} if request.is_ajax(): if form.is_valid(): form.save() response['avatar'] = request.FILES.get('avatar') else: response['error'] = '格式错误' return JsonResponse(response) return render(request, 'user/user_detail.html', { 'profile_user': profile_user, }) -
In Python Graphene is there any way to set common graphene fields for class and class arguments at one place instead of defining it at both places?
Please find the link below for the graphql queries https://www.howtographql.com/graphql-python/3-mutations/ -
Internal Server Error when implementing Allauth with Django, Nginx and uWSGI
As of this moment, I have been able to successfully implement google sign into my website while I run it locally on my machine while using a plugin known as Django-allauth. However, when I try moving it over to my AWS lightsail server, I get an “internal server error” the moment the website is attempted to load. To give some information to how we are running the website, I have the backend running through Django, and the frontend which serves the static files running through NGINX. The front end is connected through uWSGI and micro uWSGI to the backend. Also, I have all of this automized through emperor so that I don’t have to constantly run the command to run the server. While doing troubleshooting by entering one line of code at a time for the integration of allauth, I discovered that the error pops up when I try adding “allauth” to installed apps in the settings.py file. Thinking that this was because allauth may not have been installed, I tried installing it again in different versions to see if that would make a difference. It did not. Through the research that I have done, I have found that it … -
IntegrityError Django Postgres when deleting
This is the error, I get it when I delete a TaskList, which is related to ChartDay which is related to MemberRemaining all with on_delete CASCADE, If a delete TaskList the Charts related to it should be deleted, same way happens with ChartDay to Chart and MemberRemaining to ChartDay. Why am I getting this error? insert or update on table "chart_memberremaining" violates foreign key constraint "chart_memberremainin_chart_day_id_e25c792b_fk_chart_cha" DETAIL: Key (chart_day_id)=(7) is not present in table "chart_chartday". class TaskList(models.Model): members = models.ManyToManyField( to=get_user_model(), through='TaskListMemberShip', related_name='task_lists', blank=True ) name = models.CharField(max_length=60, null=True) color = models.CharField(max_length=7, default='#ffffff', null=True) avatar = StdImageField( upload_to=FilePattern(filename_pattern='task_lists/{uuid:base64}{ext}'), variations={ 'normal': {'width': 200, 'height': 200, 'crop': True}, 'small': {'width': 50, 'height': 50, 'crop': True}, }, null=True, blank=True, ) organization = models.ForeignKey(Organization, related_name='task_lists', on_delete=models.CASCADE) auto_created = models.BooleanField(default=False) objects = TaskListManager() class Chart(models.Model): """ Chart model. """ start_date = models.DateField(null=True) end_date = models.DateField(null=True) estimated = models.DecimalField(max_digits=4, decimal_places=1, null=True) task_list = models.ForeignKey( TaskList, related_name='charts', on_delete=models.CASCADE) class ChartDay(models.Model): """ Chart day model. """ date = models.DateField() chart = models.ForeignKey( Chart, related_name='chart_days', on_delete=models.CASCADE ) class MemberRemaining(models.Model): """ Member remaining model. """ member = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null=True ) chart_day = models.ForeignKey( ChartDay, related_name='members_remaining', on_delete=models.CASCADE ) remaining = models.DecimalField(max_digits=4, decimal_places=1, null=True) -
Django how to compare auto_now and auto_now_add
created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) I have used this code to stamp the time. And used the following to compare the two and if it is edited I set to express the updated time as shown below. {% if comment.created_at != comment.modified_at %} <p class="text-muted float-right"><small>Updated: {{ comment.modified_at }}</small></p> {% endif %} However, all of the comments say that it has different created_at and modified_at values even though I did not edit thus the two values would be the same. How could I fix this problem? Thanks. -
Django Model is creating another model after editing it
I made a random number creator in a model and if I make changes on an object Cakmak on the admin page, after saving it, it creates another one with the same name but different no. from django.db import models from random import randint class Cakmak(models.Model): marka = models.CharField(blank=True, max_length=200) model = models.CharField(blank=True, max_length=200) no = models.IntegerField(primary_key=True, unique=True, editable=False, ) def save(self): no = randint(100000, 999999) if Cakmak.objects.filter(no=no).exists(): super(Cakmak, self).save() else: self.no = no super(Cakmak, self).save() def __str__(self): return (self.marka) + (' ') + (self.model) -
How to get queryset with total seconds from sum of DurationField
Suppose, I have a Django model called MyModel like this: class MyModel(models.Model): event_started = models.DateTimeField(default=timezone.now) event_duration = models.DurationField() Now I want to get a queryset with the total seconds grouped by day. The following code returns the queryset with the total duration as timedelta instead of seconds: from django.db.models import Sum qs = (MyModel.objects .annotate(date=TruncDay('event_started')) .values('day') .annotate(total_duration=Sum('event_duration')) .order_by('-day') ) I want to include the total seconds instead of timedelta in the total_duration field of the queryset. How can I do that? -
Deployment Djnago appilication WSGI.py error
As i am deploying my django project on server i get a error Internal server Error but on the production server my code runs bug free and also i tried on server local host 0.0.0.0:8000 but when i create a virtual host and try to access my project from the domain or server ip i get screen with error internal server error. on ther server error logs the error i get is enter image description here I already tried hosting on differnt server modifying wsgi file but same result. -
Getting an error when creating Superuser in Django
File "C:\Users\Name\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\dispatch\dispatcher.py", line 179, in for receiver in self._live_receivers(sender) TypeError: create_profile() missing 1 required positional argument: 'senerd' Getting this error when creating a Superuser in Django with VS Code terminal, did I miss something? anyone else get this before?