Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Validation Conflict
Something weird is happening. Lets say I have a field defined as: Project_name = models.CharField(max_length=250, unique=True) So Project_name must have a unique value otherwise it'll throw an error. Then I want to add other Validation checking. So in my forms.py def clean(self): data = self.cleaned_data if data['team_member2'] == data['team_member3']: raise ValidationError("Can't have duplicate team members") However, once I add this function in, the unique operator stops working for some reason. Any ideas? -
how to pass parameters to forms.py
I have a choice field on a form I am trying to display all the cars in a drop down list that are the same color, the color chosen is defined by a user input field class car(forms.Form,email): cars = forms.ModelChoiceField( empty_label = "Current Cars", queryset = Cars.objects.order_by('name').filter(color=color), widget = Select(attrs={'class': 'span6 small-margin-top small-margin-bottom'}), required=True ) -
Adding placeholder to django form field and removing default label
Please i'm new to django. adding a placeholder to my username and password fields but none is working. This is the form class LoginForm(forms.Form): username = forms.CharField(label='', help_text='Enter your username', widget=forms.TextInput(attrs={'placeholder':'Username here'})) password = forms.CharField(label='', widget=forms.PasswordInput(attrs={'placeholder':'Password here'})) -
how get query with >= =< more filters
Have code shops = Shop.objects shops.filter(id__in=list(set(shop_ids))) if min: shops.filter(delivery_price >= min) if max: shops.filter(delivery_price =< max) shops.all() but delivery_price is not defined.... how i can fix it? and get queryset with more than 1 filter -
Why would you not want to create a backwards relation on a foreign key?
I recently came across this paragraph in the Django docs on the related_name attribute of the ForeignKey field. If youβd prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. For example, this will ensure that the User model wonβt have a backwards relation to this model: > user = models.ForeignKey( > User, > on_delete=models.CASCADE, > related_name='+', ) Under what circumstances would you want to do this? -
WYSIWYG form for users in Django CMS
Recently I started using Django CMS, it turns out to be a great tool for web developer. But one thing I couldn't have achieved so far is creating a form for users so they could submit some content created with WYSIWYG editor. I thought maybe there's some easy way to add editor available in admin panel (the one you use with creating / modifying Text plugins), doesn't seem like that unfortunately. Long story short - I'd like to enbable users to use the same WYISWYG editor available from admin panel, without giving them permission to access admin panel. Is it possible? Or do I have to use some additional extension so I could embed similiar editor on my Page(s)? -
How to test against specific database
The company I work at has a test server which houses all test data. I'm attempting to add some much needed unit tests that reference our Django database on the test server. The problem I'm having is the test database is being created instead of pointing to the database I've provided. I had tried setting the database if test in the system arguments like this: if 'test' in sys.argv: DATABASES = { 'default': { # VM Testing 'ENGINE': 'sql_server.pyodbc', 'NAME': 'x', 'USER': 'x', 'PASSWORD': "x", 'HOST': 'x.x.x.x', # 'PORT': '', 'OPTIONS': { 'driver': 'FreeTDS', 'dsn': 'mssql_staging_1', 'extra_params': 'TDS_VERSION=8.0', 'use_legacy_datetime': False }, }, } DEBUG = False TEMPLATE_DEBUG = False And while it makes it into the this if statement, the test database is still created when running python manage.py test. Any advice? And FWIW all my tests to this point are using DRF and its APITestCase class. Thanks! -
How to round a Geodjango Distance
In Django 1.9 / Python 2.7, I have the following view: qs = ThePlace.objects.filter(lnglat__distance_lte=(lnglat, D(km=30))).distance(lnglat).order_by('distance') In my template, I display the distances when I loop over the objects: {% for qsplace in qs %} {{ qsplace.distance }} {% endfor %} which displays "25.717617095 m" for example. I would like to display rounded figures (26 m). If more than 1 km, I would like to display 3 km for example I have developed a first templatetag to round the figures: from django import template register = template.Library() @register.filter def dividebyth(value): print(type(value)) value = round(value, 2) return value And put in my template: {{ qsplace.distance|dividebyth }} which results in the following error: TypeError: a float is required It seems I cannot round a Distance object. Any way to manage that ? Thank you! -
Django: extend User model with profile onetoonefield errors
I have this model from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from my_app.models import Teams class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) team = models.ForeignKey(Teams, on_delete=models.CASCADE) class Meta: app_label = 'my_app' def __str__(self): return self.name @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I then go into the shell from django.contrib.auth.models import User when I type user = User.objects.create_user(username='test', email='dummyemail@dum.com', password='test') I unsurprisingly get IntegrityError: NOT NULL constraint failed: my_app_profile.team_id but when I type user = User.objects.create_user(username='test', email='dummyemail@dum.com', password='test', team='developer') I get TypeError: 'team' is an invalid keyword argument for this function If I type user = User.objects.create_user(username='test', email='dummyemail@dum.com', password='test', profile.team='developer') I get SyntaxError: keyword can't be an expression Any help, hints or guidance would be greatly appreciated -
Django OAuth Toolkit and POSTMAN
I made a django OAuth server using Django OAuth Toolkit. I've setup the code right and when I use CURL in the following way: curl -X POST -d "grant_type=password&username=geethpw&password=abcabcabc" -u"wHsGgpsHZyw8ghnWbEPZC8f4AZLgJIPmoo50oNWp:ZQcXeQWnae0gmX0SMi6Xn6puBnhiphR2M80UC6ugmffbrUd66awhbguYgxtQ1ufahJZehj4RlGjYu06fHkVgO15TURttSozj27nshl0AhFfCVzUKqTDubBimTSsK4yDS" http://localhost:8000/o/token/ I get a response: {"access_token": "glzwHLQNvUNQSOU5kFAoopgJxiNHcW", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "5k6jvCd2UxaRUGHKONC2SqDukitG5Y", "scope": "read write groups"}Geeths-MacBook-Pro:~ geethwijewickrama$ Geeths-MacBook-Pro:~ geethwijewickrama$ which is expected. But When I try postman to do the samething, I always get: { "error": "unsupported_grant_type" } My headers are: Content-Type:application/x-www-form-urlencoded If I remove this header I get: { "error": "invalid_client" } How can I test my APIs in postman? -
What is right syntax for args in Django 1.10
I started to study Django 1.10 but uses example made on 1.6. That's why I have some troubles with syntax in new version. This's my function: def article(request, article_id=1): comment_form = CommentForm @csrf_protect args = {} args['article'] = Article.objects.get(id=article_id) args['comments'] = Comments.objects.filter(comments_artile_id=article_id) args['form'] = comment_form return render (request, 'articles.html', args) and my Traceback: File "/home/goofy/djangoenv/bin/firstapp/article/views.py", line 30 args = {} ^ SyntaxError: invalid syntax If you show me what is right syntax or he or where i can find answer, because I can found any explanations in Django Docs -
Function SetAppDir already exists, add ! to replace it - django vim
I follow the instruction on django site to add the following to my vimrc file but when I try to save the file I get an error: Function SetAppDir already exists, add ! to replace it Tried to add ! to SetAppDir()!, or call! SetAppDir but still no luck. Here is the code from django site: let g:last_relative_dir = '' nnoremap \1 :call RelatedFile ("models.py")<cr> nnoremap \2 :call RelatedFile ("views.py")<cr> nnoremap \3 :call RelatedFile ("urls.py")<cr> nnoremap \4 :call RelatedFile ("admin.py")<cr> nnoremap \5 :call RelatedFile ("tests.py")<cr> nnoremap \6 :call RelatedFile ( "templates/" )<cr> nnoremap \7 :call RelatedFile ( "templatetags/" )<cr> nnoremap \8 :call RelatedFile ( "management/" )<cr> nnoremap \0 :e settings.py<cr> nnoremap \9 :e urls.py<cr> fun! RelatedFile(file) #This is to check that the directory looks djangoish if filereadable(expand("%:h"). '/models.py') || isdirectory(expand("%:h") . "/templatetags/") exec "edit %:h/" . a:file let g:last_relative_dir = expand("%:h") . '/' return '' endif if g:last_relative_dir != '' exec "edit " . g:last_relative_dir . a:file return '' endif echo "Cant determine where relative file is : " . a:file return '' endfun fun SetAppDir() if filereadable(expand("%:h"). '/models.py') || isdirectory(expand("%:h") . "/templatetags/") let g:last_relative_dir = expand("%:h") . '/' return '' endif endfun autocmd BufEnter *.py call SetAppDir() -
How can I retrieve data from a page?
I am using FeinCMS. I want to do some processing on a page object before it goes to the template for rendering. In my view I have the code : this_page = Page.objects.best_match_for_path(request.path) which correctly gets the page for the path I am on. I really want to get some data out of this page. Is there a function I can call to get the data ? such as : this_page = Page.objects.best_match_for_path(request.path) data = this_page.get_content_for_region('main') I can't find anything in the readthedocs pages to answer this. I am not interested in templates or rendering the region. -
'utf-8' codec can't decode byte 0x96 in position 227: invalid start byte
I am starting with Django. I've got an error but cannot sort it out. Does anyone know why I am getting this? I am doing an {% extends "base.html" %} on my login page. error -
Deploy to docker with nginx, django, daphne
I want to deploy my service to docker. and my service is developed using python+django and django-channels ββ myproject βββ myproject β βββ settings.py β βββ urls.py β βββ asgi.py β βββ ... βββ collected_static β βββ js β βββ css β βββ ... βββ nginx β βββ Dockerfile β βββ service.conf βββ requirements.txt βββ manage.py βββ Dockerfile βββ docker-compose.yml myproject/Dockerfile : FROM python ENV PYTHONUNBURRERED 1 RUN mkdir -p /opt/myproject WORKDIR /opt/myproject ADD . /opt/myproject RUN pip install -r requirements.txt RUN python manage.py migrate myproject/docker-compose.yml: version: '2' services: nginx: build: ./nginx networks: - front - back ports: - "80:80" depends_on: - daphne redis: image: redis networks: - "back" ports: - "6379:6379" worker: build: . working_dir: /opt/myproject command: bash -c "python manage.py runworker" environment: - REDIS_HOST=redis networks: - front - back depends_on: - redis links: - redis daphne: build: . working_dir: /opt/myproject command: bash -c "daphne -b 0.0.0.0 -p 8000 myproject.asgi:channel_layer" ports: - "8000:8000" environment: - REDIS_HOST=redis networks: - front - back depends_on: - redis links: - redis networks: front: back: myproject/nginx/Dockerfile FROM nginx COPY service.conf /etc/nginx/sites-enabled/ myproject/nginx/service.conf server { listen 80; server_name example.com #i just want to hide domain name.. charset utf-8; client_max_body_size 20M; location /static/ { alias /opt/myproject/collected_static/; β¦ -
AttributeError: 'module' object has no attribute 'IntegerRangeField'
I got an error, AttributeError: 'module' object has no attribute 'IntegerRangeField' . I wrote in models.py class ImageAndUser(models.Model): rbc = models.IntegerRangeField(min_value=1, max_value=100) I think maybe something to be needed is not imported in models.py, but it is not true. How can I fix this? -
Django REST - saving and serializers in case of foreign fields
I think this question will be duplicated, but I am lost googling and reading the doc on Django serializers. And still I failed to implement the simplest goal of saving serialized objects that correspond to models that are related by one-to-many relationship. Here's the mock code: The models: class ParentModel(models.Model) # Some fields class ChildModel(models.Model) parent = models.ForeignKey(ParentModel, models.DO_NOTHING) Serializers: class ParentSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ('__all__') Basically, I can't figure out two things: How do I define the child-serializer to reflect its relationship with parent How do I implement the respective post-request: The class-view: class ChildList(APIView): def post(self, request): parent_serializer = ParentSerializer(data = request.data) if parent_serializer.is_valid(): # how do I tell the child serializer to use parent serializer and save? -
Sending extracted database field to the django template
I have an view as follows : def traxio_advice(request): calculation_list = Calculations.objects.select_related('customer').filter(user=request.user) p = Paginator(calculation_list, 20) page = request.GET.get('page') try: calculations = p.page(page) except PageNotAnInteger: calculations = p.page(1) except EmptyPage: calculations = p.page(p.num_pages) context = {'calculations': calculations} return render(request, 'master/archive.html', context) Thus I get all calculations for this user. And the calculation model has an price field, but the price is exclusive VAT. It needs to be stored exclusive VAT in the database but I need to show it inclusive VAT. Thus, is there any way to calculate the price for every calculation? archive.html template is as follows : {% for calculation in calculations %} <tr data-archive-row class="archive-row"> <td> <span>{{ calculation.make }}</span><br> <small >{{ calculation.model }}</small> </td> <td> <span class="text-success text-semibold"> {{ calculation.purchase_price|floatformat:0|intcomma }} </span> <small class="text-muted">(incl. VAT)</small> </td> </tr> {% endfor %} Thus, in the template it's shown the price exclusive VAT. I've created a function to convert it to the inclusive VAT : def price_incl_vat(price_excl_vat): return (price_excl_vat * decimal.Decimal(settings.VAT_VALUE)).normalize() Is there any way to calculate the price (call the function) in the view and then send it to the template or can it be done in the template? Or is there any better way to do this? Thanks β¦ -
Django 1.10: base_site.html override not working
I am creating a site in Django with a custom view, and want to link to that view on the admin page. But even though I've followed the directions to override base_site.html in the Django tutorial, nothing changes. No matter if input the simplest change: {% extends "admin/base.html" %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">Test</a></h1> {% endblock %} {% block nav-global %}{% endblock %} Or even something very drastic, where I don't extend the base.html at all: <h1>Test</h1> My directories are exactly as they should be, with the new base_site.html inside them: βββ myproject β βββ templates β β βββ admin β β βββ base_site.html This is my current settings.py:: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = <mysecretkey> # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'easy_thumbnails', 'filer', 'mptt', β¦ -
How do I create a multiplayer LAN game like Poker in Python-Django?
I have searched a lot of places on the internet to actually understand how to you start with. I basically want to create a web app where a user can sign in with his credentials. Once he signs in he should be able to see all the other online players on that server and he can start playing with him on a particular table. All of this can happen over a Local Area Network. I don't plan to do this over the internet as of now. This can be very much similar to Zynga Poker online but I want to do all of that with minimal functionalities. After searching on the internet all that I could understand is that I will require a server which will take care of all the algorithms that happen behind the scene according to the input received from the client at live time. I fail to understand which programming languages I should use for everything that I do. And how should I start? I was preferring to do all of this in python/Django/HTML/CSS/JavaScript because as far as I know Django is a great framework and has all functionalities of hosting a server and managing a β¦ -
Update automatically a specific field in Django model when saving other many-to-many related model
How can I update a field of a model automatically when saving an instance of a related model? I need to solve this scenario: class First(models.Model): name = models.CharField(max_length=100) assigned = models.BooleanField(default=False) class Second(models.Model): some_attribute = models.CharField(max_length=100) firsts = models.ManyToManyFields(First) So, every time I create a Second instance I want to automatically update the 'assigned' attribute for every related object of First model and change it to True. For simplification I am not saying that I have this models in different apps in the same project, I guess this is not so relevant, I just need the basics of it. I am trying to override the save method of Second but having trouble to iterate through the related objects. I am also trying to avoid Signals since this sounds like and advance topic and I'm a beginner programmer and I intuit there should be a simpler way to do this. 'First' objects are created in a CreateView for that model; inline formsets are not needed. Thanks for your help. -
I can't understand the django-markdownx's usage
It is kind of embarrassing. But I can't seems to understand django-markdownx's documentation on how to use the app. I've followed the Getting Started guide, installed the app and dependencies, added jquery and it works in the Admin backend. But the template doesn't render text = MarkdownxField() as correctly formatted markdown, but as plain text. I don't understand the part ...and then, include a form's required media in the template using {{ form.media }}: <form method="POST" action="">{% csrf_token %} {{ form }} </form> {{ form.media }} What I'm I missing? I know it is trivial. But I have no experience with forms. app/models.py from django.db import models from django.urls import reverse from markdownx.models import MarkdownxField class Article(models.Model): title = models.CharField(max_length=250, verbose_name='title') text = MarkdownxField() pub_date = models.DateField(verbose_name='udgivelsesdato') category = models.ForeignKey(Category, verbose_name='kategori', null=True) tag = models.ForeignKey(Tag, verbose_name='mærke', null=True) def get_absolute_url(self): return reverse('article-detail', kwargs={'pk': self.pk}) def __str__(self): return self.title class Meta(): verbose_name = 'artikel' verbose_name_plural = 'artikler' settings.py INSTALLED_APPS = [ *** 'markdownx', 'articles', ] # Markdown extensions MARKDOWNX_MARKDOWN_EXTENSIONS = [ 'markdown.extensions.sane_lists', 'markdown.extensions.nl2br', 'markdown.extensions.extra', ] urls.conf from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^', include('articles.urls')), url(r'^markdownx/', include('markdownx.urls')), url(r'^admin/', admin.site.urls), ] app/templates/app/article_list.html {% extends "base.html" %} {% block ⦠-
Django query for this sql query?
Well I have written a sql query for my need but I want to make this query in Django ORM. This is the query I want to convert it into Django ORM. select distinct * from users,billing where users.cabId_id=2 and billing.orgId_id=2 and users.contact like "98%" group by users.id In billing orgId is present. In Users orgId is not present. But both tables have cabId -
Why API response time increases after uwsgi restart in Production env?
I am running uwsgi-django with 4 worker in production environment. Recently I found that uwsgi was using more memory on ec2 instance(around 3200MB). So I did some research and find out that over the period of time memory occupied by workers will increase. So To release memory from workers, i did restart uwsgi forcefully. So It solved low free memory availble issue. But our automatic performance testing shows that now avg API response time is increased very much. Before restart, It was around 200ms for some APIs and now It is taking around 2000ms for same. What could be the reason for this much increase in API response? What could be the possible way to avoid this kind of situation? Note: over the period of time it is going down from 2000ms to 1000ms. May be it will come to normal state after some time. my configuration : [uwsgi] chdir = /path/to/project/ module = myapp.wsgi home = /path/to/project//venv master = true processes = 4 socket = /tmp/mysocket.sock chmod-socket = 666 vacuum = true -
How to pass data from HTML form to Database in Django
Can you help me with this issue? I want to pass data from HTML form to Database. This is my HTML form: <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% if user.is_authenticated %} <label for="username">Username: </label> <input id="username" type="text" name="username" value="{{ user.username }}" disabled><br> <label for="image">Image: </label> <input id="image" type="file" name="image"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Save Changes</button> </div> </div> {% endif %} </form> And this is my Views.py class CreateProfile(CreateView): template_name = 'layout/add_photo.html' model = Profile fields = ['image', 'user'] success_url = reverse_lazy('git_project:index') When I fill in the form (username is equal to logged in username, and chose an image) and when I click "Save Changes", the data has to be passed in Database in table Profile. Here is class Profile in models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.FileField() I know this is basic, but I don't know how to fix it up, so please, help! :)