Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JavaScript to Update Database
In my Django app, I have users with coins inside of their profiles. I also have a timer written in JavaScript. Essentially, when the timer is over, I want the user attached to the request to have their coin balance increased by an amount. How would I make this happen? -
list_route action does not show in Django REST framework docs
I have an action as shown below: @list_route(url_path='posts/search') def search_posts(self, request): <some action> Now, I am using DRF's Built-in API documentation to generate my API docs. But the above action does not show up. However, if I remove the url_path from @list_route then it shows up. Seems like the url_path has to match with the action name for the documentation generator to include it in the API docs. How can I fix this? I do not want to change the url_path. -
When I upload an excel file in Django numeric cell format change to General
I'm uploading some excel file from a simple HTML form to a Django application, the Excel has two columns one of them with "General Format" and the other one with "Number format". Whenever I upload a file, all the cells change to "General format". Here some snippet of my code: <form id="excelFormId" name="excelFormId" action="/appupload/" method="post" enctype="multipart/form-data"> ... <input required name="excel_file" id="excel_file" type="file" > ... excel_file = request.FILES['excel_file'] fs = FileSystemStorage(location='../') fs.save('myExcel.xls', excel_file) How can I avoid losing the original format? -
Django 1.10.0 LOGIN_REDIRECT_URL NOT Working
I have been using the default django auth for login and I am also using the decorator @login_required for some of the pages. There is no need to remember the previous page if the user hits logout and stuff. The idea is, the user will be redirected to a static page once logged in. How do I do that in django? I do not want to edit login template. LOGIN_URL = '/accounts/login/' #redirects the user to the login page if not logged in already LOGIN_REDIRECT_URL = '/something-else' #does not work. In my urlconf, it's defined like url(r'^something-else/$', views.something_else, name='something-else') Any help would be highly appreciated. Thanks. -
how to compare a unicode string in model field and choices? django
I am not sure which part I am doing wrong but somehow I am trying to compare two values and I am 100% sure they matches but somehow code would not execute. Let's say I have this model (please forgive for a bit typos for models and field names) class TestOne(models): gender = models.Charfield(max_length=10, choices=GENDER_CHOICES) my choices GENDER_CHOICES = (("MALE", "MALE"), ("FEMALE", "FEMALE")) I am so sure my gender field is MALE for the object so I am doing this statement as check that if it's MALE do something. if a.gender is `MALE`: # do something here but it never reaches it as true. I checked a.gender is a unicode type so I even did str(a.gender) to make sure it's also a string but still no luck. Am I doing anything wrong here? P.S. I did a print with a.gender and made sure that the output is MALE Thanks in advance -
During setup of django with sendgrid getting error 401
I have added sendgrid to my django app Followed the simple steps from here https://github.com/elbuo8/sendgrid-django generated acount and and copied the api at sengrid site Added code to my view sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email("commerce@gmail.com") to_email = Email("lopa@gmail.com") subject = "Sending with SendGrid is Fun" content = Content("text/plain", "and easy to do anywhere, even with Python") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) messages.add_message(request, messages.SUCCESS, str(payment.id) + response.status_code + response.body + response.headers) And getting Error HTTP Error 401: Unauthorized What could be the problem? > Traceback Traceback: File > "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\core\handlers\base.py" > in get_response > 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\contrib\auth\decorators.py" > in _wrapped_view > 22. return view_func(request, *args, **kwargs) File "C:\Users\PAPA\DEV\rent_unit\src\payment\views.py" in payment_new > 251. response = sg.client.mail.send.post(request_body=mail.get()) File > "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\python_http_client\client.py" > in http_request > 204. return Response(self._make_request(opener, request)) File > "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\python_http_client\client.py" > in _make_request > 138. return opener.open(request) File "c:\python27\Lib\urllib2.py" in open > 435. response = meth(req, response) File "c:\python27\Lib\urllib2.py" in http_response > 548. 'http', request, response, code, msg, hdrs) File "c:\python27\Lib\urllib2.py" in error > 473. return self._call_chain(*args) File "c:\python27\Lib\urllib2.py" in _call_chain > 407. result = func(*args) File "c:\python27\Lib\urllib2.py" in http_error_default > 556. raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) > > Exception Type: HTTPError … -
is saving another model through a foreign key possible? django
please ignore any typos, I am wondering if saving through a foreign key would work. If it does, how do you do it though? Let's say I have two models. class TestOne(models): name = models.Charfield(max_length=100) viewed = models.IntegerField(default=0) class TestTwo(models): one = models.ForeignKey(TestOne) test = models.Charfield(max-length=100) I know that with ForeignKey, I can access into TestOne and get the info but is there anyway I can save it too? For example: two = TestTwo.objects.get(pk=1) two.test = "this is just a test" two.one.viewed += 1 two.save() For above, I know in TestTwo's test field will be saved but TestOne's viewed will not be incremented but is this possible, so I don't have to make another query and another save? Thanks in advance for any help. -
How to resize multiple charts - C3.js
My website has multiple charts. When a page is initially loaded, chart size does not fit into grid columns. So, I'd like to resize the charts after it's loaded. When I tested it using resize API(http://c3js.org/samples/api_resize.html). I could control a chart that is lastly loaded. How can I control multiple charts at once? html <div id="lineone" class="col-md-5"></div> <div id="linetwo" class="col-md-5"></div> charts.js var chart = c3.generate({ bindto: "lineone" data: { columns: [ ['data1', 30, 200, 100, 400, 150, 250], ['data2', 50, 20, 10, 40, 15, 25] ] } }); var chart = c3.generate({ bindto: "linetwo" data: { columns: [ ['data1', 30, 200, 100, 400, 150, 250], ['data2', 50, 20, 10, 40, 15, 25] ] } }); api_resize.js setTimeout(function () { chart.resize(); }, 3000); -
Django extra-views for one-to-many relationship
I'm trying to use extra-views for django to create one-to-many relationship. I have a model of item in my shop: class Item(models.Model): name = models.TextField( 'Название товара' ) company = models.TextField( 'Производитель' ) category = models.TextField( 'Категория' ) photo = models.ImageField( blank=True, null=True, upload_to='photos/%Y/%m' ) price = models.PositiveIntegerField( 'Цена' ) quantity = models.PositiveIntegerField( 'Количество' ) text = models.TextField('Описание товара', blank=True, null=True) A model for Images: class Images(models.Model): Image = models.ImageField(blank=True, null=True, upload_to='photos/other/%Y/%m') And relationship model: class ItemImages(models.Model): item_id = models.ForeignKey(Item, default=1, on_delete=models.CASCADE) img_id = models.ForeignKey(Images, default=1, on_delete=models.CASCADE) And basically I'm trying to use it like this: class ImgInLine(InlineFormSet): model = Images class ChainInLine(InlineFormSet): model = ItemImages class AddItemView(PermissionRequiredMixin, CreateWithInlinesView): permission_required = 'shop.add_item' raise_exception = True model = Item fields = ['name', 'company', 'category', 'text', 'photo', 'price', 'quantity'] inlines = [ImgInLine, ChainInLine] and I'm getting error: ValueError at /add/ 'shop.Images' has no ForeignKey to 'shop.Item'. So I have no clue how this thing works. -
Heroku: No default language could be detected for this app for python even with runtime.txt
I am trying to deploy a project to heroku and I am getting this error:- Counting objects: 70, done. Delta compression using up to 4 threads. Compressing objects: 100% (64/64), done. Writing objects: 100% (70/70), 17.36 KiB | 0 bytes/s, done. Total 70 (delta 23), reused 3 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: Verifying deploy... If you go to my github project, I have everything required for the heroku project including runtime.txt file but still I am getting this error. I tried changing different python versions supported by Heroku but still same error. Could anyone help me out ? If I add a buildpack then I am getting the following error Counting objects: 70, done. Delta compression using up to 4 threads. Compressing objects: 100% (64/64), done. Writing objects: 100% (70/70), 17.36 KiB | 0 bytes/s, done. Total 70 (delta 23), reused 3 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Failed to detect … -
Folder structure for React and Django REST
I'm in the process of refactoring a rather basic/traditional Django webapp to a more modern React-plus-Django-REST setup. I'm far more familiar with Django than React, so where to put the React part is what's confusing to me. My question is: what are the best practices for folder structure in using both Django and React? Ideas I've had: Put all React files in their own folder like this: . ├── app1 │ └── example-files.py ├── app2 │ └── example-files.py ├── manage.py ├── react-django-project │ ├── settings.py │ └── urls.py ├── requirements.txt ├── some-app-1 │ └── example-files.py ├── some-app-2 │ └── example-files.py ├── src │ └── components │ ├── component1.js │ └── component2.js └── ... Put all React files in the static folder, but this doesn't seem right to me. Is there an established set of best practices for this? -
In django 1.11, how can I render form using formset_factory
I have started leaning Django1.11 a few days ago, but I can't understand how can I render form using formset_factory. Here is myproject/app/views.py file. from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import ArticleFormSet def get_name(request): form = ArticleFormSet() return render(request, 'name.html', {'form' : form}) Here is app/forms.py file. from django import forms from django.forms import formset_factory class ArticleForm(forms.Form): title = forms.CharField() pub_date = forms.DateField() def ArticleFormSet(self): ArticleFormSet = formset_factory(ArticleForm) Here is name.html file. <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> I have tried to render form on the browser, but exception has occurred like this. ArticleFormSet() takes exactly 1 argument (0 given) I can't figure out what's wrong. -
int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' [on hold]
I get error int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' in this function. Exactly in this line sth_instance = Object.objects.get(id_object__id_users=id, sth=sth ) Any ideas what is wrong? @api_view(['GET']) def myView(request, user_id): if request.method == 'GET': status = request.GET.get('sth', '') sth_instance = Object.objects.get(id_object__id_users=id, sth=sth ) serializer = ObjectSerializer(sth_instance) return Response(serializer.data) -
Python mock.patch a class except some instance methods
How do exclude some instance methods when a class is being patched? eg. in my_command.py class Command(BaseCommand): def handle(self): ... self.dowork() def dowork(self): ... in tests, I am patching the Command like this from django.core.management import call_command class MyTestCase(TestCase): @patch('module.Command'): def test(self, Mocked): call_command('my_command') The problem is that since the whole command class is mocked, dowork() is never called and I cannot test if dowork is called. How do I exclude the handle method so it can call the dowork method? -
Django migrations: local variable 'field' referenced before assignment
When trying to make migrations in Django I get the following error. Can any help me understand what the problem is and how it possibly can be solved? Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/rune/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/rune/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rune/env/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/rune/env/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/rune/env/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 150, in handle loader.project_state(), File "/home/rune/env/lib/python3.5/site-packages/django/db/migrations/loader.py", line 323, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "/home/rune/env/lib/python3.5/site-packages/django/db/migrations/graph.py", line 409, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "/home/rune/env/lib/python3.5/site-packages/django/db/migrations/migration.py", line 92, in mutate_state operation.state_forwards(self.app_label, new_state) File "/home/rune/env/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 289, in state_forwards delay = not field.is_relation UnboundLocalError: local variable 'field' referenced before assignment I'm using Django 1.11.1 and Python 3.5. -
how to create a two dependent checkbox django
I didn't find any solutions till now . I don't have any idea how to create a list of two dependent checkbox . I mean i have a list of checkbox, when i choose one , a list of checkbox appears when i choose a second one a second list of check box appears. I will be thankful if you could help me. I found some ideas about two dependent drop-down. sector = models.CharField('sector', max_length=100) industry = models.CharField('industry', max_length=100) -
Building a scaling Social-networking site or Real estate listing website. Python, Django? Suggestions?
First question ever. I've basically learnt html,css.. tried to learn Java / PHP etc University got in the way now I've dedicated time and learnt python and I would say I've succeeded. I enjoy it and have done some research and thought of building a web app(s) in the future. I want to start by building a real-estate-listing website such as http://www.zoopla.co.uk or a simple social networking site. I realize that I probably wont be able to make a site as good as Zoopla, however my question is: ("If I already know HTML / CSS / Python and thinking that Django would be a good starting ground for building a real estate listing website where people can list their properties and there would be a simple framework listing rooms ,bathrooms, maybe map application all that jazz. Should I dive into Django or would you suggest that I learn PHP or any other language where working on such projects would be optimal not in a performance sense, but in a logical sense where all elements combined would be "Worth". The elements I mean are probably_________________ [Scaling, Speed_to_build, Customization, Useful_Usable_Resources... etc] What I'm asking in short is, if you were in my … -
Django ManyToManyField exclude
I'm very new to Django, being a C guy (embedded/Linux) for the most part, so I apologize for my ignorance. I've tried searching for this exact query with no luck. I have two Models, each of which has a many-to-many field pointing to the same third Model. This third model represents a restriction of some kind. class Restriction(models.Model): ... class ClassA(models.Model): ... restrictions = models.ManyToManyField(Restriction) class ClassB(models.Model): ... restrictions = models.ManyToManyField(Restriction) I anticipate having an instance of ClassA (call it object_a). I'd like to find all instances of ClassB which do not contain any of the restrictions in object_a. It would look something like this: class ClassA(models.Model): ... restrictions = models.ManyToManyField(Restriction) def get_valid_b_objects(): return ClassB.objects.exclude(restrictions__in=self.restrictions) But this doesn't feel right. Again, if any of the restrictions in a ClassB object is also in my ClassA object, that instance of ClassB should be excluded from the query. So, if: object_a contains restrictions 1, 2, and 3 object_b1 contains restrictions 2, 4, and 5 object_b2 contains restrictions 1 and 2 object_b3 contains restrictions 1, 2, 3, 4, and 5 object_b4 contains restrictions 4 and 5 object_b5 contains restriction 5 object_b6 contains no restrictions Then object_a.get_valid_b_objects() should return object_b4, object_b5, and object_b6. Thank … -
Django says "didn't return an HttpResponse object. It returned None instead."
I was looking for solutions on stack, but none did helped me. The most solutions were indent-related, but I think mine is not. I'll appreciate it when someone can help me out with this! Here is what i have: models.py from django.db import models class QuestionPost(models.Model): question = models.CharField(max_length=1000) tag = models.CharField(max_length=200) pub_date = models.DateTimeField('Date published') class AnswerPost(models.Model): answer_text = models.CharField(max_length=1000) answer_rate = models.IntegerField() forms.py from django import forms # Create your models here. class QuestionPostForm(forms.Form): question = forms.CharField(label='Question text', max_length=1000) tag = forms.CharField(label='Tags', max_length=200) pub_date = forms.DateTimeField(label='Date published') class AnswerPostForm(forms.Form): answer_text = forms.CharField(label='Answer Text', max_length=1000) answer_rate = forms.IntegerField(label='Rate') views.py from django.shortcuts import render_to_response from django.http import HttpResponseRedirect, HttpResponse from .forms import QuestionPostForm from .models import QuestionPost from django.template import RequestContext # Create your views here. def get_question(request): if request.method == 'POST': form = QuestionPostForm(request.POST) if form.is_valid(): obj = QuestionPost() obj.question = form.cleaned_data['question'] obj.tag = form.cleaned_data['tag'] obj.save() return HttpResponseRedirect('forum/index.html',{'form':form}) else: form = QuestionPostForm() return render_to_response(request, 'forum/index.html', {'form': form}) Why do i get the error: didn't return an HttpResponse object. It returned None instead? I don't understand? I'm a beginner in Django and this will help me learn something.. -
Why is Django's `add()` method in my `many-to-many` Django models not taking?
Question / Problem: I am building a Django app, with 2 models: User and Secret. Secrets can be made by Users, and other Users can "like" them. I've setup my likes field as a ManyToManyField, so that Users whom like a Secret can be stored there and later retrieved, etc. However, when I try to query for a User and a Secret and use my_secret.likes.add(my_User) nothing happens. I don't receive an error and when I print my Secret's many-to-many likes field, after the add, I see: secrets.User.None. Why is my add() method running but I am not receiving any errors, and why is my User not properly being added to my Secret's likes? Note: I've saved both the User and Secret objects upon initial creation. Outside this application I've been able to use the add() method just fine, but in those scenarios I was creating objects in the moment, and not retreiving already existing objects. Is there a different way to handle add() when using data retreived from a Query? That's my only other line of reasoning right now, and I've followed the documentation here exactly: Django Many-to-Many Docs I also apologize if this was answered elsewhere on the site. … -
Django celery setup
I need to shuledule my django tasks and i was advised to use celery. I looked over the internet and on the Celery offical website, but just couldn't figure out how to set it up. Do i have to add anything in settings.py? Do i need separate app for celery tasks? Can i shuledule tasks just in a normal views.py, or does it need separate document? I only have one function to schuledule, that will send email, something like: send_mail( 'Subject here', 'Here is the message.', 'myemail@example.com', [{{ user.email }}], fail_silently=False, ) . These are the questions i couldn`t find an answer to. Help is well appreciated! -
Django UpdateView: define fields via function instead of a member variable
I have a really simple UpdateView, where my fields are defined by the member variable fields class DataUpdateView(generic.edit.UpdateView): template_name = 'data/edit.html' model = Data fields = ['title', 'text'] text2 = forms.CharField(widget=forms.Textarea) success_url = reverse_lazy('data:index') Now i have the situation that i want to change the fields value depending on a special user permission, but i have no idea how i can define the fields via a function (or any better option). Is that possible with Django (i'm using the latest verison) Greetings Tonka -
Django python created sample Webservice API when i am trying to test i am getting error
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/users/ Using the URLconf defined in RESTWebService.urls, Django tried these URL patterns, in this order: ^admin/ The current path, users/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. urls.py from django.conf.urls import url, include from restapp import views from django.contrib import admin admin.autodiscover() urlpatterns = [url(r'^admin/', include(admin.site.urls)), url(r'^users/', views.UserList.as_view()), url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),] -
How to update datatable using Ajax in Django
I have a table that performs a CRUD operation using ajax, but I am new to ajax. I have made the table interactive with the jquery datatable, but it is not working correctly. I can add and edit data to the table and it appears, but when I sort the data the new/updated data disappears until I reload the page. I think I know what the problem is, but I have not been able to solve it. views.py def case_list(request): cases = Case.objects.filter(user=request.user).order_by('date_due') return render(request, 'cases/case_list.html', {'cases': cases}) cases.js $(function () { /* Functions */ var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-case").modal("show"); }, success: function (data) { $("#modal-case .modal-content").html(data.html_form); } }); }; var saveForm = function () { var case_formset = $(this); $.ajax({ url: case_formset.attr("action"), data: case_formset.serialize(), type: case_formset.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#case-table tbody").html(data.html_case_list); $("#modal-case").modal("hide"); myTable.draw('full-reset'); } else { $("#modal-case .modal-content").html(data.html_form); } } }) return false; }; /* Binding */ // Create case $(".js-create-case").click(loadForm); $("#modal-case").on("submit", ".js-data-create-form", saveForm); // Update case $("#case-table").on("click", ".js-update-case", loadForm); $("#modal-case").on("submit", ".js-case-update-form", saveForm); // Delete case $("#case-table").on("click", ".js-delete-case", loadForm); $("#modal-case").on("submit", ".js-case-delete-form", saveForm); }); list.html <script type="text/javascript"> … -
Writing asynchronous event dispatcher for Django project
I'm using a 3rd party server-side split testing service for a Django-based web forum of mine. For events I'm tracking, I call to the service's API. Now the default event dispatcher included in the SDK is a synchronous one; I have to write an asynchronous event dispatcher for production. I've attempted doing this via grequests, but I get the error: ('This operation would block forever', <Hub at 0x7f5230a08230 epoll pending=0 ref=0 fileno=23>). The full traceback is: Traceback (most recent call last): File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 499, in wrapper return wrapped(*args, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 91, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/myuser/Desktop/myproject/links/views.py", line 2868, in create_nick elif account_creation_disallowed(getip(request)): File "/home/myuser/Desktop/myproject/links/redis1.py", line 255, in account_creation_disallowed if my_server.exists(registered_ip): File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/api/datastore_trace.py", line 70, in _nr_datastore_trace_wrapper_ return wrapped(*args, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/redis/client.py", line 838, in exists return self.execute_command('EXISTS', name) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/redis/client.py", line 565, in execute_command return self.parse_response(connection, command_name, **options) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/redis/client.py", line 577, in parse_response response = connection.read_response() File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/redis/connection.py", line 569, in read_response response = self._parser.read_response() File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/redis/connection.py", line 224, in read_response response = self._buffer.readline() File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/redis/connection.py", line 162, in readline self._read_from_socket() File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/redis/connection.py", line 120, in _read_from_socket data = self._sock.recv(socket_read_size) File …