Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework partial update with where query
I just want to update two fields of table where id_payment = 1. How to do it? It showing me the error bellow. IntegrityError at /receivePendingPayment/ (1048, "Column 'bank_id' cannot be null") #View @permission_classes([IsAuthenticated]) @api_view(['PATCH']) def receivePendingPayment(request): id_payment = request.data['id_payment'] data = {'accountant_received_by': request.user.id, 'accounts_status': 'Received'} BankPaymentHistory.objects.filter(id=id_payment) serializer = BankPaymentUpdateSerializer(data=data, partial=True, many=False) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #Serializer class BankPaymentUpdateSerializer(serializers.ModelSerializer): class Meta: model = BankPaymentHistory fields = ('accounts_status','accountant_received_by') #Model class BankPaymentHistory(models.Model): activation_enum = (('Active', 'Active'), ('Deactive', 'Deactive')) accounts_status_enum = (('Pending', 'Pending'), ('Received', 'Received')) bank = models.ForeignKey(Bank, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) file = models.ForeignKey(File, on_delete=models.CASCADE) salesperson = models.ForeignKey(SalesPerson, on_delete=models.CASCADE) paymentmode = models.ForeignKey(PaymentModes, on_delete=models.CASCADE) amount = models.PositiveIntegerField() chequeno = models.CharField(max_length=50, unique=True) chequedate = models.DateField() paymentdate = models.DateField() remark = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) accountant_received_by = models.ForeignKey(User, related_name='%(class)s_accountant_received_by', on_delete=models.CASCADE, null = True) accountant_received_date = models.DateTimeField(default=datetime.now) create_date = models.DateTimeField(default=datetime.now) activation_status = models.CharField(max_length=20, choices=activation_enum, default='Active') accounts_status = models.CharField(max_length=20, choices=accounts_status_enum, default='Pending') -
What value should I pass for the current user to my API - Django
I am having trouble connecting the currently logged in user to an Item object I'm storing in the database in an auction app I'm building. Item model class Item(models.Model): title = models.CharField(max_length=100) timestamp = models.DateTimeField(default=now, editable=False) condition = models.CharField(max_length=50) description = models.TextField() owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='owner' ) owner_email = models.CharField(max_length=100) owner_telephone = models.CharField(max_length=20, blank=True) location = models.CharField(max_length=200) def __str__(self): return self.title View for creating a new auction item def new_auction_view(request): form = ItemForm() if 'token' in request.session: token = request.session['token'] if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): item_obj = { "title": form.cleaned_data.get('title'), "condition": form.cleaned_data.get('condition'), "description": form.cleaned_data.get('description'), # I'm not sure what to pass in for 'owner' "owner": request.user.id, "owner_email": form.cleaned_data.get('owner_email'), "owner_telephone": form.cleaned_data.get('owner_telephone'), "location": form.cleaned_data.get('location'), } item_response = requests.post( f'{server}/api/items/', headers={ 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }, data=json.dumps(item_obj) ) item = item_response.json() auction_response = requests.post( f'{server}/api/auctions/', headers={ 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }, data=json.dumps({ "item": item['id'], "starting_price": float(form.cleaned_data.get("price")), }) ) messages.info(request, 'Item successfully created') form = ItemForm() else: print(form.errors) for error in form.errors: messages.info(request, error) context = { 'page_header': 'Register Item', 'page_title': 'New Auction', 'form': form } return render(request, 'forms/auction-form.html', context) else: return redirect('/login/') I've tried a number of things: The request.user object raises a User is … -
How to start django project from other python script
How can I start my django project from another python file? Directory structure |-- interface |-- ... |-- manage.py |-- script.py How can I start my interface django project from script.py -
how do i add django language translater to my project
i am trying this command to my ubuntu terminal as virtualenv e.g django-admin makemessages -l fi but its giving an command error (env3) mosestechnologies@mosestechnologies-HP-ProBook-640-G1:~/Documents/mosess projects/fourtyq/fourtyq$ python manage.py makemessages --all CommandError: errors happened while running xgettext on ./env3/bin/activate_this.py ./env3/bin/django-admin.py setting.py LOCAL_PATHS = ( os.path.join(BASE_DIR, "locale"), ) LANGUAGES = [ ('en', 'English'), ('ru', 'Russian'), ] directories assets tempplate locale myproject projectapp manage.py -
How do you pass a UserCreationForm field into input field by just using template?
I'm trying to use bootstrap's input style and wondering if I can pass user creation form fields onto input without having to create a custom class. I've tried this which didn't work: <div class="form-group"> <label for="username">Username</label> <input name="{{ form.username }}" type="text" class="form-control"> </div> -
How to handle accordion in Django,
I set all thins in models, views and template but I don't know how to handle the accordion when I click it, open all tab. Please help me -
Populating drop down list from a database
Want to retrieve data from the database in this department ID field which is on another model. -
Django - Annotating multiple Sum() object gives wrong result
models.py looks like this class Channel(Model): name = CharField() class Contract(Model): channel = ForeignKey(Channel, related_name='contracts') fee = IntegerField() class ContractPayment(Model): contract = ForeignKey(Contract, related_name='payments') value = IntegerField() When I query a model: Channel.objects.annotate(pay=Sum('contracts__fee')) It returns: 75000. And Its correct but when I query like this: Channel.objects.annotate(pay=Sum('contracts__fee')) .annotate(paid=Sum('contracts__payments__value')) And it returns: pay: 96000, paid: 33000. As you can see the pay is changed. What is going on here? I read the ticket #10060 but no luck. -
Internal Server Error: Django, uWsgi, Nginx, Pyenv
I am trying to serve a Django application using Nginx and uWsgi I followed https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04 https://serverfault.com/questions/775965/wiring-uwsgi-to-work-with-django-and-nginx-on-ubuntu-16-04 for same. platforms.ini file [uwsgi] project = platforms base = /home/ubuntu chdir = /home/ubuntu/platforms/ home = /home/ubuntu/.local/share/virtualenvs/platforms-hQBv-BwK/ module = platforms.wsgi:application master = true processes = 5 logger = file:/home/ubuntu/platforms/logs/uwsgi.log socket = %(base)/%(project)/%(project).sock chmod-socket = 666 uwsgi.service file [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/home/ubuntu/.pyenv/versions/3.7.6/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target vacuum = true When I run the application using below command uwsgi --http :8000 --home /home/ubuntu/.local/share/virtualenvs/platforms-hQBv-BwK --chdir /home/ubuntu/platforms -w platforms.wsgi it works fine. python manage.py runserver 0.0.0.0:8000 works fine But when i run using ini file I get internal server error also in the logs i am getting --- no python application found, check your startup logs for errors --- [pid: 6752|app: -1|req: -1/7] xx.xxx.xxx.xx () {44 vars in 904 bytes} [Wed Mar 11 07:12:50 2020] GET /admin/ => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) announcing my loyalty to the Emperor... I am unable to figure out what could be issue. Please Help. -
how to change "" in json to python
i have a json data like this: { "@context": "http://schema.org", "@type": "NewsArticle", "mainEntityOfPage":{ "@type":"WebPage", "@id":"https://cafef.vn/cuu-ceo-fpt-nguyen-thanh-nam-cac-chuyen-gia-smart-city-sao-khong-phat-ro-len-vi-co-co-hoi-giai-bai-toan-nuoc-song-da-20191108064344921.chn" }, "headline": "Cựu CEO FPT Nguyễn Thành Nam bật mí về tổ chức "từ thiện cho người sắp giàu"", but in the headline has "" which not allowed in python , so when i import json and get this data , i have an error JSONDecodeError at /scrape/ Expecting ',' delimiter: line 9 column 70 (char 404) how can i change "" in json data to python ?? -
How to get the checked objects immediately in django view with ajax?
I am very new to ajax. Here I have a django form and inside the form there is a form group of checkbox. What I want here is, from the checkbox if the user check some user object I want to get it in the django view immediately before the form submit. And if the the user uncheck this It should be removed from django view also. How can I do this ? After form submit it works fine but I want to get the checked user before the form submits.So I think in this case ajax will be required. But I am very beginner in ajax so I got stuck here. template <div class="form-group"> <div class="checkbox"> <input class="checkbox1" name="users" type="checkbox" value="{{user.pk}}" id="user{{user.pk}}"/> <label for="user{{user.pk}}"></label> </div> </div> jquery <script> $(function(){ var checked_lists = []; $(".checkbox1:checked").each(function() { checked_list.push(this.value); }); }); </script> views print('us',self.request.POST.getlist('checked_lists')) -
Django redirect to specific URL after Registration
Good day. I'm trying to redirect a user to specific url which in my case is rootPath/dashboard/ But when the user registers i get redirected to /user/register/dashboard/ I have searched other stackoverflow topics on same problem but they didn't resolve my problem. I have defined these settings in settings.py LOGIN_URL = 'user/login/' LOGOUT_URL = 'user/logout/' LOGIN_REDIRECT_URL = 'dashboard/' views.py def register(request): form = RegisterForm(request.POST or None) if request.POST: if form.is_valid(): data = form.cleaned_data email = data['email'] pwd = data['password'] user = User(email=email, password=pwd) user.save() return redirect(settings.LOGIN_REDIRECT_URL) return render(request, 'registration/register.html', context={'form': form}) @login_required def dashboard(request): return render(request, 'user/dashboard.html') urls.py urlpatterns = [ path('user/login/', CustomLoginView.as_view(), name='login'), path('user/logout/', auth_logout, name='logout'), path('user/register/', register, name='register'), path('dashboard/', dashboard, name='dashboard') ] register.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container text-center"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <h1 class="h3 mb-3 font-weight-normal">Register</h1> <form class="form-signin" action="." method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Register" class="btn btn-primary"></p> {# <a href="{% … -
Exporting data from mysql workbench into excel
i'm creating a tool using django in which i'm using data from the database.I need an export option from which i can export data from the mysql database into a csv file. can anyone please guide me thorugh it ? -
Resources for learning testing django channels?
I am writing tests for project that uses channels + DRF. I have to test huge user use-case scenarios. I read official docs and searched a lot but it wasn't enough. Can you recommend articles or smth like that? -
MultiValueDictKeyError at /add, Request method : GET
this is my views.py file from django.shortcuts import render def home(request): return render(request, 'home.html',{'name':'irtiza'}) def add(request): val1 = int(request.GET['num1']) val2 = int(request.GET['num2']) res = val1 + val2 return render(request, "result.html",{'result': res}) when i run this code i am getting this error, error then i tried this code: def add(request): val1 = int(request.GET.get(['num1'])) val2 = int(request.GET.get(['num2'])) res = val1 + val2 return render(request, "result.html",{'result': res}) this error occur. enter image description here what should i do now to resolve this error. This is just a simple function to ADD two numbers.Kindly help me. -
Django WSGI cannot be loaded
I am trying to start my first django app with Apache2 (2.4.18). Unfortunately, I got a bit stuck. This is the error code i get in my log file: [Wed Mar 11 06:31:32.668937 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] mod_wsgi (pid=14849): Target WSGI script '/home/nigsdtm/srv/portal/mysite/wsgi.py' cannot be loaded as Python module. [Wed Mar 11 06:31:32.669026 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] mod_wsgi (pid=14849): Exception occurred processing WSGI script '/home/nigsdtm/srv/portal/mysite/wsgi.py'. [Wed Mar 11 06:31:32.669734 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] Traceback (most recent call last): [Wed Mar 11 06:31:32.669779 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] File "/home/nigsdtm/srv/portal/mysite/wsgi.py", line 16, in <module> [Wed Mar 11 06:31:32.669783 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] application = get_wsgi_application() [Wed Mar 11 06:31:32.669789 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Wed Mar 11 06:31:32.669792 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] django.setup(set_prefix=False) [Wed Mar 11 06:31:32.669809 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 24, in setup [Wed Mar 11 06:31:32.669812 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] apps.populate(settings.INSTALLED_APPS) [Wed Mar 11 06:31:32.669817 2020] [wsgi:error] [pid 14849:tid 140433834096384] [remote 10.150.29.220:33874] File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 112, in populate [Wed Mar 11 06:31:32.669820 2020] [wsgi:error] [pid … -
how to fetch data from two different models in single api call in django rest frame work? is it possibel if yes then how?
How I can add and fetch two different models in a single API call. urlpatterns = [ path('users/<int:id>/', GenericAPIView.as_view()), path('users/', GenericAPIView.as_view()), ] # User Serializer class userSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' # usersdata serializer class userdataSerializer(serializers.ModelSerializer): class Meta: model = UserData fields = '__all__' this is my views.py this is views.py code. class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin): serializer_class = userdataSerializer, userSerializer queryset = UserData.objects.all() lookup_field = 'id' def get(self, request, id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self, request): return self.create(request) def put(self, request, id=None): return self.update(request, id) How I can add and fetch two different models in a single API call. How I can add and fetch two different models in a single API call. How I can add and fetch two different models in a single API call. How I can add and fetch two different models in a single API call. How I can add and fetch two different models in a single API call. -
updating multiple rows in django database
I have 5 records in the database and want to update all the values of a particular field called "ret_name". For that, I have written the following code in views: def retap_list(request, date_selected): obj = ret_tbl.objects.filter(curr_date = date_selected) obj[1].update(ret_name = "change") print(obj[1].ret_name) But it is showing me the following AttributeError: "'ret_tbl' object has no attribute 'update'" How should I update each row one at a time? -
how to create filtering by argument inside the model and not through id
need to blow filtering by post field here is my code enter code here class Comment(models.Model): post = models.ForeignKey('AnimalInfo', related_name='comments',on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) class CommentView(viewsets.ViewSet): permission_classes = [IsAuthenticated] serializer_class = CommentSerializer queryset = AnimalInfo.objects.all() def retrieve(self,request,pk=None): user = CommentSerializer(self.queryset) return Response(user.data) class CommentSerializer (serializers.ModelSerializer): class Meta: model =Comment fields='all' thank you in advance -
How request_id is being called at django tutorial 03
I am new to Django. I am learning it from Django's official website (making voting app). I am not stuck process wise but want to understand why in polls/view.py request_id call is working(we have not imported any class then how does it know about this particular id). https://docs.djangoproject.com/en/3.0/intro/tutorial03/#writing-more-views the only packages installed are from django.shortcuts import render from django.http import HttpResponse Please help me understand this logic. Thanks -
How to upload file in Xhtml?
I wish to upload file and perform some task on that file using django upload api, i uploaded a file or more than a file from postman ,that is working properly . i did same process using xhtml file but that is not working . Please help me anyone. index.xhtml <form id="submit_form" action="http://xx.xxx.xx.xxx:xxxx/upload" method="POST"> <label for="ubutton">Upload</label> <input type="file" id="file" name="file" multiple="multiple" /> <label for="utext">Project Name</label> <input id="utext" type="text" name="projectname" placeholder="enter project name"/> <label for="utextarea">Entity Names</label> <input id="utextarea" type="textarea" name="entitynames" placeholder="Enter camma separated values"/> <input type="submit" value="Submit" id="submit" onclick = "return myfunction(this)"/> <span id="error_message" class="text-danger"></span> <span id="success_message" class="text-success"></span> </form> views.py @csrf_exempt def upload(request): if request.method == 'POST': print("Inside post request") projectname = request.POST.get('projectname') entitystr = request.POST.get('entitynames') uploaded_file=request.FILES files=uploaded_file.getlist('file') fs=FileSystemStorage() filepaths=[] for file in files: filename = fs.save(file.name, file) file_path = os.path.abspath("media/"+filename) filepaths.append(file_path) extract_text(filepaths,fs) textfilepath=r'/home/sharmila/test/brat-v1.3_Crunchy_Frog/prediann/text_files'+"/" preprocessing(textfilepath,projectname) write_config(entitystr,projectname) return redirect("http://xx.xxx.xx.xxx:xxxx/index.xhtml#/") I got projectname and entitysrt values from xhtml , but files variable is empty dictionary . How can i upload file ? -
How can I use dropdowns and according to the dropdown I provide further details
I used ng-if using radio buttons for yes or no selection and according to that provided the details but how can I use dropdowns and according to each deopdown selection I show the details like if I select Near Metro from the dropdown and I show the available places and when I select the place again from the dropdown I show the post office pincode -
question about switching from heroku to a public host
my site is in Heroku is what if I launch it in public hosting the images work or it is necessary to open an Amazon account. image and video in the locale they work and all my files are put in a media document in the root I use whitenoise in production -
Django model has several booleanfields and I want to put them into the same checkbox
As title This is my model.py A = models.BooleanField(_('A'), default=True) B = models.BooleanField(_('B'), default=False) C = models.BooleanField(_('C'), default=False) How to put them in the same checkbox by forms.py? thx -
Problem with upload FileField and ImageField in new django 3.0.4
I'm with a big issue about django 3.0.4. I'm using virtualenv with python3.6.9 and django==3.0.4, In my models at upload process the picture be saved in correct folder, but return error 500 on server and the data field (title, category, file_attach) aren't saved in database. If I change django to version==2.2 in virtualenv the picture be stored and save in database without errors. Some bug or hack in django==3.0.4? The project was created in django 3 but work fine in 2.2. Some solution?