Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic value change in for loop in django
Hi how to pass dynamic value in for loop. in value={{ product.size.0.size }} instead of 0 i want to pass index value {% for no_of in product.size %} {{ forloop.counter }} <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label or="">Product Size</label> <input class="form-control" placeholder="Alpha-Numeric characters" required="required" type="text" name="product_size" id="product_size" value="{{ product.size.0.size }}"> <div class="help-block form-text with-errors form-control-feedback"></div> </div> </div> </div> -
missing 1 required positional argument: 'request' django restframework
I was using routers for creating urls now i want to make urls for my api, but problem is, i am getting error createuser() missing 1 required positional argument: 'request'missing 1 required positional argument: 'request',iam getting same error for all my methods inside UserAuthAPIView class, i have already read solutions on stackoverflow but they are not working i my case. I have many methods in UserAuthAPIView class and i want to create urls for all of those. for eg 127.0.0.1:8000/api 127.0.0.1:8000/api/createuser 127.0.0.1:8000/api/login 127.0.0.1:8000/api/<pk>/viewuser urls.py from django.conf.urls import url from UserAPI.api import views from UserAPI.api.views import UserAuthAPIView urlpatterns = [ url(r'^$', UserAuthAPIView.as_view({'get': 'list'}), name='user-list'), url(r'createuser/$', views.UserAuthAPIView.createuser, name='user-create'), #url(r'userlogin/$', views.UserAuthAPIView.userlogin, name='user-login'), ] views.py class UserAuthAPIView(ModelViewSet): queryset = UserModel.objects.all() serializer_class = ListViewSerializer def get_object(self, queryset=None): return self.request.user @action(methods=['post'], detail=False, permission_classes=[AllowAny], serializer_class=UserSerializer) def createuser(self, request, *args, **kwargs): data = request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({ "status" : "user created successfully"}, status=HTTP_201_CREATED) -
How break cycle for with if else statement in django template
I read if else statement in Django docs but i don't understand my case. I have photos list, i want render image if is COVER else i want render static image. This my code {% for x in listing.photos.all %} {% if x.photo_tipo == 'COVER' %} <img src="{{ x.get_thumb }}" alt=""> {% else %} <img src="{% static 'images/about/1.jpg' %}" alt=""> {% endif %} {% endfor %} Result is: an image if x.photo == 'COVER' and a static image for every other photo in the list. I would like to get only one result if the declaration is true or only one static image if it is false -
Aggregate 2 fields in django to count difference between hours
I try to calcul the difference between 2 DateTimeField to know the total work (only hours) per week and I want the same function for days only. Following another Stackoverflow question, I find a aggregation like that: total_hours_per_week = (Timesheet.objects.filter( owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1] ) .annotate( total_hours_per_week=Func(F('end'), F('start'), operator='+', function='age') )) Currently, i don't have the function for days (if you can help me too for her), but this previous agregation return me this error: "no such function: age" you can read bellow my models: class Timesheet(models.Model): owner = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 64, verbose_name = _("Title")) start = models.DateTimeField(verbose_name = _("Start time")) end = models.DateTimeField(verbose_name = _("End time")) allDay = models.BooleanField(blank = True, default = False, verbose_name = _("All day"), help_text = _("If it's a full day work, just click 'Now' for start/end")) week = models.IntegerField(verbose_name = "working week") def __str__(self): return "{}".format(self.title) def save(self, *args, **kwargs): if not self.pk: self.week = datetime.datetime.now().isocalendar()[1] if self.allDay: self.start = datetime.datetime(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day, hour=8, minute=00) self.end = datetime.datetime(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day, hour=17, minute=30) super(Timesheet, self).save(*args, **kwargs) I hope you can help me to solve my … -
in python 3.X I have error with django-admin
I have error with django-admin on IOS by the following I did this steps: 1. conda create --name DjangoProject django 2. y 3. conda info --envs 4. source activate _DjangoProject_ 5. conda install django 6. python 7. 'django-admin.py' startproject `first_project` the last line (7) gave me a message says: (DjangoProject) MacBook-Air:~ ali$ 'django-admin' startproject first_project CommandError: '/Users/al/first_project' already exists My path is: /Users/al/anaconda3/envs/DjangoProject How can I put the project (first_project) on a correct path -
Django div reload - ajax GET after POST does not get latest database model instances
In a chat-like app, I'm using ajax calls to POST a new message and update the messages displayed on the page without reloading the entire page. My ajax call for posting works - a new message instance is created in the database. However, afterwards when I make an ajax call to GET all messages, the new message is missing from the resulting query set. If I refresh the page fully, I can see all the messages, but that's not what I'm after. HTML messages template: {% for message in messages %} <p> {{ message.content }} </p> {% endfor %} HTML chat template: <div id="chat"> {% include "messages.html" %} </div> <form id="post-message-form", method="post" enctype="multipart/form-data"> [my form goes here] </form> JavaScript: $('#post-message-form').on('submit', function(event){ event.preventDefault(); $form = $(this); var data = new FormData($form.get(0)); $.ajax({ url: '/post/a/new/message/', type: 'POST', data: data, success: refresh_div, cache: false, contentType: false, processData: false }) return false; } function refresh_chat(){ $.ajax({ url: '/get/all/messages/, type: 'GET', success: function(json) { $('#chat').html(json['data']); } }) return false; } Views: import json from django.template import loader from .forms import MessageForm # /post/a/new/message/ def post_message(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message = form.save() return HttpResponse( json.dumps({'status': 1, 'message': 'Message posted!'}), content_type='application/json' … -
Can we use angular.js without node?
We are working with Django as a server framework as used JavaScript for client-side scripting? Now we are migrating to Angular4, do we need to run a node.js server with the existing running Django server? -
Using database for forms django
I have an area where teachers can put homeworks for students. Students can see these homeworks and when they click "send homework" button. they can fill a form so Teachers can see the homeworks from admin panel. I have class to post homework. I have 5 fields in class to post homework. Fields = ["student number","Deadline","Lecture","Files"] when students posting their homeworks, I want only use 2 ["student number","files"] fields for the form and I want other fields ["deadline","Lecture"] to be filled automatically from database. What is the best way do it? -
How can I divide a decimalField with a float?
def save(self, *args, **kwargs): self.netto = self.reisepreis / 1.19 self.mwst = self.reisepreis - self.netto super(Assignment, self).save(*args, **kwargs) -
Where is my tasks? (Docker, Celery, Redis)
I have three docker container with Celery, Redis and Django. Celery brocker is redis. When I initialize a task it should be put in redis but when I go to redis-cli and do KEYS * there is nothing. How and Where can I check my queue? -
How to add "+" button in group model (auth_group) in django admin user to add group directly from user add page
Check the image, i tried checking the group admin in django auth.But didnt find anyway. Image-link: https://i.stack.imgur.com/xocVn.png -
Celery shared_task parameters wrong parsing
i'm using celery 4.2.0 with Django to schedule new tasks in rabbitmq and it randomly fails when it comes to parse arguments. My code looks like that: for param in serializer.validated_data['parameters']: run_task.delay(param_name=param) Where parameters is list of int and it is ensured with serializer validation. @shared_task def run_task(param_name: int) -> None: obj= Obj.objects.filter(param=param_name) ... Under UTs when i invoke this run_task with CELERY_TASK_ALWAYS_EAGER=True everything works. On real enviroment this tasks sometimes runs just OK and sometimes it fails with server error: File "/usr/lib/python3.6/site-packages/rest_framework/decorators.py", line 53, in handler return func(*args, **kwargs) File "/opt/app/compliance/jobs/views.py", line 30, in create_task run_task.delay(param_name=param) File "/usr/lib/python3.6/site-packages/celery/app/task.py", line 408, in delay return self.apply_async(args, kwargs) File "/usr/lib/python3.6/site-packages/celery/app/task.py", line 535, in apply_async **options File "/usr/lib/python3.6/site-packages/celery/app/base.py", line 741, in send_task with self.producer_or_acquire(producer) as P: File "/usr/lib/python3.6/site-packages/celery/app/base.py", line 876, in producer_or_acquire producer, self.producer_pool.acquire, block=True, File "/usr/lib/python3.6/site-packages/celery/app/base.py", line 1246, in producer_pool return self.amqp.producer_pool File "/usr/lib/python3.6/site-packages/celery/app/amqp.py", line 612, in producer_pool self.app.connection_for_write()] File "/usr/lib/python3.6/site-packages/kombu/utils/collections.py", line 34, in __getitem__ h = eqhash(key) File "/usr/lib/python3.6/site-packages/kombu/utils/collections.py", line 25, in eqhash return o.__eqhash__() File "/usr/lib/python3.6/site-packages/kombu/connection.py", line 629, in __eqhash__ repr(self.transport_options)) File "/usr/lib/python3.6/site-packages/kombu/utils/collections.py", line 16, in __init__ self.hashvalue = hash(seq) TypeError: unhashable type: 'set' I understand error itself but how come it appears here when I pass only one simple … -
What Query should I make to prefetch my data from first model to get filled when my form for second model opens
models.py class Appname(models.Model): name=models.CharField(max_length=150,blank=False,null=False,help_text='Add your new App') def __str__(self): return self.name def get_absolute_url(self): return reverse("dashapp:view") class Adspace(models.Model): name=models.ForeignKey(Appname,related_name='adspaces', null=True, default=None,on_delete=models.CASCADE) ad_space=models.CharField(max_length=150,blank=False,null=False) def __str__(self): return self.ad_space def get_absolute_url(self): return reverse("dashapp:view") Query to make I create a form using CreateView for both the models. For First model i save the appname and then I create a listview of app names Using ListView and display them. When i click on one of the app from the displayed list it takes me to the next form which is for the next model Adspace . Now I want as my form opens for second model the name section gets autofill with the name of the app with which i clicked to reach on that form.What Query should i make to make it possible.Please Explain it with your answer. -
displaying the field data to django template if a column already exist or dash if the field does not exist in the database
am using an users api to display all user in a django template.what i want to implement is to first check if those users already exist in the local and if they exist display their roles on the other hand if the user Does not exist you save the user and select what role they fall and display to front-end -
Wagtail - passing queryset to inline
I am facing a problem from days, but, no matter how much I keep searching, I could not find any solution here or anywhere in the web. So here it is: I am developing a website for some sort of institution which offers teaching courses. I am using WAGTAIL and I am structuring the classes this way: class Course(Page): ... content_panels = Page.content_panels class Exam(Page): #fields content_panels = Page.content_panels + [ #fields InlinePanel('preparatory_exam', heading='Preparatory Exams'), ] class PreparatoryExam(Orderable): page = ParentalKey('Exam', on_delete=models.CASCADE, related_name = 'preparatory_exams', ) name = models.ForeignKey( Exam, on_delete=models.CASCADE, blank=True, null=True, related_name = 'preparatory_exam', ) I also structured the ADMIN section PAGES this way: \COURSE_1_PAGE \-----------\EXAM_1 \-----------\EXAM_2 \------------------\Prep exam 1 \------------------\Prep exam 2 \-----------\EXAM_3 ... \COURSE_2_PAGE \-----------\EXAM_1 \-----------\EXAM_2 \-----------\EXAM_3 .... So, the problem is: is there any way to pass a custom queryset to the inline dropdown box when choosing the preparatory exams for a certain one? What I want is to restrict the set to the exams present in the same Course. I could do that with a limit_choices_to added to the foreignkey field, but AFAIK, it would be a "static" filter, because it would be related to the model and not to its istances, so it … -
descriptor 'strftime' requires a 'datetime.date' object but received a 'bool'
I have this problem with passing data to excel in python 2.7. I want to allow the specified special characters to be passed in an excel cell, but somehow I can't understand the flow. I have the comment and comment_date fields, the concatenation of which will pas in an excel cell. The comment field contains special characters which I want to be allowed. My code is: str= dataset[id]['actions'][0][7] comment = re.sub('^[a-zA-Z0-9!ËëÇç€%@#$&()\\-_`.+,/\"]*$', '', str) comment_date = dataset[loan_id]['actions'][0][9] if comment : comment = comment + " Commented on: " + datetime.datetime.strftime(comment_date,"%B %d, %Y") print comment except IndexError as e: comment = 'no comment added today' cell = '%s%s' % (get_column_letter(col), row) ws.cell(cell).value = comment -
How to handle the for loop in a django formset?
the problem with my formset is that it does not take into account the amount of the modified article in the for loop, and i would also like to know how can i get the total sales perform. thank you views.py : def post(self, request): vente_formset = self.VenteFormSet(self.request.POST) if vente_formset.is_valid(): for temp in vente_formset: vente = temp.save() article = vente.id_article print('article de départ', article.quantite) entre = article.quantite entre -= vente.quantite_v if entre >= 0: article.quantite -= vente.quantite_v article.save() print('article final', article.quantite) else: vente.delete() messages.warning(request, 'Stock insuffisant pour cette opération!') else: messages.warning(request, 'Formulaire invalide!') return render(request, self.template_name, {'form': self.VenteFormSet()}) in terminal pycharm : -->article debut 15 .article fin 10 -->article debut 15 .article fin 8 what I wish to have : -->article debut 15 .article fin 10 -->article debut 10 .article fin 3 -
django from_db __init__() takes 1 positional argument but 26 were given
The reason mybe I upgrade the wagtail. I try to find the cause, but failed. The Error Page address enter image description here -
Django- ValueError [The User couldn't be created because the data didn't validate]
I used extend user model based on this tutorial.When I submit the registration form this error occurs.This errors shows for both time I use is_active() and is_active in my code. How to resolve this error? Error registration form Here is my code: views.py from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login from django.views import generic from django.views.generic import View from .forms import UserForm,ProfileForm class UserFormView(View): user_form_class = UserForm profile_form_class= ProfileForm #display a blank form def get(self , request): user_form = self.user_form_class(None) profile_form = self.profile_form_class(None) return render(request, 'website/registration_form.html',{ 'user_form':user_form, 'profile_form':profile_form }) #process form data def post(self, request): user_form = self.user_form_class(request.POST) profile_form = self.profile_form_class(request.POST) user= user_form.save(commit= False) if user_form.is_valid() and profile_form.is_valid(): password= user_form.cleaned_data['password'] username = user_form.cleaned_data['username'] user.set_password(password) user_form.save() profile_form.save() # auto login user = authenticate(username =username, password = password) if user is not None: if user.is_active(): login(request,user) return redirect('website:index') return render(request, 'website/registration_form.html',{ 'user_form':user_form, 'profile_form':profile_form }) -
Django one model for two model form
i am newbie on Django. I have one model.Two forms where different url. I have two different table on my database when i fill forms. I want to one table on the database. What can i do? Here is my forms; class customerForm(forms.ModelForm): class Meta: model = customerInfoModel fields = ( "customerName", ) class addCustomerForm(forms.ModelForm): class Meta: model = customerInfoModel fields = ( "user", "passwd", ) And here is my model; class customerInfoModel(models.Model): customerName = models.CharField(max_length = 100) user = models.CharField(max_length = 50) passwd = models.CharField(max_length = 20) -
How to upload form data with image file to django model using ajax
I want to upload image file with some other data to django database using ajax. But every time i am doing this by using formData.But formData is always empty when debugging.And my serializer not validating.Please help me to resolve this problem.is there any other way to send image file to server. function add_bike_model(btn){ debugger; var data=new FormData() data.append('image',$("#bike_model_name")[0].files[0]) // BikeModels = document.getElementById('bike_model_name').value; // var e = document.getElementById("city_drop"); // var strUser = e.options[e.selectedIndex].value; // image = document.getElementById('img_file').value; // e.preventDefault(); // var data = new FormData($('#form').closest('form')[0]); console.log('hello') data = {"CityForCars":strUser, "BikeModels": BikeModels, 'Image':image} $.ajax({ type: 'POST', enctype: 'multipart/form-data', processData: false, contentType: false, cache: false, url: baseUrl + "/bike_model/", data:new FormData($("#moment-pane-upload-form")[0]), success: function(data) { console.log('sucessfully done') console.log(data) window.location.href = baseUrl + "/bike_model/"; } }); } <form name="add_model_form" id="add_model_form" enctype="multipart/form-data" class="comon-form" method="post"> <h3>ADD BIKE MODELS</h3> <div class="col-md-6"> <div class="avatar-upload"> <div class="avatar-preview"> <div id="imagePreview" style="background-image: url(/static/Chatbot_Dashboard/img/logo/logo.png);"></div> <img id="bike_image" src=""> </div> </div> </div> <div class="col-md-6"> <div class="form-group-inner"> <label>Bike Model Name <em>*</em></label> <input class="form-control" placeholder="" type="name" id="bike_model_name" required=""> </div> </div> <div class="col-md-6"> <div class="form-group-inner"> <label>City <em>*</em></label> <select style="width: 100%; background: #fff; padding: 7px;" id="city_drop"> <option value="" selected="selected">Select City</option> {% for city in city.car_city %} <option value="{{city.id}}">{{city.CityForCars}}</option> {% endfor %} </select> </div> </div> <div class="col-md-6"> <div class="form-group-inner"> <label>Bike … -
Django background task - schedule integrity error
I am trying to use the schedule decorator to schedule a background task using django-background-tasks module. However, when i run this particular piece of code, it shows the following error. Code: @background(schedule=1) def function(s,id): return some_return_value Error: IntegrityError at url null value in column "repeat" violates not-null constraint DETAIL: Failing row contains (169, function, [["s", 57], {}], a24y78123j1b23j1321232aebc9762c0fa2, null, 0, 2018-11-21 07:29:28.99142+00, null, null, null, 0, null, , null, null, null, null). The error is in the background_task table(repeat column) but I am not sure why this pops up. Yes, I understand that it tries to insert a null value in a not null column, but I have never got such an error while using background task before. -
Django send context data from template to view (request.post)
I have a page with forms which is filled out by the user. In this page there is a check box, if the checkbox is valid, I need to execute a method and to display result of action, but after that in this page a post the inquiry is cleaned as it is possible to add data from a template to a post inquiry template -> view -> if checkbox true -> show new page with result -> then save all data from 1st page template (request.POST is empty) how i can add template data (context) to request.POST def add_data(request): # takes data from template if request.method == "POST": #checkbox checking interpolation_method = request.POST.get("interpolation_method",default=None) if interpolation_method: # this method work with data from template forms data = Interpolation(data, interpolation_method) context = { 'd' :data, } return render(request,'data/interpolation.html',context) than i show our next page with the processed data def int_data(request): # Our next view to get user desicion from second template page if request.method == "POST": #request.POST is empty return JsonResponse(request.POST) how i can add context data (from view 1) to request.POST -
Set specific group of Django user as celery worker
I need to make a specific group of Django user(group : delivery person) as celery worker. Whenever any registered django user from that specific group logs in, they can pick task from the celery queue and complete. As soon as one user completes a task, it must be dequeued from the queue and asynchronously it should not be visible to the next logged in user from that group. -
How to make form with checkbox in Django to select the list of items?
I am trying to make a form which consists list of foods with name, price and quantity. From which I can select the multiple items using check box and can submit after selecting. And also how can I display the selected items on the admin page along with name that has been submitted previously in loginform. Please give the full explanation.