Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting "doesn't exist or is m2m field" error on my uuid (primary key) when trying to save in DRF
I've written my own bulk save() because I can't get the internal save() method of ListSerializer to call the relevant method (create() & update()) depending on the query payload. The model is called Product whose primary key is a uuid. When I call Product's bound save() method with the updated_fields kwarg, I get: ValueError: The following fields do not exist in this model or are m2m fields: uuid Here's save(): def save(self): instances = [] result = [] # Note self.validated_data is a list of multiple OrderedDicts representing # the json of Product fields. Depending on the request, they will either # have uuids (so we will update these instances), or won't and hence # require creation. for obj in self.validated_data: uuid = obj.get('uuid', None) if uuid: instance = get_object_or_404(Product, uuid=uuid) update_fields = [k for k,v in obj.items()] for k, v in obj.items(): setattr(instance, k, v) instance.save(update_fields=update_fields) result.append(instance) else: instances.append(Product(**obj)) Product.objects.bulk_create(instances) result += instances return result Here's the relevant tail part of the traceback: File "/my/app/views/API/serializers.py", line 72, in save update_fields = [k for k,v in obj.items()] File "/lib/python3.5/site-packages/django/db/models/base.py", line 792, in save % ', '.join(non_model_fields)) ValueError: The following fields do not exist in this model or are m2m fields: … -
Django + angular integration
I have got lazy loading pages i.e. load-children ones in angular which are working when ng serve, but they do not work in Django. Any help would be good -
Sending form to another view django
I am building a website and I want various views that will ask the user to request a quote from our page. I want to keep the code as DRY as possible so I am writing a view quote which will receive the quote requests from various views and, if there is a validation error redirect back to the page that made the request. I managed to solve this using the super bad practice 'global variables'. I need a better solution, I would like redirecting to respective view with the current form so I can iterate through the form.errors. Here is my code: def send_quote(request): form = Quote(request.POST) if form.is_valid(): # do stuff when valid return redirect('Support:thanks', name=name or None) quote_for = request.POST['for_what'] global session_form session_form = form return redirect('Main:' + quote_for)#Here I would like to send form insetead of storing in global variable Thanks in advance and pardon if this is a stupid question but I have googled and nothing. -
Django Form Field validation
I have a form that requires a URL as input. I would like to check if the URL begins with http:// or https://. If it doesn't have one of these two 'stings' in the beginning, the form submission should give an error. I don't have any clue on how to get started with this and could not find any info based on my limited knowledge of django and I have no clue what search terms to look up. A basic hint would be a great help. Thanks! My current forms.py has a form based on a model: class AddUrlForm(forms.ModelForm): class Meta: model = forwards # fields = '__all__' exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"] models.py: class forwards(models.Model): uniqueid = models.AutoField(primary_key=True) user = models.CharField(max_length = 150) urlA = models.CharField(verbose_name="URL Version A", max_length = 254) counterA = models.DecimalField( max_digits=19, decimal_places=0,default=Decimal('0')) urlB = models.CharField(verbose_name="URL Version B",max_length = 254) counterB = models.DecimalField( max_digits=19, decimal_places=0,default=Decimal('0')) timestamp = models.DateTimeField('date created', auto_now_add=True) shortcodeurl = models.CharField(max_length = 254) html segment where that shows how the form is integrated: <form method="post"> {% csrf_token %} {% for field in forwardform %} <span>{{ field.label_tag }} </span> <p style="color: black">{{ field }} </p> {% for error in field.errors %} <p style="color: … -
Going from PostgreSQL JSONField to JSON object in Django template
I am trying to send a JSON object from a Django PostgreSQL database to a Django template. Here is my models.py # models.py from __future__ import unicode_literals from django.contrib.postgres.fields import JSONField from django.db import models class Net(models.Model): net_name = models.CharField(max_length=200) def net_default(): return {"net_name": "None", "graph_data": "None", "city_data": "None"} data = JSONField(default=net_default()) def __unicode__(self): return self.net_name Here is my views.py # standard includes from django.shortcuts import render # my includes from django.http import HttpResponse from django.template import loader # get nets from .models import Net def index(request): net_q_set = Net.objects.order_by('net_name') context = { 'nets': net_q_set, } return render(request, 'viewer/index.html', context) So I have a sidebar in which the user selects a network from the 'nets' JSON object. Then a javascript function which takes the selected network name should iterate through the JSON object to get the network's nodes and get each node's latitude and longitude. I am able to iterate through the names with the following code (this code works and produces what I want): {% for name in nets %} <li><a href="javascript:plotMap('{{name}}');">{{name}}</a></li> {% endfor %} But I am having an issue establishing the JSON object in the javascript script. I have tried: <script> var nets = JSON.parse({{ nets }}) … -
I would like to build a Django environment using uWsgi and nginx with Ansible
I am using Ansible to build a local environment. I want to use the Django framework. For that, I am using uWsgi and Nginx. I wrote the following AnsibleScript. - name: shell: bash -lc "/home/vagrant/.pyenv/versions/3.6.0/envs/myproject/bin/uwsgi --ini /home/myproject/uwsgi.ini &" args: chdir: /home/myproject/ become: false However, Django's initial page is not displayed. Enter vagrant's machine with vagrant ssh, When the following command is executed, the page of Django is displayed. /home/vagrant/.pyenv/versions/3.6.0/envs/myproject/bin/uwsgi --ini /home/myproject/uwsgi.ini & The log of Nginx when the initial page is not displayed is described below. 2017/08/03 18:42:32 [error] 20657#0: *11 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.50.1, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://127.0.0.1:8001", host: "192.168.50.13:8000", referrer: "http://192.168.50.13:8000/" Is there a solution? Thanking you in advance. -
ImproperlyConfigured url
I was trying Django REST Framework. I am using Django 1.10 and DRF 3.6.2. What have I missed, can anybody please tell me!!! I have created an "api" app in a sample django project. In my serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['url', 'username', 'email',] In my views.py from django.contrib.auth.models import User from rest_framework import generics from .serializers import UserSerializer class UserListAPIView(generics.ListAPIView): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer In my projects urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('api.urls', namespace='users')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] In my app "api" urls.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^api/users', views.UserListAPIView.as_view(), name='user-list'), ] It looks everything fine. But when I call the http://127.0.0.1:8000/api/users/ It is showing --- -
Passing extra data while passing through serializer django rest framework
I am looking to pass extra data in the serializer but unable to do so. Below is my code views.py device_id = request.META.get('HTTP_DEVICE', '') user_data = request.data serializer = UserSerializer(data=user_data) I want to pass device id as well with user_data. I tried a dictionary but it is not getting the data. Suggest a syntax -
How to get django tables2 working on a Cloud 9 django instance
Can't seem to get django tables2 to work. I am using Cloud 9 dev environment on their cloud service. I installed django tables2 through sudo pip install. I added 'django_tables2' to the installed apps list. Here is my model: class Project(models.Model): project_name = models.CharField(max_length=150) project_type = models.ForeignKey(Project_Type) created_date = models.DateField() start_date = models.DateField() end_date = models.DateField() pm_scope = models.IntegerField() dev_scope = models.IntegerField() design_scope = models.IntegerField() testing_scope = models.IntegerField() Here is my view: def project_list(request): table = Project_table(Project.objects.all()) return render(request, 'person_list.html', { 'table': table }) Here is my table class in tables.py: import django_tables2 as tables from copacity.models import Project class Project_table(tables.Table): class Meta: model = Project The error I keep getting is "ImportError: No module named django_tables2copacity.apps" (copacity is my apps name inside the django instance) I'm new to django so I'm quite lost on this one. Any suggestions on what I am doing wrong? -
Erro ImproperlyConfigured DetailView Django 1.8
How to corrige error? See my error: ImproperlyConfigured at schedule/confirmed/c4e068dc-9e89-4fa5-9a66-cfb5ec6a306b/ ScheduleConfirmed is missing a QuerySet. Define ScheduleConfirmed.model, ScheduleConfirmed.queryset, or override ScheduleConfirmed.get_queryset(). And see my views.py # views.py class ScheduleConfirmed(generic.DetailView): modal = Schedule template_name = 'schedule-confirmed.html' # def get_context_data(self, **kwargs): # context = super(ScheduleConfirmed, self).get_context_data(**kwargs) # obj = self.object # return context my urls.py #urls.py url(r'^schedule/confirmed/(?P<pk>[^/]+)/$', views.ScheduleConfirmed.as_view(), name='schedule_confirmed'), my models.py #models.py class Schedule(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) creator = models.ForeignKey(User, related_name='schedule_creator') # ... -
RuntimeError: Never call result.get() within a task Celery
I am using celery to send a task to remote server and trying to get the result back. The state of task is constantly updated using update_state method on remote server. I am sending task using app.send_task('task_name') getting results of celery task is a blocking call and i don't want my django app to wait for result and timeout. So i tried running another celery task for getting results. @app.task(ignore_result=True) def catpure_res(task_id): task_obj = AsyncResult(task_id) task_obj.get(on_message=on_msg) But it results in the error below. Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 367, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 622, in __protected_call__ return self.run(*args, **kwargs) File "/home/arpit/mateverse/admin_dashboard/tasks/results.py", line 42, in catpure_res task_obj.get(on_message=on_msg) File "/usr/local/lib/python2.7/dist-packages/celery/result.py", line 168, in get assert_will_not_block() File "/usr/local/lib/python2.7/dist-packages/celery/result.py", line 44, in assert_will_not_block raise RuntimeError(E_WOULDBLOCK) RuntimeError: Never call result.get() within a task! See http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks Is there any workaround for this error. Do I have to run a daemon process for getting the results? -
Trying to get login required to work when trying to access protected pages
Django 1.11 Django REST Framework (DRF) 3.6 DRF-JWT 1.10 AngularJS 1.6.5 ui-router 1.0.3 Fairly new to all of this technology and have been messing with this issue for several days now. Learned about this stack (minus UI-router which I just switched to a week ago) through the following class and repository: https://www.udemy.com/django-angularjs/learn/v4/overview https://github.com/codingforentrepreneurs/Django-AngularJS/tree/master/src These are the directories that are probably the most relevant to my issue: Config and JS: https://github.com/codingforentrepreneurs/Django-AngularJS/tree/master/src/static/js/app Login-required interceptor: https://github.com/codingforentrepreneurs/Django-AngularJS/tree/master/src/static/js/app/core/interceptors Service, pages where login is required, and interceptor is utilized: https://github.com/codingforentrepreneurs/Django-AngularJS/tree/master/src/static/js/app/core/comment I am trying to adapt it for my project. I have read several tutorials on using ui-router purely for this purpose, but they don't seem to use DRF-JWT or are missing important steps that a newb like me needs. Anyway, I have two urls: / /dashboard The former is the login, /dashboard requires authorization and should route to / if the person isn't logged in. Before I started trying to implement this, one could just type in /dashboard without being authenticated and view it. I have verified that when a person logins in the token through DRF-JWT it is being generated and written to the cookie as I can console.log it on successful login. Since I … -
baffled by python __str__ method and unicode behaviour
This is Python 2.7. Don't judge me. :) I have a Django application where the class file is being used for a bit of auditing. For historical reasons I have a __str__ method in this class, and I am trying to return something useful. def __str__(self): return "%s %s" % (self.guid, self.setside_username) Now, this failed with non-ascii characters in the setside_username, as the audit log was indirectly calling __str__ like so log.info("change to %s", obj) I tried renaming __str__ to __unicode__ but it still failed in the same location. So I tried sanitize the string by ascii encoding it and having the encoder replace anything it didn't understand. def __str__(self): return "%s %s" % (self.guid, self.setside_username.encode('ascii', 'replace') but that line fails with a UnicodeDecodeError, which baffles me because I thought that call would tell the encoder to replace anything it doesn't understand. So to prove that I don't understand the difference between encode() and decode(), I s/encode/decode and suddenly the error is gone. And I haven't a clue why. I thought decode created unicode objects and encode created byte strings, so why would decode on a unicode object help here? Worse, my little test script that simply prints the object … -
Setting a default value for a django input field
I'm using jquery-number on the front end to provide as-you-type currency formatting, but this doesn't seem to play nice with input number fields. So inn Django I've overridden the default form field for my numerical field like so: self.fields['budget'] = forms.CharField( empty_value='0') I've set the empty_value to 0, but it totally ignores it and I still get a blank field. I thought the empty_value was the default value of the input, but maybe I am not understanding it correctly. How can I set a default field? Is it having an issue because I'm forcing a different input type? In the model it is a decimal field: budget = models.DecimalField(max_digits=15, decimal_places=2, validators=[ MinValueValidator(0), -
Why am I having this database issue?
I am working on a Python/Django project, and we need to use two databases. Following the documentation I added a second database like this: DATABASE_URL = os.getenv('DATABASE_URL', 'postgres://*******:********@aws-us-***********:*****/*****') CURRENCIES_URL = os.getenv('CURRENCIES_URL', 'postgres://*******:********@aws-us-***********:*****/*****') DATABASES = { 'default': dj_database_url.parse(DATABASE_URL), 'currencies': dj_database_url.parse(CURRENCIES_URL) } The parse() method returns the data in the format the object is expecting. Then, I have this code: currencies = connection['currencies'].cursor() Basically this allows me to run custom SQL code on the database, by returning its cursor and storing it in currencies However when running this code I get this in the console: url(r'^', include('btcmag.urls', namespace="btcmag")), File "/Users/john/.virtualenvs/btcmag/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/john/btcmag/btcmag/urls.py", line 7, in <module> from . import views File "/Users/john/btcmag/btcmag/views.py", line 4, in <module> from .apis import getTrendingArticles, getTickers, getCurrency, getHistory File "/Users/john/btcmag/btcmag/apis.py", line 9, in <module> currencies = connection['currencies'].cursor() TypeError: 'DefaultConnectionProxy' object has no attribute '__getitem__' Some clarification: When I run just currencies = connection.cursor() it uses the default database and works just fine, which tells me it's not the connection module If I switch currencies and default in the databases settings it works also fine - running currencies = connection.cursor() - by using the … -
IntegrityError: (1048, "Column 'username' cannot be null")
From the email field form the well known User(AbstractUser) class, I got I little error : IntegrityError: (1048, "Column 'username' cannot be null"). This error is displayed when I uncomment the following method in CustomerBaseForm(forms.Form) class : def clean_email(self): email = self.form.cleaned_data.get('email') qs = User.objects.filter(email=email) if self.form.instance not in (None, ''): # This is from the update form, so we exclude the updated customer # from the search results qs = qs.exclude(pk=self.form.instance.pk) if qs.count(): raise ValidationError( _('This email is already in use') ) How could I fix this method so that it works fine? Tell me please if it misses something in the question. -
How to populate inlineformsets in Django
I have an inlineformset_factory, CoinInfoFormSet = forms.inlineformset_factory(Portfolio,CoinInfo ,form = CoinForm,can_delete=False,extra=1) That produces my inlineformset, But when i try to populate it in my updateview, the data is unbound. class UpdatePortfolio(LoginRequiredMixin,UpdateView): model = Portfolio fields = ('title','is_public') template_name = 'hello/edit_create_portfolio.html' def get_context_data(self, **kwargs): print(self.get_object()) print( CoinInfoFormSet(instance=self.get_object(), prefix='coininfo_set').is_bound) as output i get: portfolio Object false How should i populate my inlineformset? -
Django: reverse() does not find view with args/kwargs given
There are a few posts related to my problem. However, none seems to solve the following issue: I have defined urls in myapp/urls.py: app_name = "myapp" urlpatterns=[ url(r'^$', views.index, name="index"), url(r'^adduser/$', views.addUser, name="adduser"), ] and corresponding views in myapp/views.py: def index(request, status_msg=None, error_msg=None): return HttpResponse(render(request, "myapp/index.html", context={"error_message":error_msg, "status_message":status_msg})) def addUser(request): try: uname=request.POST["user_name"] except KeyError: url = reverse("myapp:index", args=(None, "No user name specified.")) return HttpResponseRedirect(url) # ... adding user to db ... url = reverse("myapp:index", args=("Added user '%s'"%uname,)) return HttpResponseRedirect(url) Either variant of passing arguments to index() from the redirect in addUser() yields an error of the kind Reverse for 'index' with arguments '(None, u'No user name specified.')' not found. 1 pattern(s) tried: [u'myapp/$'] I don't get what I'm doing wrong here. Seems the index view is found but not recognized to allow any arguments aside the request? Using kwargs instead of args does not help, either. Any suggestions are highly appreciated. Thanks already! -
Why django-pipeline does not collect static?
I've followed django-pipeline docs and I am having an issue when collecting static, the console shows that the specified file is not found. Here's how my app tree is configured : Globalapp : (root folder) - src (the base that contains all my django files) -- app (where settings.py is) ... -- pages (where static files are) --- static - css -- main.css ... And here's how I configured my settings.py : INSTALLED_APPS = [ ... 'pipeline', ] ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'COMPILERS': ( 'pipeline.compilers.stylus.StylusCompiler', ), 'STYLESHEETS': { 'pages': { 'source_filenames': ( 'css/main.css', ), 'output_filename': 'designer.css', }, }, } I am working in localhost for now, the error occures when I run pip manage.py collectstatic, have I done something wrong ? -
Show Objects and Relevant Sub-Objects
I have two models, Category and Topics. Each Topic belongs to a Category (via foreign key). What i want to do in my template is display a category, and then under it show all the topics that have been filed under that specific category. Here is my models.py: class Category(models.Model): name = models.CharField(max_length=55) class Topic(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=55) Any idea on how I can accomplish this? Thanks. -
How to update a model in the Database with Django Rest Framwork Serializer fails?
If I run my code at the first time, it works successfully. Data are stored in the database and the http code is 200. If I change some data on the client side and try to save the model again, I reach the following error. I read on the django doc, hat i can use Save as "create" and "update" as well. error message heating mapping with this zone already exists views.py @detail_route(methods="post") def save(self, request): zone = request.data.get('zone') data = json.loads(zone) serializer = HeatingMappingSerializer(data=data) valid = serializer.is_valid(raise_exception=True) if(valid): result = serializer.save() self.response = {"result": True, "data":HeatingMappingSerializer(result).data, "message": "Erfolgreich gespeichert"} return JsonResponse(self.response, safe=False) -
Django + PostgreSQL: database representation of JSONField is changing
PostgreSQL 9.4.12 Django 1.10.7 With this minimal class : from django.contrib.postgres.fields import JSONField class Foobar(models.Model): extra_data = JSONField(blank=True, default="") I run manage.py shell_plus : In [2]: a=Foobar.objects.create() In [3]: a.extra_data={} In [4]: a.save() In [6]: a.extra_data Out[6]: {} In [7]: a.refresh_from_db() In [8]: a.extra_data Out[8]: '{}' In [9]: a.save() In [10]: a.refresh_from_db() In [11]: a.extra_data Out[11]: '"{}"' What could be the reason the JSONField value is quoted at each database save? -
django-extra-views expose InlineFormSet field values into get_context_data() and forms_valid() methods
I would like to get access to fields of the InlineFormSet for consumption into the View. Here is an example based on https://django-extra-views.readthedocs.io/en/latest/views.html#createwithinlinesview-and-updatewithinlinesview: from extra_views import InlineFormSet, CreateWithInlinesView, class ItemsInline(InlineFormSet): model = Item class TagsInline(InlineFormSet): model = Tag class OrderCreateView(CreateWithInlinesView): model = Order inlines = [ItemsInline, TagsInline] def get_success_url(self): return self.object.get_absolute_url() How do I expose the InlineFormSet fields in the get_context_data() and forms_valid() methods? Warning: Code below fails! class OrderCreateView(CreateWithInlinesView): [... see above ...] def get_context_data(self, **kwargs): context = super(OrderCreateView, self).get_context_data(**kwargs) if self.request.POST: context['items'] = ItemsInline(self.request.POST) context['tags'] = TagsInline(self.request.POST) else: context['items'] = ItemsInline() context['tags'] = TagsInline() return context def forms_valid((self, form, inlines): [...] return super(OrderCreateView, self).forms_valid(form, inlines) -
How to change datetime format in Django-filter form?
I'm creating a filter which contains datetime range choice. I would like user to be able to input date in this format: 24.08.2017 17:09 From docs, it is possible to specify a widget (from django.forms) and widget has attribute input_formats. So this would be a solution: datetime_range = django_filters.DateTimeFromToRangeFilter(method='datetime', label=u'Čas od do',widget=forms.widgets.DateTimeInput(format="%D.%m.%Y %H:%M:%S") The problem is that it uses DateTimeFromToRangeFilter which uses two DateTimeInput fields. So if I specify the widget, it renders one DateTimeInput instead of two inputs. So the question is, how to specify the format (without changing widget)? -
ImportError: No module named menu
I'm trying to customize the admin interface with django-admin-tools. I'm following https://django-admin-tools.readthedocs.io/en/latest/customization.html The menu.py has been created successfully with python manage.py custommenu in my project directory. When I add ADMIN_TOOLS_MENU = 'project_name.menu.CustomMenu' to my settings.py, as indicated I get the follwoing error: ImportError: No module named menu