Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove Queryset From Output
How do i remove queryset from the output so it just says teacher ? form = PofileUpdateForm(instance=request.user.profile) user_id = request.user.id get_user = User.objects.get(pk=user_id) access = get_user.groups.all() print(access) context = ({'form': form,'access': access, }) return render(request, 'users/profile.html', context) Outputs: <QuerySet [<Group: Teacher>]> -
In django unittests how do you specify a database that you are modifying?
In django, while testing, how do you resolve the error 'Database connections to {blah} are not allowed in this test. Add {blah class} to ensure proper test isolation and silence this failure'? -
django and js imports
i use django and want to use javascript locally on my computer. the javascript has some imports. normally I should build them with npm and then I can use them. how does this work with the command: python manage.py runserver I find it a bit ugly to push the links to the html file for test purposes. -
My collapsible button makes my other buttons stop working
I have the following code: Template: <div id="formwrapper" class="FwCenterShort"> <form method="post" enctype="multipart/form-data"> {% csrf_token %}> <center> <button type="submit" name="pass" id="pass">Pass</button> <button type="submit" name="fail" id="fail">Fail</button> <button type="button" id="check" class="collapsible">Check Needed</button> <div class="content"> {{ form.Comment.label_tag }} {{ form.Comment }} {{ form.Comment.errors }} <button type="submit" id="submitCheck">Send Comments</button> </div> </center> </form> </div> <script> var allHeights=0; var contents = document.getElementsByClassName("content"); var j; for (j=0; j<contents.length; j++) { var h = document.getElementsByClassName("content")[j].scrollHeight; allHeights+=h; } var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.maxHeight == allHeights + "px") { content.style.maxHeight = "0px"; } else { content.style.maxHeight = allHeights + "px"; } }); } </script> Form: class GroupReportForm(forms.ModelForm): class Meta: model = GroupReport fields = {'Date', 'Comment', 'Signature'} labels = {"Date": "Date (YYYY-MM-DD)"} def __init__(self, *args, **kwargs): super(GroupReportForm, self).__init__(*args, **kwargs) self.fields["Date"].widget = forms.HiddenInput() self.fields["Date"].required = False self.fields["Signature"].widget = forms.HiddenInput() self.fields["Signature"].required = False self.fields["Comment"].required = False Model: class GroupInspection(models.Model): InspectionID = models.AutoField(primary_key=True, unique=True) GroupID = models.ForeignKey('PartGroup', on_delete=models.CASCADE, null=True, unique=True) @classmethod def create(cls, groupid): inspection = cls(GroupID = groupid) return inspection def __str__(self): return str(self.InspectionID) class GroupReport(models.Model): ReportID = models.AutoField(primary_key=True, unique=True) InspectionID = models.ForeignKey('GroupInspection', on_delete=models.CASCADE, null=True) Date = models.DateField(auto_now=False, auto_now_add=False, null=True) Comment = models.CharField(max_length=255, … -
How to queryset inheritance model django?
I have models class Parent(Model): pass class Child1(Parent): att1 = CharField() class Child2(Parent): att2 = CharField() class Final(Model): parent = ForeignKey('Parent', related_name="final") I need to queryset Final.objects.filter(parent__att1='abc') But just Child1 inheritance Parent has att1. How to queryset att1 in Child1 not Child2? -
Dynamic and custom Urls
I'm currently working at my first Django REST Api and I have a question about the routing. I have a JSON and the short form looks like this: { "name": "Summer Festival", "date": "2020-01-05", "deadline": "2020-01-01", "address": "Fantasy Road 50", "postcode": 12346, "location": "New York", (...) } I use this ViewSet: class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer and this serializer: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = "__all__" My urls.py: router = routers.DefaultRouter() router.register("events", views.EventViewSet) urlpatterns = [ path('', include(router.urls)), path( 'events/location=<str:address>&from=<str:from>&to=<str:to>', views.EventViewSet.as_view({"get": "list"})), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] The scenario: On my frontend is a form where you can pick your postcode and a date range. When the user just inserts his postcode he gets all events up today and the url should look like this: http://127.0.0.1:8000/events/postcode=12345 When the user picks a from date and postcode it should like this: http://127.0.0.1:8000/events/postcode=12345&from=2019-01-01 With a daterange + postcode like this: http://127.0.0.1:8000/events/postcode=12345&from=2019-01-01&to=2019-02-01 The url should be dynamically build. The second path in my urls.py code snippet is a workaround but this urls isn't dynamically created. My first idea was to just set the values null but the result is just a large url with no information. I already tried … -
How to set SMTP settings for each email on the fly?
We can configure SMTP settings globally by defining these variables in the settings.py: EMAIL_HOST = 'SMTP_HOST' EMAIL_PORT = 'SMTP_PORT' EMAIL_HOST_USER = 'SMTP_USER' EMAIL_HOST_PASSWORD = 'SMTP_PASSWORD' I want to set these parameters different for each email. How can I define the SMTP settings on the fly? I mean just before the sending. -
django - html || for loop issue
i want to display all the items from the list 'sum_list' in the html table. but one item get displayed in the table. i know i have to use for loop in html to display all the items and i have tried but failed to do so. i am working with django and below is my views.py code in which sum_list is defined. detail = Sale_detail() sum_list= [] x = datetime.datetime.now() month = x.strftime("%B") path = r'\\10.9.32.2\adm\Ash\FY 2019-20\Sale detail sheet\SALE DETAIL SHEET JANUARY 2020.xlsx' customers1 = [20,31,28,27,17,46,13,15,14,37,100125,100051,100062,100087,100072,100071,100070,100057,100056,100066,100068,100086,100091,100103,100126,100131,100145,100150,100152,100140,100165,100180] customers2 = [ 'Asian Cements','Asian Fine', 'UTCL Roorkee', 'UTCL Bagheri','UTCL Panipat','UTCL Sikandrabad','Ambuja Nalagargh','Ambuja Ropar','Ambuja Roorkee','Ambuja Dadri','ACC LTD','Fateh','Everest','Hemkund Sahib','Rakesh kumar','Amritsaria','Jai Shiv shankar','Ramjee','Paras','Manju','Sachin','R.S.Green','BTS','S.A.Bricks','Royal','M.M. Concrete','Fairmont','Aniket','A One','ONS','NTC','Guru Teg Bhadar'] customers2_length = range(0,len(customers2)) today = date.today() d1 = today.strftime("%d-%m-%Y") tarik = d1 df = pd.read_excel(open(path,"rb"),sheet_name= month.upper(), index_col=None, header= None) for (i,j) in zip(customers1, customers2_length): ab = df[df[2] == i] a= (ab[ab[6]== tarik][8]).sum() b = round(a,2) i = customers2[j] if b != 0: sum_list.append([i, str(b)]) # print(sum_list) for i,j in sum_list: detail.customer = i detail.qty = j return render(request,'index.html', {'x': detail}) and this my html part to display item in shape of table <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">Customer</th> <th scope="col">Quantity (MT)</th> </tr> </thead> <tbody> <tr> … -
How CustomUser login view should be realised
I have custom user model MyUser class MyUser(AbstractBaseUser): email = models.EmailField(_('email adress'),unique=True) I created login form CustomAuthenticationForm which inherit from built-in AuthenticationForm from django import forms from django.contrib.auth.forms import AuthenticationForm from .models import MyUser class CustomAuthenticationForm(AuthenticationForm): class Meta: model = MyUser fields = ('email',) Now i want to create login view where i can check user inputed credentials and authenticate user. To accomplish this task i bit confused by misunderstanding how to properly do it. def login(request): if request.method == 'POST': form = CustomAuthenticationForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] #how to check that user inputed #data is valid. Is AuthenticationForm have any method to check password validness user = authenticate(email=email,password=password) else: form = CustomAuthenticationForm() return render(request,'registration/loginn.html',{'form':form}) Here is my question is in built-in AuthenticationForm have any method which provide functionality to check user password validity. If no can anyone suggest any appropriate solution to check password than authenticate user -
how to make django serve non static js files?
My python backend server serves a react application as static files. In react, everything inside the src directory is bundled when we build the app, however, there is one javascript file outside the src, in the public directory, that I left there because I want to be untouched after the build. the reason I did this, is because inside the src code, I create Workers, and to create workers we have to specify the url of the worker file. This file is called worker.js, it remains untouched after the build, but after deploying the backend, the frontend cannot access the /worker.js url because apparently django only serves static files, so /worker.js is not recognized and the index.html is returned instead. How can I make it possible to access this non-static js file? -
Adding extra field to resolver in django-graphene
I am following the tutorial steps in the django graphene documentation. I am trying to customise fields with an extra_field but the extra_field will simply not show up in the response. Here is the code I use: class ConversationNode(DjangoObjectType): class Meta: model = Conversation filter_fields = ['title',] interfaces = (relay.Node,) extra_field = String() def resolve_extra_field(self, info): return 'hello!' I am also unable to add extra_field to the fields or filter_fields option as this will result in the following error: TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: extra_field All the other model fields are included in the response as expected. Do you guys know what I am doing wrong? -
Django forms checkbox selection does not work
i have a django form with a check box for "Accept terms of service" but if i check it or not my app block the request with the message "you have to accept oyr Terms of service" Here my code: forms.py class ProfileModelForm(ModelForm): class Meta: model = UserProfile fields = ['u_fullname', 'u_job', 'u_country', 'u_email', 'u_terms', ] def clean(self): cleaned_data = super(ProfileModelForm, self).clean() u_fullname = cleaned_data.get('u_fullname') u_job = cleaned_data.get('u_job') u_country = cleaned_data.get('u_country') u_email = cleaned_data.get('u_email') u_terms = cleaned_data.get('u_terms') if not u_terms: raise forms.ValidationError("Please read and accept our Terms of Service") if not u_fullname and not u_job and not u_country and not u_terms: raise forms.ValidationError('You have to write something!') return cleaned_data field u_terms ids a Boleanfield in my model. the views.py: if request.method == 'POST': if 'user_reg' in request.POST: form = ProfileModelForm(request.POST) if form.is_valid(): instance = form.save(commit=False) #Create user and get the id n_user = User.objects.create_user(username=request.POST['u_email'], email=request.POST['u_email'], password=request.POST['u_password']) instance.user = User.objects.get(id=n_user.id) instance.u_profile = 'U' print("TERMS-->",request.POST['u_terms']) instance.save() return # Put return here else: messages.error(request, "Error") #form = ProfileModelForm() return render(request, 'login.html', {'form': form}) elif 'register' in request.POST: pass elif 'company' in request.POST: pass and the html template part related to my checkbox: <div class="col-lg-12 no-pdd"> <div class="checky-sec st2"> <div class="fgt-sec"> <input type="checkbox" name="cc" … -
Add transformed image to database using views.py
Add a transformed(color to black and white) version of uploaded image in django database using views.py only. I was able to do this by changing the save method of models.py but I want to do this using views only. -
using django generic.ListAPIView . type object 'DoctorsListView' has no attribute 'get_extra_actions'
I am new to django using rest API . there are alot of tutorials using generics.ListAPIView for filetering the results. I am trying to make an API for the doctors model which will search for doctor with specifics specialties class DoctorsListView(generics.ListAPIView): """ API endpoint that allows groups to be viewed or edited. """ queryset = Doctors.objects.all() serializer_class = DoctorSerializer filter_backends=(DjangoFilterBackend,) search_fields=('specialties') File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\routers.py", line 153, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: type object 'DoctorsListView' has no attribute 'get_extra_actions' -
fetch specific data from json and store in table in django
I'm trying to fetch specific data from external api and store it into my table in django.I am able to fetch all the data but how to send only specific data to table. My view.py def post(self, request): api_key = "API-KEY" response = requests.get('https://api.themoviedb.org/3/movie/popular?api_key={}'.format(api_key)) data = json.loads(response.text) serializer = GetListSerializers(data = data) # serializer = GetListSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My Model.py file class GetList(models.Model): movieid = models.IntegerField() title = models.CharField(max_length=10) def __str__(self): return self.title My serializer.py file class GetListSerializers(serializers.ModelSerializer): class Meta: model = GetList fields = ('movieid', 'title') -
My div includes an element, but the element doesn't show up when iterating using .children()
Here's my html that I'm using in a Django application: <div id="mahal_questions" class="showHide_div"> {{soldier.mahal_status.label_tag}} {{soldier.mahal_status}} {{soldier.mahal_status.errors}} {{soldier.mahal_program.label_tag}} {{soldier.mahal_program}} {{soldier.mahal_program.errors}} <p> {{soldier.mahal_id.label_tag}} {{soldier.mahal_id}} {{soldier.mahal_id.errors}}</p> </div> {{soldier.currently_serving.label_tag}} {{soldier.currently_serving}} <div id="currently_serving_questions" class="showHide_div"> {{soldier.idf_id.label_tag}} {{soldier.idf_id}} {{soldier.idf_id.errors}} <p></p> <!--prevents the error message from running into the next label--> {{soldier.army_unit.label_tag}} {{soldier.army_unit}} {{soldier.army_unit.errors}} <p>{{soldier.tafkid.label_tag}} {{soldier.tafkid}} {{soldier.tafkid.errors}}</p> </div> I have two divs here that each include 3 fields. mahal_questions includes mahal_status, mahal_program and mahal_id currently_serving_questions includes idf_id, army_unit, and tafkid fields. For some reason though, when I loop through my divs and within each div, loop through my elements, I only see the first two elements in each div. The last element is ignored. (I think this problem may have started when I added in some <p> elements, but I'm not sure.) Here's my js (the method is meant to loop through each div on the page and if the div is hiding, loop through the elements and erase their value on submit so the hidden fields' values don't get sent to the db): $('#intake_form').submit(function() { var showhideDivList = document.getElementsByClassName("showHide_div"); //To avoid errors on a page with no show/hides if (showhideDivList.length > 0) { //get each show/hide div Array.from(showhideDivList).forEach(function (div) { console.log(div); //if this div is hidden if … -
Django request.POST.get return None
Hi I am fresher django developer.I tried to connect my website with android and ios using POST method.When i run url using postman app.It return null valu.But using android code,It returns correct value.How can i solve this issue.I tried this code , if request.method == 'POST': eusername=request.POST.get('eusername') epassword=request.POST.get('epassword') print(eusername) print(epassword) -
How optimze complex query django 1.8
I have a query taking about 36 seconds to run, this is unviable, I've tried using select_related and prefetch, but the results don't improve. This my query: job_list = Job.objects.filter(Q(hiring_manager=emp) | Q( followers=emp)).values_list('pk', flat=True) emp is: emp = Employee.objects.filter( user=self.request.user, firm=obj).first().pk Then i use in: _candidates = Candidate.objects.filter( job__in=job_list, apply_date__range=[date_initial, date_end] ).order_by('-apply_date') And ater: _candidates.count() This SQL: SQL Executed: SELECT ... FROM `combo_candidate` WHERE ( `combo_candidate`.`job_id` IN ( SELECT ... FROM `combo_job` U0 LEFT OUTER JOIN `combo_job_followers` U2 ON U0.`id` = U2.`job_id` WHERE U0.`hiring_manager_id` = 9482 OR U2.`user_id` = 9482 AND `combo_candidate`.`apply_date` BETWEEN '2019-01-01 02:00:00' AND '2019-02-01 02:00:00' ) Time 33402,8768539 ms hiring_manager is a FK in Job, followers is m2m in model Job -
How to make Ajax refresh an element only if file was changed?
I have .xspf file that my app downloads from server. This file content updates sometimes. How to make Ajax refresh the element as soon as file content has changed? Now I have refreshing every 1 sec. view.py def sign_update(request): artist, track = Icecast().get_sign() response_dict = {'artist': artist, 'track': track} return render( request, 'sign.html', context=response_dict ) sign_update.js function sign_update() { $.ajax({ url: "sign_update", cache: false, success: function(data) { $("#sign").html(data); } }); } $(document).ready(function() { sign_update(); setInterval('sign_update()', 1000); }); -
Display part of django module in html table
How to display only some columns of Django model in a HTML template? And also: how do I perform a function on one of the records? (amount)? Right now I'm displaying a whole table of model like that: my models.py class Tabela(models.Model): block_id = models.CharField(max_length=64) timestamp = models.DateTimeField() type = models.CharField(max_length=32) link = models.CharField(max_length=64) link_as_account = models.CharField(max_length=100) account = models.CharField(max_length=100) amount = models.CharField(max_length=64) def __str__(self): return self.block_id My views.py def search_results(request): model = Tabela query_addresse = request.GET.get('addressee', None) query_hash = request.GET.get('hash', None) if not query_hash and not query_addresse and request.method == 'GET': return render(request, 'nanosite/index.html', {}) if query_hash and request.method == 'GET': if query_addresse: result = Tabela.objects.filter(account=query_addresse, block_id=query_hash) else: result = Tabela.objects.filter(block_id=query_hash) field_names = [f.name for f in model._meta.get_fields()] data = [[getattr(ins, name) for name in field_names] for ins in result] elif query_addresse and request.method == 'GET': result = Tabela.objects.filter(account=query_addresse) field_names = [f.name for f in model._meta.get_fields()] data = [[getattr(ins, name) for name in field_names] for ins in result] return render(request, 'nanosite/index.html', {'field_names': field_names, 'data': data}) My index.html <div id="bottomhalf" class="table-responsive"> <table class="table table-sm table-dark table-hover"> <thead class="thead-light"> {% for head in field_names %} <th scope="col">{{ head }}</th> {% endfor %} </thead> <tbody> {% for row in data %} <tr … -
Django Admin: field not listed in list_display being displayed
My project consists in items to be processed and then classified, so I have two main models: Item and Classification, as follows: class Item(models.Model): seq_prod = models.IntegerField(primary_key=True) value = models.DecimalField(decimal_places=4, max_digits=20) class Classification(models.Model): item = models.ForeignKey(Item, db_index=True, on_delete=models.CASCADE) rule = models.ForeignKey(Rule, null=True, blank=True, on_delete=models.CASCADE) atribute = models.ForeignKey(Atribute, on_delete=models.CASCADE) valid_clas = models.BooleanField(default=True) dat_emission = models.DateField() Models Rule and Atribute doesn't really matter for the problem. As for the admin part we have: class ClassificationInline(admin.TabularInline): model = Classification list_display = ('rule', 'atribute', 'valid_clas') @admin.register(Item) class ItemAdmin(admin.ModelAdmin): list_display = ('desc', 'value',) inlines = [ ClassificationInline, ] Notice that in Classification model I haven't specified an primary key field, so Django creates an id column. In the list_display at ClassificationInline we have only 'rule', 'atribute' and 'valid_clas', notice that neither 'id' nor 'dat_emission' are present. However, in the interface Django shows a 'dat_emission' column and doesn't show 'id' column. Shouldn't only fields specified at the list_display be displayed? How can I remove 'dat_emission'? -
Button in bootstrap popover loses attributes
I have a bootstrap popover for my django website that opens when a button is clicked. Inside this popover is another button. I am currently doing this by putting HTML in the 'data-content' of the popover, seen below: <a tabindex="0" id="{{prod.title}}" value="{{prod.id}}" type="button" class="btn btn-secondary btn-light mt-3 mb-0" data-toggle="popover"data-trigger="focus" data-html="true" data-content=" <div class='btn-group-vertical'> <a type='button' data-show-value='{{prod.id}}' id='{{prod.id}}' class='btn btn-secondary btn-pop wish'>Add to Wishlist</a> </div>" >More Options</a> I need to get the 'data-show-value' in jQuery, and I am currently using the following which triggers when this button is clicked: $(document).on('click', '.wish', function () { var thisButton = $(this)[0] console.log(thisButton); var prodID = $(this).data("show-value"); } However, all this does is return 'undefined'. I used console.log(thisButton) to see what the button code is displaying as, and it is this: <a id=10 class='btn btn-secondary btn-pop wish'>Add to Wishlist</a> This explains why the 'data-show-value' is returning as undefined, as the attribute itself is not rendering on the web page. Why is this? -
Django : Form Successful but image not uploaded
MODELS.PY class Campaign(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) campaign_image = models.ImageField(default="profilepic.jpg",upload_to="campaign_pictures") FORMS.PY class RaiseFundsFrom3(forms.ModelForm): class Meta: model = Campaign fields = ['campaign_image'] VIEWS.PY @login_required def raise_funds_medical_3(request): if request.method == 'POST': form = RaiseFundsFrom3(request.POST, request.FILES or None, instance=request.user) if form.is_valid(): check = form.save(commit=False) check.save() return HttpResponse('form worked') else: form = RaiseFundsFrom3() return render(request,'funds/raise_funds_medical_3.html',{'form':form}) URLS.PY path('raise/medical/photo', views.raise_funds_medical_3, name="raise_funds_medical_3"), raise_funds_medical_3.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group pt-2"> <small>Photo formats must be PNG / JPG / JPEG</small> <input type="file" name="campaign_image" /> </div> <button class="btn btn-lg button_bfg_blue" type="submit"> <small><b> NEXT </b></small> </button> </form> on form submit, i do not get any error, but image is not uploaded to the required folder. however, in the raise_funds_medical_3 function within views.py, if i remove instance=request.user, the image gets uploaded but i get following error : NOT NULL constraint failed: funds_campaign.user_id -
My django view breaks when a Request is received
I made a simple django view that, once triggered, sends a POST request to an external Python script. The external Python script sends a response, using Requests, and the Django view should just print the request. However, i'm having some troubles. I tried the following: def myView(request): URL = 'someurl' if request.user.is_authenticated(): req = requests.post(URL, json={"one": 1}) if request.method == 'POST': data = request.POST print('FIRST:', mydict) else: print('Not authenticated') return JsonResponse('test') So the code inside that if statement is triggered once a Request is received by the view. What's weird about this view is that, once the Request is received, i will see the following on my console: AUTHENTICATED - DEBUG Not authenticated - DEBUG [09/Jan/2020 10:52:50] "GET /balances/fin HTTP/1.1" 200 2 Not authenticated - DEBUG How is that possible that the view is both authenticated and not authenticated? Why are there three print statements instead of two? Can someone explain what is happening here? Thanks in advance! -
Can't use vue.js from django
I introduced vuejs using webpack in django, but I can not use vue instances from django templates. Looking at the chrome devtool, the transpiled js is loaded correctly, but shows {{message}}. Please help me. main.js import Vue from 'vue' import App from './App.vue' import vuetify from '@/plugins/vuetify' // path to vuetify export window.Vue = require('vue'); Vue.config.productionTip = false new Vue({ render: h => h(App), vuetify, }).$mount('#app') html {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Example</title> </head> <body> {% verbatim %} <div id="app"> {{ message }} </div> {% endverbatim %} {% render_bundle 'main' %} <script> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) </script> </body> </html