Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check Context Data Of Views - Django?
I am new to Django lets say I have modal like college and department like follow class College(models.Model): name = models.CharField() is_active = models.BooleanField() class Department(models.Model): name = models.CharField() college = models.ForeignKeyField() Now I have views such as DepartmentListView, DepartmentCreateView, DepartmentUpdateView to list,create,update department. I want check is_active(True) of college before adding, list, update department. currently i am using get_context_data like follow def get_context_data(self, **kwargs): context = super(DepartmentListView, self).get_context_data(**kwargs) try: college_id = self.kwargs.get('position_id') context['college'] = College.objects.get(pk=college_id, is_active = True) except College.DoesNotExist: raise Http404 return context but I am repeating the same block of code, again and again, I want to check is_active of college on all views in department app.how can I achieve this without repeating. -
How to find count of records per week of given month in django 1.11?
I need to count the number of records per week of given month. I got count per month of given year using query as below c = Cars.objects.filter(sold__year='2017').extra(select={'month':'extract(month from sold)'}).values('month').annotate(perMnth=Count('sold')) How to find count per week of given month, that is like week wise count of month 'November' , like week1=10, week2=12,week3=5,etc -
django rest framework: forms how to pass the select options
I am trying to create a form in reactjs as frontend, which will create an object using Django api I am trying to create an ingredient the following is the serializer to create or update and ingredient class IngredientCreateUpdateSerializer(ModelSerializer): class Meta: model = Ingredient fields = [ 'name', 'munit', 'rate', 'typeofingredient', ] I will be having munit and typeofingredient as select fields. The options for these select fields have to supplied from the server. eg: munit can have options of kg,ltr, pcs etc and typeofingredient can have option of vegetables, spices, fruits etc both are ForeignKey type. So prior to using the create api i have to supply to the form the options of both munit and typeofingredient at that particular instance from the server. So how to do this. For getting the options should i have to create another api. or is there any direct way -
Getting the value of a forms.ChoiceField instead of the label, from the view
I have a FormView from which I'd like to do a bit of form processing. Within the form_valid() I'm trying to obtain the submitted form's values in order to instantiate a different object. When I get the form.cleaned_data however, I am returned a dictionary of {'form field name' : 'choice label'}. I'd like to get the value corresponding to the choice label. Here is the FormView--the get_form_kwargs bit is simple passing custom choices to the view: class RequestView(FormView): form_class = RequestForm template_name = 'profile/request.html' success_url = '/' def get_form_kwargs(self, *args, **kwargs): requester_obj = Profile.objects.get( user__username=self.request.user) accepter_obj = Profile.objects.get( user__username=self.kwargs.get('username')) r_favorite_set = requester_obj.get_favorite() a_favorite_set = accepter_obj.get_favorite() kwargs = super().get_form_kwargs() kwargs['your_favorite'] = r_favorite_set kwargs['their_favorite'] = a_favorite_set return kwargs def form_valid(self, form): super(PairRequestView, self).form_valid(form) # I've tried get_FOO_display() extra instance method print(form.get_your_favorite_display()) # The following will return the choice label print(form.cleaned_data.get('your_favorite')) Favorites.objects.create(#need form choice selections) Code explanation: Within the form_valid I hope to create a different object using the selection from the submitted form. So how do I get the submitted choice instead of the label? Is this even the proper place to do this? -
How to access SQLite from JavaScript in Django?
I am trying to build a web-app using Django where I take in a stream of csv data, write a Python script to upload the data to the local SQLite database, then later connect to the database and use that data to build a JS-based graph. Currently, I am trying to do this: from .models import GraphData def getdata(request): return JsonResponse({'graphdata': GraphData}) And the JavaScript is: var dataxhttp = new XMLHttpRequest(); dataxhttp.open("GET", "/testGraph/getdata/", true); //this is where I try to connect to the URL that gets the data dataxhttp.send(); var j = 0; dataxhttp.onreadystatechange = function() { if (dataxhttp.readyState == 4 && (dataxhttp.status == 200 || dataxhttp.status == 0)) { console.log("Ready state: " + dataxhttp.readyState); console.log("Status: " + dataxhttp.status); console.log(dataxhttp.response); // Not working, unless I change {'graphdata': GraphData} to {'graphdata': GraphData.objects.get(id=1).customerName} } } The way I want to use it is this way: data = dataxhttp.response; console.log(data.get(id=1).customerName); or: for (int i = 0; i < 2; i++) { console.log(data.get(id=i).customerName; } Also, is it possible to access 'dataxhttp.response' or 'data' outside 'dataxhttp.onreadystatechange()'? This way, I can get the data inside 'readystatechange' then use it outside to build my graph. -
Sending Godaddy email via Django using python
I have these settings EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True Speaking to Godaddy I have found out these are the ports and settings smtpout.secureserver.net ssl 465 587 TLS ON 3535 TLS ON 25 TLS ON 80 TLS ON or TLS OFF I have tried all the combinations. If I set TLS to True I am getting STARTTLS extension not supported by the server. If I set to 465 I am getting If I set other combinations like EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False For verification, I used Google Mail settings to test if the email sending via python works, and it is working. Now I want to switch to GoDaddy and I know for the email we use TLS to log in even for POP3 download and it is working, so I am not sure why python / Django option is not working. Can you please help? I have called Godaddy, they cannot help because it is a software issue - all their settings and ports are … -
Color the bars of Barchart differently in Google Charts
I am trying to make a barchart using Google Charts and I want to color the bars differently. From the Documentation of google charts I am sending data from backend in the following format : { "cols": [ {"id":"","label":"Topping","pattern":"","type":"string"}, {"id":"","label":"Slices","pattern":"","type":"number"} ], "rows": [ {"c":[{"v":"Mushrooms"},{"v":3}]}, {"c":[{"v":"Onions"},{"v":1}]}, {"c":[{"v":"Olives"},{"v":1}]}, {"c":[{"v":"Zucchini"},{"v":1}]}, {"c":[{"v":"Pepperoni"},{"v":2}]} ] } I am using a ajax call to get data from my django backend, the code is shown below - var jsonData = $.ajax({ url: $('#barchart_values').attr('data-actionurl'), dataType: "json", async: false }).responseText; I know I can use the options parameter to set different colors but when I do so only the first color of the list is applied to all the bars. var options = { title: "Vegetables", legend: { position: 'top' }, colors: ['green', 'red', 'blue'] }; var data = new google.visualization.DataTable(jsonData); var chart = new google.visualization.BarChart(document.getElementById('barchart_values')); chart.draw(data, options); In the above code, green color is applied to all the bars. I want to send the color from the backend, i think I can do it using the "p" attribute, but I don't know how exactly to do it. I want to know is there some way I can include the color in the json data which I am sending from … -
How to implement Django user PasswordHasher in java?
I want to analog passwordHasher process like Django does in java. As we know, Django has a way of PasswordHasher to add the user to mysql with encryption. And I've found this Java implementation of Django PasswordHasher to authenticate whether the password is right or not. However, I cannot use this to insert users into mysql, because django found the password is wrong. So, how can I implement the make_password like Django does in java? As a result, it can authenicate with success from data inserted into mysql in java. -
Django templates - Check if user already has created an object for another object
I have 2 models called Valuation and Assessment. A valuation has many assessments (foreignkey relationship). Users can only create 1 assessment for each valuation. This seems to be very simple but I can't wrap my head around it. I need to check if any of a valuation's existing assessments belongs to the request.user, how do I do that? this doesn't work because assessment_set.all is a list. (assessments in this case is a list of assessments for the currently displayed valuation) {% if request.user.assessment_set.all not in assessments %} # Display "make an assessment" form {% endif %} So I think I'd need to loop over request.user.assessment_set.all and see if each of the user's assessments is in the assessments list, but I feel like that is very inefficient and there must be a better way. Advice? -
Django backend with Express/React for Server Side Rendering
I'm mapping out a web app and would like an opinion on my proposed back end architecture. I plan to use React, and need the SEO benefits of server side rendering. I'd like to use Django as my core backend, but I understand it's difficult to implement React SSR with it. As an alternative, I'm considering hosting Django separately from a light weight Express server where I can implement SSR rather easily. In the Express API routes, I'd call the Django project's API. I wanted to know if this is a viable option. Meaning: it's performant and still meets SEO standards. Perhaps there are other factors I should be considering, too. Any thoughts or alternatives would be much appreciated! Thanks. -
Deploying Django app to Google App Engine
I worked through the tutorial for deploying a Django app to the Google App Engine. But I ran gcloud app deploy --verbosity debug thirty minutes ago and it still hasn't finished. Here are the messages I've received: DEBUG: Running [gcloud.app.deploy] with arguments: [--verbosity: "debug"] DEBUG: No staging command found for runtime [python27] and environment [STANDARD]. DEBUG: API endpoint: [https://appengine.googleapis.com/], API version: [v1] Is there something I can do? Does it usually take this long to deploy a project? -
jquery file upload to upload only the selected files from the datatable
I am trying to implement jquery upload plugin on my django app. What I have done is, I made the plugin to choose the files and list those files on the jquery datatable and I restricted the plugin to not to upload automatically. If I click on the #startProcessing button, all the files stored in the input[files] attribute is sent to the server. js_part $('#fileupload').fileupload({ url: '/upload/', crossDomain: false, beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type)) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, dataType: 'json', autoUpload: false, acceptFileTypes: /(\.|\/)(csv|xls|xlsx)$/i, maxFileSize: 5000000, // 5 MB singleFileUploads: false, add: function (e, data) { console.log('inside add'); $("#bntStartProcessing").off('click').on('click', function () { console.log('On start proc click'); console.log(data); data.submit(); }); }, }).on('fileuploadadd', function (e, data) { $.each(data.files, function (index, file) { dt.row.add( [ '', file.name, checkExtension(file.name) ] ).draw( false ); }); }) Relevant html file <div class="container"> <div id="msg-alert" class="row"> <div class="alert alert-info alert-dismissable" role="alert">To create a new dataset, start by uploading files to it. Use the "Add" button to upload files. </div> <div class="alert alert-success alert-dismissable" role="alert">For FAQ on how to successfully upload files press <i class="fa fa-question-circle"></i> button</div> </div> <div class="row"> <button id="btnAdd" type="button" class="btn btn-primary waves-effect waves-light"><i class="fa fa-plus"></i> Add </button> <div class="btn-group"> <button type="button" id="btn-remove" … -
using meta classes properly in Python 3 / Django
I keep looking at references and examples, but still can't quite get this right. Django provides lots of examples of using metaclasses as part of a factory system that creates all sorts of methods, etc., specific to the values passed in. The idea is clear. But how it really works is a bit mysterious. A typical piece of Django (straight from the Django 'getting started' tutorial)code looks like this: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) Now, later on, there will be actual instances of these classes, e.g.: q1 = Question(question_text='my question', pub_date='01-01-2017') Yet, for all the world, within the class definition, question_text and pub_data look like they are class-wide objects (i.e., shared by all instances of that class, such as q1, q2, etc.). The more traditional way to do this and maintain isolation would be for there to be a 'self' in front of each, so that the class def looked like: class Question(models.Model): self.question_text = models.CharField(max_length=200) self.pub_date = models.DateTimeField('date published') I even tried looking at the source code for Django. Indeed, models.Model is a class which has a meta-class above … -
Implement a Look Through in Django
I want to have a Django view that queries the model, and then if it doesn't find anything uses an object to attempt to get the information from the internet. What I want to do is something like this: def my_view(request, foo): try: bar = ModelClass.objects.get(property=foo) except Question.DoesNotExist: bar = api_object.get(foo) How do I do this so that I don't have to construct api_object each time. -
Django - moderate users for admin approval
I have created an app that allows users to create online products - basically a structured form fill with permissions. I'm using Django's basic auth for sign up and login. When a user signs up I want the account to be approved by an admin before they can log in. I know there are modules I can use to do this, but I wondered if there is something I can do to enable this without installing more stuff. Here's the signup view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) If it's not that simple and the best way is to use a module, which one is the best? I've seen a couple but am not sure which one to use, if I have to use one. -
Django translating MySQL query to Django Query
How can i get the equivalent of this MySQL script in Django views? The depart_city, arrive_city, and travel_date will be inputed by the user. Here is my Models class Driver(models.Model): first_name = models.CharField(max_length=30, null=True, blank=False) last_name = models.CharField(max_length=30, null=True, blank=False) class Schedule(models.Model): depart_time = models.TimeField() arrive_time = models.TimeField() class TravelDate(models.Model): start_date = models.DateField(null = True) interval = models.IntegerField(null = True) class Route(models.Model): depart_city = models.CharField(max_length=50, null=True, blank=False) arrive_city = models.CharField(max_length=50, null=True, blank=False) driver = models.ForeignKey(Driver) schedule = models.ForeignKey(Schedule) traveldate = models.ForeignKey(TravelDate) Here is my MySQL script. This works when i run it on MySQL workbench but I'm not sure how to translate this to Django Query SELECT busapp_route.depart_city, busapp_route.arrive_city, busapp_driver.first_name, busapp_schedule.depart_time FROM (((busapp_route INNER JOIN busapp_driver ON busapp_route.driver_id = busapp_driver.id) INNER JOIN busapp_schedule ON busapp_route.schedule_id = busapp_schedule.id) INNER JOIN busapp_traveldate ON busapp_route.traveldate_id = busapp_traveldate.id) WHERE busapp_route.depart_city='Tropoje' AND busapp_route.arrive_city='Tirane' AND (DATEDIFF('2017-11-26', busapp_traveldate.start_date) % busapp_traveldate.interval = 0); -
Django STATIC files does not work in Develop mode
Django STATIC files does not work in Develop mode. I tried in many ways, but I did not succeed. Could someone tell me where I'm wrong? Thank you very much for your attention. STATIC_URL = '/static/' STATIC_ROOT = "/Users/user/Projects/RMA/static/" STATICFILES_DIRS = ( os.path.join(BASE_DIR, '..', 'static'), ) .... 'django.contrib.staticfiles', routes urlpatterns = [ url(r'^$', views.index, name='index') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) View def index(request): return render(request, 'base.html', {'question': 'ads'}) template {% load static %} <link href="{% static 'site/bower_components/select2/dist/css/select2.min.css' %}" rel="stylesheet"> -
Searching in multiple fields respecting the row order
I have a model like the following: class Foo(models.Model): fruit = models.CharField(max_length=10) stuff = models.CharField(max_length=10) color = models.CharField(max_length=10) count = models.IntegerField() exists = models.BooleanField() class Meta: unique_together = (('fruit', 'stuff', 'color'), ) It is populated with some data: fruit stuff color count exists Apple Table Blue 4 True Pear Book Red 4 False Pear Phone Green 3 False Apple Phone Blue 7 True Pear Table Green 3 True I need to merge/join this with a collection (not a queryset): [('Apple', 'Table', 'Blue'), ('Pear', 'Phone', 'Green')] So basically rows 0 and 2 should return when I search this model with this list of tuples. Q seemed promising with a little modification on the list: from django.db.models import Q Foo.objects.filter( Q(fruit__in=['Apple', 'Pear']), Q(stuff__in=['Table', 'Phone']), Q(color__in=['Blue', 'Green']) ) but this returns rows 1 and 3 as well. Currently my workaround is to read Foo.objects.all() into a DataFrame and do a merge with the list of tuples and get the ID's to pass to Foo.objects.filter(). I also tried iterating over the list and calling Foo.object.get() on each tuple but it is very slow. I feel like there should be a clean, efficient way of doing this. Is there? Note: The list of tuples does … -
migrating from one-to-many to many-to-many: interm. table does not have UNIQUE constraint
TL;DR; changing completely different field in the same migration as introducing many-to-many field leads intermediate table does not have UNIQUE constraint. Root challenge. I need to replace one-to-many relation with many-to-many. Step-by-step. Assume initially I have: class Test(models.Model): pass class Test2(models.Model): title = models.CharField(max_length=100) test = models.ForeignKey(Test) After changing test2.test into ManyToMany class Test(models.Model): pass class Test2(models.Model): title = models.CharField(max_length=100) tests = models.ManyToManyField(Test) and running makemigrations/migrate I'm getting new table test2_test with UNIQUE constraint for pair test_id + test2_id and that's definitely I expect. But once I wanted to update another field also: class Test(models.Model): pass class Test2(models.Model): title = models.TextField() tests = models.ManyToManyField(Test) And test2_test does not get UNIQUE INDEX for test_id + test2_id. As a workaround I've finally moved changes for different field into separated migration. Question Does anybody know reason for a such behavior? -
Sending a file via POST using Django using Javascript instead of HTML Form
I have a PDF file saved in a variable 'report.' I am using Django and want to pass it to a function in my views.py file using POST -- @xframe_options_exempt @csrf_exempt def process_report(request): if request.method == 'POST' report_file = request.FILES['docfile'] .... return response How can I send a ajax POST request with this file? The filetype is a PDF. I was using an HTML form to do this before, but I wanted to style the form upload using javascript. I tried styling the button using javascript (changing colors and text depending on file type uploaded), but the file was no longer being able to be passed through the POST request. Now I just have the file saved in a javascript variable, and am trying to just pass it via POST without using form. I understand it's impossible to prepopulate a form with a file. My old code: <form id="boring" action="{% url "process_report" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {{ form.docfile.label_tag }} {{ form.docfile.help_text } {{ form.docfile.errors }} {{ form.docfile }} </form> What I have been trying to do with ajax var formdata = new FormData(report); $.ajax({ url: 'process_report', type: 'POST', processData: false, contentType: false, dataType : 'application/pdf', … -
Django throwing isoFormat error when receiving string for model DateField
I am trying to utilize a DateField in my model, but when I send it an iso formatted string from my javascript form ('2017-10-17') I get an error on the backend stating: AttributeError at /comment/ 'str' object has no attribute 'isoformat' It looks like something far down in django/python is treating this like a python datetime object. I can get around this by converting my string into a python datetime object in the corresponding serializer, but that seems like it should be unnecessary. Here is my code # Inside comment/models.py submission_date = models.DateField(blank=True, default=datetime.date.today) # Work around inside comment/serializers.py if 'submission_date' in validated_data: validated_data['submission_date'] = datetime.strptime(validated_data['submission_date'], "%Y-%m-%d") I'm sorta new to Python and Django, but I find it hard to believe that I'd have to force the conversion of an incoming string (the only way to pass data from the front end) into a python datetime object for every DateField that may come up. This also seems especially odd as all the documentation around the DateField uses the same iso formatted strings that I am using. Am I doing something silly? Are my assumptions incorrect about how this should work? -
django 'ModelFormOptions' object has no attribute 'virtual_fields'
models.py class Products(models.Model): company = models.ForeignKey(Companys) name = models.CharField(unique = True, max_length = 50) description = models.CharField(unique = True, max_length = 500) price = models.PositiveIntegerField() in_stock = models.BooleanField(default = True) crated = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name forms.py class ProductForm(forms.ModelForm): class Meta: model = Companys fields = '__all__' name = forms.CharField() description = forms.CharField(widget = forms.Textarea, ) company = forms.ModelChoiceField(queryset = Companys.objects.all(), label = 'Company') in_stock = forms.BooleanField(initial = True) price = forms.ImageField() views.py class ProductCreate(CreateView, ProductEditMixin): model = Products template_name = 'store/product_add.html' fields = '__all__' Please help me. Without forms code work. But with forms i have AttributeError: 'ModelFormOptions' object has no attribute 'virtual_fields' error -
I need consultation and possibly a solution for the matter of serializing a complex object in django to json
So as I've started saying in the title, my problem is that I have a complex object that I've constructed specificaly for a project but it's in python and I want to serialize and convert it to JSON format and receive it on the client side JS. Now my question is, what is the best approach to such a problem? should I in fact not be doing any work on the backend of django and actually sending raw lists and objects to the JS client side and there build the complex object, or is this aproach sensibile and I should just deal with the problem of serializing this complex object and deliver it to the client JS? I've added my code so that you can understand the full context of what I'm trying to acheive : def get_foundation_estimated_value(found): if found.sumCalls: return found.lastAcc.sum / found.sumCalls else: return 0 def add_to_foundation_batzir_year(found): found.batzir = 0 if found.actions['calls'] and found.actions['calls'][0]: found.batzir = found.actions['calls'][0].date.year def update_kibbutz_total_actions_sums(found, kibbutzim_totals): kibbutzim_totals[found.kibbutz.name]['callTotal'] += found.sumCalls kibbutzim_totals[found.kibbutz.name]['distTotal'] += found.sumDists if found.lastAcc: kibbutzim_totals[found.kibbutz.name]['accsTotal'] += found.lastAcc.sum def add_actions_to_foundation(found): capital_calls = CapitalCall.objects.filter( foundation_id=found.id).all().order_by('date') capital_accounts = CapitalAccount.objects.filter( foundation_id=found.id).all().order_by('date') distributions = Distribution.objects.filter( foundation_id=found.id).all().order_by('date') found.actions = { 'calls': capital_calls, 'accs': capital_accounts, 'dists': distributions } def add_to_foundation_sums_of_actions(found): # … -
I have this kind of error python. reset_password
I wanted to make a reset password on Django but this problem came. I tried to rename it but it does not work. The problem comes: NoReverseMatch at /password_reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. **URL.PY** from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views from grooveapp import views as core_views from django.contrib.auth.views import ( password_reset, password_reset_done, # password_reset_confirm, # password_reset_complete ) urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'grooveapp:login'}, name='logout'), url(r'^login/$', auth_views.login, name='login'), # url(r'^lobby/$', views.lobby, name='lobby'), # url(r'^lobby/(?P<name>[0-9]{1})/$', views.lobby, name='lobby'), url(r'^lobby/(?P<name>[0-9]+)/$', views.lobby, name='lobby'), url(r'^profile/$', views.profile, name='profile'), url(r'^profile/edit/$', views.edit_profile, name='edit_profile'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^infostories/$', views.infostories, name='infostories'), url(r'^story/$', views.story, name='story'), url(r'^makechat/$', views.makechat, name='makechat'), url(r'^api/lobby_messages$', views.get_messages), url(r'^signup/$', core_views.signup, name='signup'), url(r'^password_reset/$', password_reset, name='password_reset'), url(r'^password_reset/done/$', password_reset_done, name='password_reset_done'), ] -
How to pass a array to form field
i want to attach an array to input field and post. i cant seem to store the value of the array to a form field. Here is my code plz help $('#field_id').append(array) var values = form.serialize() $.post(url,values ) }