Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Creating an instance via the serializer with a foreign key reference
I have a agencies and users. I want to create User instances via the UserSerializer which have an agency_id. However the serializer's validated_data does not have the agency_id after calling is_valid(). class Agency(models.Model): name = models.CharField(max_length=60) class User(modes.Model): username = models.CharField(max_length=60) agency = models.ForeignKey(Agency, blank=True, null=True) class UserSerializer(serializers.ModelSerializer): class Meta: User = get_user_model() model = User fields = ( 'id', 'username', 'agency_id' ) read_only_fields = ['id'] Try to create a user via the serializer which belongs to the Acme Agency: agency = Agency.objects.create(name="Acme Agency") serializer = UserSerializer(data={ 'username':'wiley', 'agency_id': agency.id} ) serializer.is_valid() # True serializer.validated_data.get('agency_id') # None Creating a user via the UserManager using the agency id works just fine: user = User.objects.create(username='wiley', agency_id=1) user.agency.id # 1 -
Dnago "str" object has no attibute 'data'
I have this error when I try to save a post in my database in django. What am I doing wrong and how can I fix it? AttributeError at /account/create-post 'str' object has no attribute 'data' I have this field image , my model: class Post(models.Model): created_date = models.DateTimeField() title = models.CharField(max_length=100) profile_image = models.ImageField(upload_to='poze', blank=True, null=True) text = models.CharField(max_length=1000, default='Nimic', blank=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) View: class CreatePost(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'create_post.html' def get(self,request): serializer=CreatePostSerializer() return Response({'fields':serializer}) def post(self, request): serializer = CreatePostSerializer(data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer.data}) user = UserProfile.objects.filter(username=request.user.username).first() serializer.save(user=user) return redirect('mainPage') Create_post.html: {% extends 'base.html' %} {% load rest_framework %} {% block content %} <div class="offset-3 col-md-6"> <form action="{% url 'create_post' %}" method="POST"> <div class="form-group"> {% csrf_token %} {% render_form fields %} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> {% endblock %} URL: url(r'create-post$', login_required(CreatePost.as_view()), name='create_post'), What is in console: Internal Server Error: /account/create-post Traceback (most recent call last): File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 158, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 156, in _get_response response = response.render() File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\response.py", line 106, in render self.content = self.rendered_content File "C:\Users\Intern\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\response.py", line 72, in rendered_content ret … -
Why am I receiving this NoReverseMatch error?
I am following the Mozilla tutorial for a simple Django web application here. I am really going to use it as a template for a website that I'm making for my job involving equipment management. So, when trying to add a page with a link /catalog/models (model being the part number of a piece of equipment) I receive the following error. I feel like it could be a small error that I'm just not seeing. Apologies for the terrible formatting. /catalog/models.py: from django.db import models from django.urls import reverse the URL patterns import uuid import datetime class Book(models.Model): """Model representing a book (but not a specific copy of a book)""" title = models.CharField(max_length = 200) author = models.ForeignKey('Author', on_delete = models.SET_NULL, null = True) # Foreign Key used because book can only have one author, but authors can have multiple books # Author as a string rather than object because it hasn't been declared yet in the file. summary = models.TextField(max_length = 1000, help_text = 'Enter brief descp. of book') #TextField for longer descp. isbn = models.CharField('ISBN', max_length = 13, help_text = '13 character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') #ManyToManyField used because genre can contain many books. Books can cover many genres. … -
Updating django timezone with user profile time
I have an admin chang_list.html that I am extending that looks like this {% extends "admin/change_list.html" %} {% load i18n admin_static admin_list %} {% load tz %} {% block result_list %} {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %} {% timezone request.user.userprofile.timezone %} {% result_list cl %} {% endtimezone %} {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{ % endif %} {% endblock %} I have a click_time field in my model that is store in the database as UTC. From my understanding of the django timezone funciton it should be set to request.user.userprofile.timezone, 'America/Chicago' in my case. But the click_times are still being displayed as 'utc'. -
HAPI-FHIR vs smart vs FHIR-NET-API
HAPI-FHIR vs smart vs FHIR-NET-API ,can any one help me pros and cons for this api's and which is the best for eclinical works and all scripts emr software. my requirement is to DEVELOPMENT & INTEGRATION OF FHIR WITH OPEN-SOURCE EMR & RELATIONAL DATABASES and perform some analytics on that data. -
Django nav link not working
When I change from one page to another nothing happens except teacher page and from teacher page I cannot go any other pages! <ul class="sidebar-menu" data-widget="tree"> <li class="treeview"> <a href="Dashboard:index"> <i class="fa fa-dashboard"></i> <span>Current Courses</span> </a> </li> <li class="treeview"> <a href="Dashboard:result"> <i class="fa fa-th"></i> <span>All Batch Records</span> </a> </li> <li class="treeview"> <a href="{% url 'Dashboard:course' %}"> <i class="fa fa-list"></i><span>Courses</span> </a> <li> <a href="{% url 'Dashboard:teacher' %}"> <i class="fa fa-user"></i> <span>Teachers</span> </a> </li> </ul> my urls.py file: from django.urls import path from . import views app_name = 'Dashboard' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('course/', views.course, name='course'), path('teacher/', views.teacher, name='teacher'), path('student/', views.student, name='student'), path('result/', views.result, name='result'), ] When I change from one page to another nothing happens except teacher page and from teacher page I cannot go any other pages! -
Django access to language code in filter function
I have some list of items in django template and I loop over this list to build a table od my records. In one of fields I have a dictionary key (int from 1 to 12). I wrote a filter to change key integers for a good looking names. I would like to check what is currently user language before filter returns. It is possible to check language code in filter/tag function in Django? This is my loop in template: {% for field in fields_list %} <div class="row row-eq-height"> <div class="col-padding-5"><div class="cart-tab-row">{{ forloop.counter }}</div></div> <div class="col-padding-5"><div class="cart-tab-row">{{ field.field_name }}</div></div> <div class="col-padding-5"><div class="cart-tab-row">{{ trans field.c_type|get_cname }}</div></div> <div class="col-padding-5"><div class="cart-tab-row">{{ field.area|floatformat:2 }}</div></div> <div class="col-padding-5"><div class="cart-tab-row">{{ field.price|floatformat:2 }}</div></div> </div> {% endfor %} This is my filter function @register.filter def get_cname(key): ctype = CesTypesDict.objects.filter(id=key)[0] return ctype.english_type_name In normal view I access this information from request attribute, but in filter I don't have access to request object. -
Django - How to display foreign key fields as Text Inputs in a ModelForm instead of dropdowns while using generic view fields?
I am new to Django and I have been digging through the documentation and other google search results but I can't seem to find an answer that works for me. Basically I created a ModelForm "RequisitionForm" that uses the "Requisition" model. Requisition model contains 4 FK fields that as of right now if I display the form the fields display as drop-downs. I understand that is how django will display them by default. I would like the user to be able to write in what they want and when they hit submit it will preform validation and ass the record to 2 tables. I may be going about this the wrong way, I'm not sure if I should be using my "Item" model as the model for the ModelForm since thats the primary table I guess. Basically I need some of the Item Model fields and additional fields that do not belong to the Item Model to be presented and when the form is filled out it will update the 2 respective tables which is the Item Model and the Requisition Model. I am also utilizing the Generic View Fields, create, update, and delete. Im not sure what exactly to … -
setting instance for forms in UpdateView
i have an UpdateView with a couple of forms and i'm trying to understand how to set the instance for the other form because the first form work just fine but the second form is always empty and i cant figure out how to set the instance for that modelform . class ProfileUpdateView(UpdateView): # model = User queryset = User.objects.all() form_class = UserForm second_form_class = ClientForm template_name = 'accounts/update.html' def get_object(self): user = get_object_or_404(User , username__iexact=self.kwargs.get('username')) return user def get_context_data(self, **kwargs): user = self.object profile = Client.objects.get(id = user.clients.id) context = super(ProfileUpdateView, self).get_context_data(**kwargs) if user.is_client and 'ClientForm' not in context: context['client_form'] = self.second_form_class(self.request.GET, instance=profile ) return context the question now how/where can i set the instance for the second form and where is the first form instance is set . -
wkhtmltopdf (pdfkit) Could not connect to any X display
I am trying to use wkhtmltopdf with Django ,nginx,uwsgi it works perfectly on development env running using manage.py runserver but when serving with nginx ans uwsgi i get this error: wkhtmltopdf exited with non-zero code 1. error: QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-isp' qt.qpa.screen: QXcbConnection: Could not connect to display Could not connect to any X display. Exception Location: /home/isp/Env/isp/lib/python3.6/site-package/pdfkit/pdfkit.py in to_pdf, line 159 the command : wkhtmltopdf http://www.google.com output.pdf works perfectly on terminal and i used this guid to deploy the Django app https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04#setting-up-the-uwsgi-application-server i think it is related to virtualenv , i tried using this wrapper https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server but still having the same error mycode : import pdfkit pdfkit.from_file("./invoices/invoice"+str(booking_id)+"-"+str(invoice_id)+".html", "invoices/invoice_initial"+str(booking_id)+"-"+str(invoice_id)+".pdf") -
How can I make a decorator that checks if the form(any custom form) is submitted or not in django?
I am making a webpage like food ordering in restaurant. So I have included a form in which customer must have to fill the form which includes Name, Table number, Password, etc to order the food. For that I want to make a decorator so that customer can not directly go to another page directly without filling the form. from django import forms from order.models import LoginModel from django.core import validators from django.core.validators import MinValueValidator,MaxValueValidator def check_password(value): if value != 'onetofour': raise forms.ValidationError("Invalid Password") class LoginForm(forms.ModelForm): username = forms.CharField(max_length=128) Table_number = forms.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(4)]) password = forms.CharField(widget = forms.PasswordInput,validators[check_password,]) class Meta: model = LoginModel fields = '__all__' -
Django Celery task for email notification after create
can somebody explain me how create task for email notification after create some question/answer in application from simply based on createview. and another question can i send email on iteration for user emails -
Django custom command object ID not found
I'm trying to build a custom Django command which can be run against individual model objects When I check in shell I see the object fine >>> Obj.objects.get(id=1) <Obj: the object I'm looking for> My custom command however looks like the below: # app/management/update.py class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--id') def handle(self, *args, **options): if options['id']: try: obj = Obj.objects.get(id=options['id']) # do things except: raise CommandError('no object with ID: "%s"' % options['id']) else: # do other things Running this I get the error message >>> python manage.py update CommandError: no object with ID: "2" Any help appreciated. Thanks -
Django: How to change default SignUp fields
I am struggling with changing default UserCreationForm - I was able to add one additional field by creating child class: class SignUpForm(UserCreationForm): display_name = forms.CharField(max_length=32, help_text='Your display name') class Meta: model = User fields = ('username', 'display_name', 'password1', 'password2', ) def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.display_name = form.cleaned_data.get('display_name') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('user/home') else: form = SignUpForm() return header.views.show(request, 'userpanel/register.html', context={'form': form}) Together with template: <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text | safe }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error | safe }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> I was able to create following page: But I have the problem with changing description texts on a page. Now, if I would like to change Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. to something else, how to do it? -
unable to except ValueError thrown by mongoengine
I'm trying to catch a ValueError that occurs due to the skip parameter equal to a negative number. For example, try: MyModel.objects.skip(-1) except ValueError as error: print(error) does not do anything. It doesn't error out with ANY message nor does it do anything else. What I want is just to catch the ValueError and handle it appropriately. If I except TypeError (that is not raised) instead of ValueError it displays the same behaviour. -
Staticfiles are not loaded because the urls contains "&" instead of just "&"
Im trying to implement "django jet" which is a template for the admin interface. After installing it i run collectstatic and the staticfiles are correctly added to my s3 bucket. However when I go to the admin page some of the files can't be loaded because the genereted urls are incorrect. The urls seperates the authorization query parameters with "&" instead of just "&". Can I somewhow controll the genereted urls? -
Simplify query spanning multiple objects
I am trying to filter human query based on which departments the requesting user manages. Ando (example Human) manages three depts. I want to return all humans in those three departments. Humans can have multiple contracts. Each contract attaches the human to a department: class Contract(models.Model): human = models.ForeignKey(Human, related_name='contracts', on_delete=models.CASCADE) department = models.ForeignKey(ShowDepartment, related_name='contracts', on_delete=models.CASCADE) What I have below works, but I'm sure there is a more efficient way to make this query. output_humans = [] depts = self.request.user.human_profile.departments_managed() for d in depts: contracts = Contract.objects.filter(department=d) for c in contracts: if c.human not in output_humans: output_humans.append(c.human) -
cannot import name setting error while importing psa
I wanted mobile users to get google signin in my django application. And I followed this : https://stackoverflow.com/a/28946767 And got this error File "/usr/local/lib/python2.7/dist-packages/social/apps/django_app/utils.py" in 1. from social_django.utils import load_strategy, load_backend, psa, setting, BackendWrapper, strategy Exception Type: ImportError at / Exception Value: cannot import name setting How can I work around this? Thank you in advance -
check that tag is used in template only once
I write a custom tag for using in django templates: {% my_custom_tag %}. Using django channels it extends some page functionality. But I a worried that users may by accident insert this tag twice to a template, and that can create some issues because channels will deliver the same info twice etc. Is there any relatively simple way to check that the tag is used in a template only once and raise an error otherwise? -
Setting up a SRID to a Leaflet - Geodjango
I have data in my Postgres DB which are in 31277 projection. Anyway, I am using Leaflet map to show them with Geodjango. Right now, my data are moved somewhere down in the map, so I need to change the projection of the Leaflet map. In documentation (http://django-leaflet.readthedocs.io/en/latest/advanced.html) is written just to add SRID attribute to LEAFLET_CONFIG variable, which I did. Like here: LEAFLET_CONFIG = { 'DEFAULT_ZOOM': 13, 'MIN_ZOOM': 2, 'MAX_ZOOM': 18, 'SRID':31277 } But after I added SRID attribute I got an error when I tried to access to that page with a map: "GET /static/proj4js/31277.js HTTP/1.1" 404 1770 Also, I get same error for the WGS84 - 4326 which is default epsg. -
Django slow on production
I'm facing performance issues since a few weeks and it became huge since 1 week. I run an Ecommerce website with Django. It’s hosted at Linode cloud hosting. My set up is : 1 DB Linode 8GB with Postgres & Redis 1 Web Linode 8GB with Supervisor+Gunicor+Nginx+Django and Celery 1 Elastic Linode 8GB with elasticsearch On June 13th I installed elasticsearch on the DB Linode and upgraded django from 1.11.5 to 2.0.6. Everything was working fin exept on the linode manager the Web Linode stats was high on CPU. (between 80/100%) Then it started to get a bit slower. My Web server was a 4GB plan at the time, so I decided to upgrade it to the 8GB on July 3rd. It was better but still a bit slow. Then it slowly became slower and slower, until next week when it was too much (15/20s to display cart, sometime 504 errors …) I restarted everything (supervisor, nginx, postgress, elastic, redis …) I purged every caches … I took a look at my traffic, to see if a bot was crawling … I rebooted every linode. Still the same. I took a look at my git history, if I pushed a … -
Unexpected UTF-8 BOM Deploy Django-app to Heroku
I am trying deploy my Django application to Heroku. I've done almost all the steps in this tutorial. But when I try to finish the last step($ git push heroku master) , Heroku returned the following error: -----> Python app detected ! The latest version of Python 3.6 is python-3.6.6 (you are using python-3.7.0, which is unsupported). ! We recommend upgrading by specifying the latest version (python-3.6.6). Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.7.0 -----> Installing pip Traceback (most recent call last): File "/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/vendor/pipenv-to-pip", line 24, in <module> main() File "/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/vendor/pipenv-to-pip", line 12, in main lockfile = json.load(f) File "/app/.heroku/python/lib/python3.7/json/__init__.py", line 296, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "/app/.heroku/python/lib/python3.7/json/__init__.py", line 338, in loads s, 0) json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0) ! Push rejected, failed to compile Python app. ! Push failed What can cause it? how can I fix it? can it result from a bad python version (recommended is 3.6.6 but i have 3.7)? or if someone had a similar problem, where he was looking for a solution? Any help will be appreciated. -
Django - postgreSQL - new connection is made for every page
settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'tutorial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', 'CONN_MAX_AGE': 10, } } As I navigate to links in my website, a new connection is created. For example, upon entering <domain.com>, a new connection is created: 2018-08-10 06:22:15.301 CDT [3380] LOG: connection received: host=::1 port=56368 2018-08-10 06:22:15.306 CDT [3380] LOG: connection authorized: user=postgres database=tutorial And upon navigating to one of the links, like <domain.com/some_page/>, another new connection is created. 2018-08-10 06:20:10.095 CDT [22932] LOG: connection received: host=::1 port=56181 2018-08-10 06:20:10.098 CDT [22932] LOG: connection authorized: user=postgres database=tutorial When I have visited 10 different link within my domain and visit my 11th link, it finally reaches the maximum available connections, and disconnects the very first connection I established by visiting <domain.com>: 2018-08-10 06:30:17.715 CDT [6884] LOG: disconnection: session time: 0:00:09.011 user=postgres database=tutorial host=::1 port=56368 Please note that port=56368 was the exact same port I opened upon visiting my <domain.com> the first time. Apparently a new connection is established every time I visit a new link, and if the current number of connections exceeds the max connections, the very first connection is disconnected in order to accept a new connection. But this is … -
official support of MongoDB in django
I want to use MongoDB database in Django. Officially there is no Django-MongoDB drivers are available. Some third-party sources are available, but they're outdated. I found some projects on Github but they are updated 2-3 year ago. -
Python tempalteDoesnotExist
, line 53, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) TemplateDoesNotExist: MNR/post_list.html [10/Aug/2018 11:15:22] "GET /blog/blog-list/ HTTP/1.1" 500 78896