Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django oscar rebuild_index with error
I add attributes proizvoditel_mt here /dashboards/catalogue/product-type/1/update/ and do rebuild_index . Indexing 1227 Products Failed to add documents to Solr: Solr responded with an error (HTTP 400): [Reason: ERROR: [doc=catalogue.product.596]unknown field 'proizvoditel_mt'] What should i do? -
Graphene resolver for an object that has no model
I'm trying to write a resolver that returns an object created by a function. It gets the data from memcached, so there is no actual model I can tie it to. I think my main issue is I can't figure out what type to use and how to set it up. I'm using this in conjunction with Django, but I don't think it's a django issue (afaict). Here's my code so far: class TextLogErrorGraph(DjangoObjectType): def bug_suggestions_resolver(root, args, context, info): from treeherder.model import error_summary return error_summary.bug_suggestions_line(root) bug_suggestions = graphene.Field(TypeForAnObjectHere, resolver=bug_suggestions_resolver) Notice I don't know what type or field to use. Can someone help me? :) -
django entrys of author
I need to get list of all authors and their publishs {% for author in authors %} {{ author.name }} {% for publish in publishes %} {{ publish.title }} {% endfor %} {% endfor %} views.py: def authors_list(request): authors = Author.objects.all() publishes = Group.objects.filter(author=author) return render(request, 'app/authors_list.html', {'authors': authors,'publishes': publishes}) This way 'publishes' is not Defined. -
How to efficiently handle large file uploads with django+react?
I have a Django application with a React frontend, and need to upload multi-gigabyte files (around 8-12gb) selected from the React on a remote machine. Currently I'm using a simple form and uploading the files via fetch with formData in the body and then reading them out of request.FILES, however I'm not very happy with this solution, since it takes over a minute to upload the files even from the same computer to itself (and I'm not entirely sure why). Is there any way to speed up this process? The production environment for this is a gigabit local network without any external internet access so no cloud storage please. The data seems to be fairly compressible, easily reducing it's size by 30%+ when zipped/tared. Is there any way to compress during file uploads, or any parameters I can change on either end to speed up the process? It doesn't seem like an 8 GB file should take over a minute to upload from the same machine to itself, and in fact should theoretically be faster than that over a gigabit network. How can I streamline this? It'd be nice if I could make a progress bar on frontend but fetch … -
Django multi level template inheritance example?
Django documentation mentioned about three level template inheritance (http://djangobook.com/templates-in-views/). What is not clear is not to implement it. Can somebody give an actual example? -
How to configure "body" parameter to input JSON data in Django Rest Swagger UI for POST method?
I'm using django-rest-swagger 2.1.2 and python 2.7. In Swagger UI, for a post method, how can I configure the UI so that there is a body parameter for me to input JSON data along with other types of parameters, such as path? Thanks. -
Python pip install error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2
I'm having constant problems with installing packages for python. Previously, I just fixed the missing Visual C++ 14.0 error, now this. -
How to convert a date value to date type for comparison?
I'm reading a date value from the user and need to do a date comparison for that in django. I could not find any answer how to do that. What I exactly need is get the string converted to date so that it can be compared for equality/less than/greater than value. I obtain the form value as follows. start_date = form_new_task.cleaned_data['start_date'] I need to compare start_date value with date.today() for equality/less than/greater than. Can anyone let me know exact way to do this. I don't read any time portion from the input since I set the form input as a date field (not datetime). -
NoReverseMatch - 'viewflow' is not a registered namespace
When trying to run the custom UI demo in the cookbook I get the error: enter image description here Here is the copy and pasted traceback. I tried to look for an urls.py in viewflow to include in my project urls but couldn't find anything. How can I fix this? Thanks. -Paul -
Why are my django locales failing this way?
I'm trying to create a website that will be in both french and english, but my Django locales are not really working: on my machine, it works fine (with ./manage.py runserver) but when I send the code on my server, for deployment ... This is the page's code : Template <head> <meta charset="UTF-8"> <!-- Removed meta and useless stuff for clarity --> {% load i18n %} {% get_current_language as LANGUAGE_CODE %} <!-- Funny stuff: LANGUAGE_CODE seems to always be 'en-us' on prod --> <!-- Which is the default in settings.py, so yeah --> {% get_available_languages as LANGUAGES %} {% language fav_lang %} <!-- But this is empty on prod, while it is 'en' on my machine --> </head> <body> <!-- Same here, removed CSS stuff and pretty spacing --> {% trans "message" %} <br> {{ fav_lang }} </body> {% endlanguage %} And view: from django.template import loader from django.http import HttpResponse def index(request): template = loader.get_template("index.html") context = { 'fav_lang': request.LANGUAGE_CODE, } #So yeah, request.LANGUAGE_CODE is empty on prod return HttpResponse(template.render(context, request)) I pretty much figured from there that this is certainly my server config breaking things. But my server's settings.py and my local test are the same: import os … -
DRY principle in signals
Django 1.11.1 Below are signal handlers. This is about saving history. That is difference is signal (post_save and post-delete) and operation(+ or -). The code is mostly duplicated. Could you help me understand how can I adhere to DRY principle here? @receiver(post_save, sender=FramePlace) def save_add_place(sender, **kwargs): current_request = CrequestMiddleware.get_request() author = current_request.user instance = kwargs.get('instance') frame = instance.frame place = instance.place FramePlaceHistory.objects.create(author=author, operation="+", frame=frame, place=place) @receiver(post_delete, sender=FramePlace) def save_delete_place(sender, **kwargs): current_request = CrequestMiddleware.get_request() author = current_request.user instance = kwargs.get('instance') frame = instance.frame place = instance.place FramePlaceHistory.objects.create(author=author, operation="-", frame=frame, place=place) -
Chatterbot Django and Heroku (Issues Running Example)
I've had a couple of issues now and I've nearly got the Chatterbot example working for Django running on Heroku. Here is my example page. https://polar-basin-92507.herokuapp.com/ looking at the log the issue seems to be OperationalError: no such table: django_chatterbot_statement Full log https://hastebin.com/mucanobuki.sql git source https://github.com/gunthercox/ChatterBot/tree/master/examples/django_app/example_app From what I can tell their example was setup to use sqlite3 but heroku doesn't support that and that I need to somehow switch it over to postgres? Not sure and this is where I'd like some guidance. -
django-registration-redux add and save extra field
I have gone through lots of fix for this, so far the only one that works doesn't save users extra field just username, email and password. The user also gets a mail to activate account. What I want to do is be able to add extra fields especially first and last names and have them saved in the db. For the code that doesn't work so well my root urls.py looks like this url(r'^accounts/', include('registration.backends.default.urls')), My app models.py class user_profile(models.Model): user = models.OneToOneField(User, unique=True) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) other_name = models.CharField(max_length=24, help_text="Enter other names") timestamp = models.DateField(auto_now=False, auto_now_add=True) def __str__(self): return "%s" %(self.user.username) my app forms.py class UserRegForm(RegistrationForm): first_name = forms.CharField(widget=forms.TextInput()) last_name = forms.CharField(widget=forms.TextInput()) other_name = forms.CharField(widget=forms.TextInput()) my app regbackend.py def user_created(sender, user, request, **kwargs): form = UserRegForm(request.POST) data = user_profile(user=user) data.first_name = form.data["first_name"] data.last_name = form.data["last_name"] data.other_name = form.data["other_name"] data.save() from registration.signals import user_registered user_registered.connect(user_created) -
django registration-redux customfields
I'm trying to create a custom Django registration using registration-redux. I followed the django-registration-redux add extra field but when I did this, I get only custom fields in registration template, not usermodel fields like username, email, and password. models.py from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True) college = models.CharField(max_length=10,blank=False) branch = models.CharField(max_length=10,blank=False) year = models.CharField(max_length=10,blank=False) contact = models.IntegerField(blank=False) forms.py class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('college', 'branch', 'year') regbackend.py from registration.backends.default.views import RegistrationView from reg.forms import UserProfileForm from reg.models import UserProfile class MyRegistrationView(RegistrationView): form_class = UserProfileForm def register(self,request, form_class): new_user = super(MyRegistrationView, self).register(form_class) user_profile = UserProfile() user_profile.user = new_user user_profile.field = form_class.cleaned_data['field'] user_profile.save() return user_profile urls.py from django.conf.urls import url, include from django.contrib.auth import views as auth_views from reg.regbackend import MyRegistrationView urlpatterns = [ url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^registration/', include('registration.auth_urls')), url(r'^login/', auth_views.login, name='login'), ] -
Python/Django data to jquery alert box
I have a function which get some data. Result is for example: sites = Site.objects.filter(is_active=False) Function runs after button is pressed in django admin.py: def my_function(self, request): sites = Site.objects.filter(is_active=False) return HttpResponseRedirect(request.META["HTTP_REFERER"]) def get_urls(self): urls = super(ConfigAdmin, self).get_urls() my_urls = [ url(r'^my_function/$', self.export), ] return my_urls + urls This is my button code: <input type="submit" onclick="location.href='my_function/'" value="{% trans 'My_function' %}" /> I would like to put result to jquery alert box. How can I achieve that? -
django task that runs a function periodically
I am writing a django application that grabs data from an API and converts it to readable graphs. At the moment I have 3 functions in the views.py of my application. The first function grabs the data using requests and returns the data. The second function uses that data to decode it using a database, then it returns the interesting parts. The 3rd function will make graphs of that (I didn't get there yet). Now is the question, how do I get the request function run periodically to grab data and let the other functions "update"? I've read something about celery and some other things, but I'm very lost with those as it seems very difficult for me to understand. -
Django DB records disappears after first testcase run
I'm working on a project based on Django REST Framework. So I need to write some test cases for my REST API. I've written some basic class (let's call it BaseAPITestCase) inherited from standard DRFs APITransactionTestCase. In this class I've defined setUp method where I'm creating some test user which belongs to some groups (I'm using UserFactory written with FactoryBoy). When I run my tests, the first one (first test case method from first child class) successfully creates a user with specified groups, but the others don't (other test case methods in the same class). User groups just don't exist in DB at this time. It seems like existed records are deleted from DB at each new test case run. But how then it works for the first time? I've read Django test documentation but can't figure out why it happens... Can anyone explain it? The main question is what I should do to make these tests works? Should I create user once and store it in object variable? Should I add some params to preserve user groups data? Or should I add user groups to fixtures? In that case, how can I create this fixture properly? (All related models, … -
Django: Show progress on page for MySQL query?
I have several queries that take a long time (about 3 seconds each) to execute so I can have the data in the context to show on a page for my website. Is there a way that I can show the page, then indicate which of the queries have finished, something like: STARTED RUNNING QUERY 1 FINISHED RUNNING QUERY 1 *QUERY 1 RESULTS* STARTED RUNNING QUERY 2 FINISHED RUNNING QUERY 2 *QUERY 2 RESULTS* STARTED RUNNING QUERY 3 FINISHED RUNNING QUERY 3 *QUERY 3 RESULTS* STARTED RUNNING QUERY 4 FINISHED RUNNING QUERY 4 *QUERY 4 RESULTS* If relevant, here is my context: context = {'avg': execute_query('usp_WeatherTempAccuracy', [service, 'avg', 1])[0], 'first': execute_query('usp_WeatherTempAccuracy', [service, 'first', 1])[0], 'last': execute_query('usp_WeatherTempAccuracy', [service, 'last', 1])[0], 'decay': execute_query('usp_WeatherTempAccuracy', [service, 'decay', 1])[0]} where execute_query executes a stored procedure with the given arguments. Thanks. -
Django migration allow_migrate() missing 1 required positional argument 'model'
I'm trying to update my django application from version 1.8.18 to 1.11.1 and facing following problem TypeError: allow_migrate() missing 1 required positional argument: 'model' I searched a web and didn't find solution for my problem. Here is the traceback Traceback (most recent call last): File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models errors.extend(model.check(**kwargs)) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/db/models/base.py", line 1282, in check errors.extend(cls._check_fields(**kwargs)) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/db/models/base.py", line 1357, in _check_fields errors.extend(field.check(**kwargs)) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 909, in check errors = super(AutoField, self).check(**kwargs) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 219, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 321, in _check_backend_specific_checks if router.allow_migrate(db, app_label, model_name=self.model._meta.model_name): File "/srv/projects/TcellIDM/env/lib/python3.5/site-packages/django/db/utils.py", line 300, in allow_migrate allow = method(db, app_label, **hints) TypeError: allow_migrate() missing 1 required positional argument: 'model' Please help me to detect problem location or suggest me where should I go to solve the problem. -
Is it possible to send a Django HttpResponseRedirect but to a certain ID in the HTML page?
I have this simple view where the user confirms or declines an offer: def confirmoffer(request, offerid): offer = Offer.objects.get(id = offerid) if 'confirm' in request.GET: offer.traveler_approval = True; else: offer.traveler_approval = False; offer.save() return HttpResponseRedirect("/dashboard#excursionoffers/") I'm trying to return the user to her dashboard but to a certain part instead of the begining of the page thus I did this: dashboard#excursionoffers/ however a slash gets automatically added to look like this: http://127.0.0.1:8000/dashboard/#excursionoffers/ Which renders the id with no effect. That's the url for the dashboard: url(r'^dashboard/$', views.dashboard, name="dashboard"), -
Django, such table not found
I have set up a Project with Django and defined in the models some tables, also the table "Artikel": class Artikel(models.Model): anr = models.IntegerField(primary_key=True) anzahl = models.CharField(max_length=5) bez = models.CharField(max_length=255) preis = models.DecimalField(max_digits=7, decimal_places=2) info = models.CharField(max_length=255) def __str__(self): return 'Anr: {}, Anzahl: {}'.format(self.anr, self.anzahl) Then I have used makemigration and migrate to migrate the defined tables to the database (runserver also works without Errors) but when I open now the shell with the command: python manage.py shell When I use following commands to create a object and I save it: from shop.models import * a = Artikel(anr=1, anzahl=1, bez='test', preis=1.99, info='test') a.save() I get the following error by the method a.save() Traceback (most recent call last): File "<console>", line 1, in <module> File "E:\Python34\lib\site-packages\django\db\models\base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "E:\Python34\lib\site-packages\django\db\models\base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "E:\Python34\lib\site-packages\django\db\models\base.py", line 889, in _save_table forced_update) File "E:\Python34\lib\site-packages\django\db\models\base.py", line 939, in _do_update return filtered._update(values) > 0 File "E:\Python34\lib\site-packages\django\db\models\query.py", line 654, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "E:\Python34\lib\site-packages\django\db\models\sql\compiler.py", line 1148, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "E:\Python34\lib\site-packages\django\db\models\sql\compiler.py", line 835, in execute_sql cursor.execute(sql, params) File "E:\Python34\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "E:\Python34\lib\site-packages\django\db\backends\utils.py", … -
Validating the Database username and password in mysql
This regarding to Django website development project, i need to get the text value from html form and validate those value in mysql database. if the uname and pwd gets validated then throws to next page else pop up another window. Anyone kindly advise me -
Django rest framework authentication
I would like create authentication in Django. I'm trying to do everything according to this. Unfortunately, at this moment I have two problems. Firstly, when I try to add from rest_framework.authtoken import views I have conflict with from companies import views. I need views from authtoken to url(r'^api-token-auth/', views.obtain_auth_token). Secondly, when I use /api-token-auth/ I can login only superuser, other users visible in my database get response: { "non_field_errors": [ "Unable to log in with provided credentials." ] } -
macOS, Dockerfile mounting a folder cannot change locale
I'm trying to mount a folder with my docker file instead of copying it on build. We use git for development and I don't want to rebuild the image everytime I make a change for testing. my docker file is now as such #set base image FROM centos:centos7.2.1511 MAINTAINER Alex <alex@app.com> #install yum dependencies RUN yum -y update \\ && yum -y install yum-plugin-ovl \ && yum -y install epel-release \ && yum -y install net-tools \ && yum -y install gcc \ && yum -y install python-devel \ && yum -y install git \ && yum -y install python-pip \ && yum -y install openldap-devel \ && yum -y install gcc gcc-c++ kernel-devel \ && yum -y install libxslt-devel libffi-devel openssl-devel \ && yum -y install libevent-devel \ && yum -y install openldap-devel \ && yum -y install net-snmp-devel \ && yum -y install mysql-devel \ && yum -y install python-dateutil \ && yum -y install python-pip \ && pip install --upgrade pip # Create the DIR #RUN mkdir -p /var/www/itapp # Set the working directory #WORKDIR /var/www/itapp # Copy the app directory contents into the container #ADD . /var/www/itapp # Install any needed packages specified in requirements.txt #RUN … -
Django @property in modelfield:FieldError: Cannot resolve keyword while searching with Q lookup?
I'm currently learning Django and my models have @property methods to get values. What I'm trying to do is to generate profile_id automatically and assign to profile_id modelfield, for that, I use property method in the model with different Fieldname.while performing search by Q lookup getting below error. The Problem while searching: FieldError at /userprofiles/search/Cannot resolve keyword 'profile_id' into field. Choices are: _profile_id,first_name,last_name ..... My models: class UserProfile(models.Model): _profile_id = models.CharField(max_length=100, blank=True,default='',db_column='profile_id') first_name = models.CharField(('first name'), max_length=30, default='', blank=True) last_name = models.CharField(('last name'), default='', max_length=30, blank=True) def set_profile_id(self): return 'F%08d' % self.pk profile_id = property(set_profile_id) def __unicode__(self): return self.profile_id views: def search_profile(request): try: if 'q' in request.GET: querystring = request.GET.get('q') if len(querystring) == 0: messages.error( request, 'Invalid or empty string',extra_tags='alert') return redirect('userprofile') else: print querystring except: pass results = {} if 'q' in request.GET: querystring = request.GET.get('q') if querystring is not None: results = UserProfile.objects.filter( Q( first_name__contains = querystring ) | Q( profile_id__contains = querystring ) | Q( last_name__contains = querystring ) ) context = {'profiles': results} template = 'userprofiles/user_list.html' return render(request, template, context) else: return redirect('userprofile') context = {} else: return render(request,"userprofiles/user_list.html") Do properties work on django model fields?