Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Poll app in django tutorial: How to show another poll after voting instead of result page
As following exactly the django tutorial in djangoproject.com, we made a poll web app. After choosing a choice and hit "vote" button, users will see the result page of that question. But i want to change a bit How do i change codes to show the next question after users choose a choice and hit vote button. And if the last question is showed, users will then see the whole results -
Using ExpressionWrapper as inside Value in a Case,When query in Python
I am trying to calculate the share of each type (BookType) of book (Book) in the list of a Publisher's books. I suppose this should do the job: Book.objects.annotate( publisher = F('Publisher__id') publisherBooksNum = Count('Publisher__id') ).values( 'publisher' ).annotate( Case( When(BookType=0, then=Value( ExpressionWrapper( Count('publisher')/F('publisherBooksNum') ), output_field=FloatField()) default=Value(0 , output_field=FloatField()) ... however I get the error: float() argument must be a string or a number, not 'ExpressionWrapper' What am I missing in the code? Is there a better Way to achieve this? -
Converting a a string to be a part of a python command in a Python script [duplicate]
This question already has an answer here: How do I retrieve a Django model class dynamically? 6 answers I have a function in a python script (views.py in Django) with a django's API command: def layer(layer_name, model_name): # here is the command in_out = model_name.objects.filter(geom__contains=location) result = inform_user(layer_name, in_out) return result When I call the layer() function as: layer(layer_variable, model_variable) python interpret the command as: 'model_name'.objects.filter(geom__contains=location) How can I send the model_name variable without python interpreting it as a string ? -
The result of table after running "python manage.py migrate" is different from what shows in sqlmigrate
I wanna create a table like this : Afterwards, I ran command--"python manage.py makemigration",it outputted a file called 0001_init.py as I expected.Then,I ran command "sqlmigrate user 0001_initial" They were all ok at that moment.However,to my puzzlement,when I ran command "python manage.py migrate",the database created the table like this: So,where are my "student_id"and"name" fields???They should had been created as the SQL statement goes that: "student_id" varchar(10) NOT NULL,"name" varchar(20)NOT NULL Is that a Django bug ?or MySQL bug? -
Beautiful soup multiple class storage
def index(request): driver = webdriver.Chrome("C:/Users/Hello/Downloads/chromedriver_win32/chromedriver.exe") browser = webdriver.Chrome("C:/Users/Hello/Downloads/chromedriver_win32/chromedriver.exe") browser.get('the website') time.sleep(10) a="None" for _ in range(1): browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(5) browser.execute_script("window.scrollTo(0,500);") time.sleep(5) pageSource =browser.page_source **soup = BS(pageSource, 'lxml') hello=soup.findAll("span",{"class":["SRPriceB proPriceField","SRPPS sqrPriceField","localityFirst"]}) for hellos in hello: location=hellos.get_text() landscrapes = landscrape.objects.create(location=location) landscrapes.save() return HttpResponse(location)** as with find all three values are getting found and stored as separate objects in the database, when find all is used. How do i successfully store these three values differently in the database with them corresponding to each other -
Couldn't understand this regex pattern [duplicate]
This question already has an answer here: Reference - What does this regex mean? 1 answer ^,$ When to use this symbol in regex? 1 answer So I recently started learning django and I am making the polling app from django's tutorials. I stumbled upon these two regex expressions which I cant understand-> The first code is in polls/urls.py from django.conf.urls import url from . import views urlpattersn = [ url(r'^$', views.index, name="index"), #1 ] The second code is in mysite/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.url')), #2 url(r'^admin/', admin.site.urls), ] Now coming to #1 marked in the code-> I did some research and found out that url takes in 4 arguments 2 of which are optionals. So I basically I am giving a regex expression r'^$' to the url function and also passing an optional name for url and a view. I am having trouble understanding what does r'^$' actually do ? All I could find out is ^ stands for negation or first word in a line and $ stands for last word in a line. Now coming to #2 marked in the code-> I cant understand the working of … -
order django formset without form change
I have a form with only one filed that's repeated(names of family members and that field is the name, so when you want to see the family members using this form all members would be shown). Now I want my form be sorted (arbitrary order) defined by the user. For example in a family, I want to show A first, then B and then C, while the creation sequence may be C, B and A. Is there anyway to do that? I searched and realized I should add an order field to my forms and override --iter--(), is that the only way? If there is no way to do that without change in form, how can I do that? class FamilyMemeberItem(forms.Form): name= forms.CharField(label=_('name'), max_length=20) thanks -
Serving NGINX with DJANGO on Ubuntu
I am trying to Run my django(1.8) project on Nginx server since it is much faster. I am able to run by using uwsgi --ini commands to setup socket. so what i wants to do is by running NGINX alone want to run my django project, is there any way to do that ? Well the socket created by uwsgi is removing automatically when uwsgi --ini command ends. NGINX config and .ini ia as shown below : # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///var/www/html/vir/crum/crumbs.sock; } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name .localhost.com; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /var/www/html/alteryx_vir/crum/media; } location /static { alias /var/www/html/vir/crum/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; /var/www/html/vir/crum/uwsgi_params; } } >>> uwsgi.ini file : # mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /var/www/html/vir/crumb/ # Django's wsgi file module = crum.wsgi # the virtualenv (/alteryx_vir/) home = … -
Error: 502 nginx gcloud with Django app
Good day. I uploaded my Django app to Google cloud and I keep getting a 502 error nginx. My error log reads: Exec: gunicorn: not found How do I go about this. Thanks -
How to add new player safely?
Based on my question here I'm trying to use both transactions and select_for_update but using Django to make sure it works on SQLite and later on on PostgreSQL. I have setup Game, PersonGame and Person like this: class Game(models.Model): name = models.CharField(max_length=200, default=None, blank=True, null=True) number_of_players = models.IntegerField(default=2, blank=True, null=True) players = models.ManyToManyField(Person, blank=True, through='PersonGame', default=None, symmetrical=False, related_name='person_game') class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class PersonGame(BaseModel): person = models.ForeignKey(Person, on_delete=models.CASCADE) is_creator = models.BooleanField(default=False) game = models.ForeignKey(Game, on_delete=models.CASCADE) data = models.BinaryField(default=None, blank=True, null=True) So the idea is to lock Game and PersonGame while checking if there's room for another player and if so add a new player. My insertion code looks like this: with transaction.atomic(): g = Game.objects.select_for_update().get(pk=int(pk)) p, created = Personne.objects.get_or_create( user=request.user) if g.players.count() <= g.number_of_players: p_g = PersonGame.objects.create(person=p, is_creator=True, game=g) I'm calling g.players via g.players.count() so will this lock the table PersonGame? If many players want to join the game, are we sure there won't be any possibility of 2 insertions at the same time, resulting in more players than the Game should have? If it's not safe, what is the solution? -
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.