Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Page not found (404) Request Method: No Sales matches the given query
please help review below code for editing entry. It keeps returning below error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/geo_gas/edit_sale/ Raised by: geo_gas.views.edit_sale No Sales matches the given query. class Sales(models.Model): gas_qty = models.CharField(max_length=20) amount = models.CharField(max_length=20) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.gas_qty class Meta: verbose_name_plural = 'Sales' View.py def edit_sale(request): """Edit an existing sales record.""" entry = get_object_or_404(Sales, pk=1) if request.method != 'POST': form = SalesForm(instance=entry) else: form = SalesForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('geo_gas:sales')) context = {'entry': entry, 'form': form} return render(request, 'ht/edit_sale.html', context) Urls.py ....... # Page for editing a sale entry path('edit_sale/', views.edit_sale, name='edit_sale'), ....... ht/templates/ht/edit_sale.html Edit entry: <form action="{% url 'geo_gas:edit_entry' %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name="submit">save changes</button> </form> -
Updating existing Django app version
I was working through the tutorial for Django 2.0 when I had an earlier version of Django installed. I have now updated Django to 2.0.1 and Python to 3.6.4. I am part way through building my app and I am getting an error when I try to include paths like this: from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ # url(r'^$', views.index, name='index'), # ex: /polls/ path('', views.index, name='index'), # ex: /films/5/ path('<int:film_id>/', views.detail, name='detail'), # ex: /films/5/results/ path('<int:film_id>/results/', views.results, name='results'), # ex: /films/5/vote/ path('<int:film_id>/vote/', views.vote, name='vote'), ] The error I get is: ImportError: cannot import name path Paths are not supported in pre Django 2.0, but this error still occurs after updating. Is there a setting within my app files that I need to change? I don't want to have to start from scratch if I can avoid it. -
Django rest framework DateField format
I have drf model which is containe DateField. That field default format is "YYYY-MM-DD" just i want to convert "DD-MM-YYYY" how can is possible. models.py class Reminder(BaseModel): content = models.TextField() schedule_date = models.DateField() schedule_time = models.TimeField() is_release = models.BooleanField(default=True) serializer.py class ReminderSerializer(HyperlinkedModelSerializer): schedule_date = serializers.DateField(format="%d-%m-%Y") class Meta: model = Reminder fields = ('id','content','created_at','schedule_date','schedule_time','user_id','is_release','is_deleted',) in serializer.py i just give the format but that format convering only in List page. as you can see listing is okey but the POST action field is not converted. API please look at image -
Error updating Django
I get the following error when I type "pip install -U Django": Collecting Django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/tn/d7vg_zcd5pq0cq3sltw0j7pc0000gn/T/pip-build-xIsFov/Django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/tn/d7vg_zcd5pq0cq3sltw0j7pc0000gn/T/pip-build-xIsFov/Django/ I read that this relates to the version of python. But if I type python3 in terminal I get : Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin -
how to build datatables in react components?
i am using react, and while checking for datatables(jquery plugin) to work with react, i found gigatables-react. In documentation, it seems nice and screenshots are very cool. but while implementing gigatables, i followed the steps, -> npm i gigatables-react -> import React, { Component } from 'react'; import SideBar from './../account_upload/sidebar'; import { Reactables, Header } from 'gigatables-react'; var settings = { struct: {// all in search: ['top'], rowsSelector: ['asc', 'top', 'bottom'], pagination: ['bottom'] }, requestType: 'POST', ajax: '/domain_ip/', columns: [ {data: "id"}, {data: "desc"}, {data: "title"}, {data: "date"}, {data: "types"}, {data: "info"} ] }; class Accounts extends Component { render() { return ( <div style={{"display": "inline-flex"}}> <div className="custom_sidebar"> <SideBar /> </div> <div className="content"> <Reactables settings={settings}> <Header data="id">ID</Header> <Header data="desc">Description</Header> <Header data="title">Name</Header> <Header data="date">Date</Header> <Header data="types">Date</Header> <Header data="info">Info</Header> </Reactables>, </div> </div> ); } } export default Accounts; wts wrong in this?? am getting error in console as, accountsSet-ccb24f5e97f47f7e0ca9.js:sourcemap:29807 Uncaught TypeError: Cannot read property 'csv' of undefined at t.value (accountsSet-ccb24f5e97f47f7e0ca9.js:sourcemap:29807) at t.value (accountsSet-ccb24f5e97f47f7e0ca9.js:sourcemap:29807) how do i resolve this?? -
Adding paths in Django to create more views
I am following the tutorial on the Django website. I try and replicate this: My code is as follows: views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") def detail(request, film_id): return HttpResponse("You're looking at film %s." % film_id) def results(request, film_id): response = "You're looking at the results of film %s." return HttpResponse(response % question_id) def vote(request, film_id): return HttpResponse("You're commenting on film %s." % film_id) films/urls.py from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ # url(r'^$', views.index, name='index'), # ex: /polls/ path('', views.index, name='index'), # ex: /films/5/ path('<int:film_id>/', views.detail, name='detail'), # ex: /films/5/results/ path('<int:film_id>/results/', views.results, name='results'), # ex: /films/5/vote/ path('<int:film_id>/vote/', views.vote, name='vote'), ] With this I am getting ERR_CONNECTION_REFUSED. If I comment out all the paths leaving only the index url, and also comment out from django.urls import path a page displays, but that is where I was at before trying to add more views. -
Django admin panel missing management form
The following exception occurs on admin panel while trying to change an object type (say a product), but it only occurs on SOME of them. I can't seem to debug this, where should I be inspecting? I'm not instantiating custom forms and formsets so I don't know what I could be doing wrong. Do you have any ideas where I should be inspecting? How can I know if the management form is rendered at all? I've saved the HTML source of the product change form. Traceback: File "/website/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/website/venv/lib/python3.4/site-packages/newrelic-2.50.0.39/newrelic/hooks/framework_django.py" in wrapper 499. return wrapped(*args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper 544. return self.admin_site.admin_view(view)(*args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner 211. return view(request, *args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in change_view 1512. return self.changeform_view(request, object_id, form_url, extra_context) File "/website/venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/website/venv/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python3.4/contextlib.py" in inner 30. return func(*args, **kwds) File "/website/venv/lib/python3.4/site-packages/django/contrib/admin/options.py" in changeform_view 1448. if all_valid(formsets) and form_validated: File "/website/venv/lib/python3.4/site-packages/django/forms/formsets.py" in all_valid 456. … -
Get QuerySet in QuerySet Python
I have a basic question about Python hope your guys help me. Get QuerySet in QuerySet Python I have a queryset: qrs1 = [1, 3, 5, 6, 9, 11, 16, 22] I want to get first, second and third object in this queryset and put it on a queryset like this result. result = [1, 3, 5] -
How to use pre_save methods in rest_framework serializers?
I know this is a noob question about DRF. I use latest version of Django and DRF. In my Django , I create slugs in a method using pre_save signals. def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Article.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug = new_slug) return slug @receiver(pre_save, sender = Article) def pre_save_article_receiver(sender, instance, raw, using, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_article_receiver, sender=Article) Then I can manage to write my views and serializers using DRF from rest_framework import serializers from yogavidya.apps.articles.models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = [ "title", "user", "content", "excerpt", ] --views.py-- app_name = 'articles' class ArticleListView(generics.ListCreateAPIView): lookup_field = 'pk' serializer_class = ArticleSerializer queryset = Article.objects.all() def list(self, request): # Note the use of `get_queryset()` instead of `self.queryset` queryset = self.get_queryset() serializer = ArticleSerializer(queryset, many=True) print(serializer.data) return Response(serializer.data) def get_queryset(self): return Article.objects.all() def get_object(self): pk = self.kwargs.get("pk") return Article.objects.get(pk=pk) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) class ArticleViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Article.objects.all().order_by('-title') serializer_class = ArticleSerializer When I post my form I … -
Read specific part of json string with python
I am currently working on a programme within the django environment which operates off a json api provided by a third party. There is an object within that API which I want however the string of information it provides is too much for me. The data I want is the created_at tag from the twitter api using tweepy. This created_at contains data in the following format: "created_at": "Mon Aug 27 17:21:03 +0000 2012" This is all fine however this will return the date AND time whereas I simply want the the time part of the above example i.e. 17:21:03. Is there any way I can just take this part of the created_at response string and store it in a separate variable? -
Reveal a <div> containing a database object only when another <div> containing a database object from the same row is clicked - Django
I am developing a website for a mobile barber service. There's a page on the website which displays all the barbers on the service. Each barber has a hidden 'div' containing their booking calendar, this appears when they click on a barber (using JavaScript). The booking calendar is a 3rd party booking system, and I input the barber's specific calendar url into the model form and then display it in the template like so: <iframe class="booking-system" src="{{BarberProfile.booking_link}}" frameBorder="0"></iframe><script src="https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js" type="text/javascript"></script> My problem is, when a barber is clicked, it displays all the 'divs' containing all of the barbers booking calendars. How can I only show the booking calendar of the barber that is clicked, and hide all of the other barber's booking calendars that are not clicked? An example of the page, and the 'div' containing the booking calendar: I am very new to web development but have a pretty solid understanding of HTML & CSS, but a weak understanding of JavaScript so please be very clear in your suggestions. I am unsure if the solution to this will lie in Django views, JavaScript, or CSS. My current code (I have edited out some which is irrelevant to this question): … -
django freetds MSSQL encoding error
I have a Django app running on Ubuntu that connects to a MSSQL server to extract table info and show it on a webpage. I'm using FreeTDS for the connection. When a line of information contains an 'ë' the whole line gets removed. So I tried to fix it by adding "client charset = UTF-8" to /etc/freetds/freetds.conf. But after that "fix" the app stops running and I get this error: [42000] [FreeTDS][SQL Server]Unclosed quotation mark after the character string \'ondersteuningsco\'. (105) (SQLExecDirectW)') The next character after "ondersteuningsco" is an 'ë' so I think this error is not a coincidence. Does anyone know how to fix this problem? The characterset of the MSSQL server is SQL_Latin1_General_CP1_CI_AS but I cannot change that. -
Use different firebase service account in development and production
We are using firebase python admin sdk in our django app. (This is used for the phone auth backend verification). The sdk is authenticated using serviceAccountKey.json file. What is the best practice to use this in production and development environments? It will be good to have a separation So that This file can be safely git ignored. -
Properly configuring user registration using 2 forms
I am trying to submit 2 forms at a time to create my student user in Django. I have been struggling for a while now, but I think I'm finally closing to an end on how to manage 2 forms at a time for my users to register. But when I fill in the data and then click register, I get error: "This field is required." under my student ID field. What am I doing wrong ? Thanks. class UserForm(forms.ModelForm): password = forms.CharField( label='Password', max_length=32, required=True, widget=forms.PasswordInput, ) password2 = forms.CharField( label='Confirm', max_length=32, required=True, widget=forms.PasswordInput, help_text="Make sure they match!", ) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password', 'password2') class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('phone', 'student_ID', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) photo = models.ImageField(upload_to='students_images') phone = models.CharField(max_length=15, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_student(sender, instance, created, **kwargs): if created: Student.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_student(sender, instance, **kwargs): instance.profile.save() @csrf_protect def student_register(request): if request.method == 'POST': form1 = UserForm(request.POST, prefix="user") form2 = StudentForm(request.POST, prefix="profile") if form1.is_valid() and form2.is_valid(): # create initial entry for … -
Get field attributes on form submit and used them to override save method
I have the following form: class DocumentModelForm(forms.ModelForm): document = forms.FileField(required=False) I have the following input(from a widget): <input name="document" data-type='a' type="file"> I need to: on form submit get the data-type value override the def save and add/update data-type field with the value from data-type attribute. The data-type exist on the Model but not in the form -
How can I apply for loop to display number of same images in django template?
In code below, i want to display a number of same images based on the number of votes. The code must be placed in between br and /div. {% extends 'polls/base.html' %} {% block main_content %} <head> <style> #Results h1{ font-family: Verdana; background-image: url("../../static/hviolet.jpg") ; color: white; border-radius: 4px; text-align: left; border-style: none none solid solid; border-color: darkblue; border-width: 1px; padding: 15px 15px 15px 15px; text-shadow: 1px 1px black; margin-top: 5px; } ul{ padding-left: 0px; } #votes{ list-style: none; font-family: Verdana; color: white; font-size: 20px; background-image: url("../../static/nviolet.jpg"); border-radius: 4px; text-shadow: 1px 1px black; padding-left: 3px; margin-bottom: 4px; font-size: 15px; font-style: normal; padding: 5px 5px 5px 5px; border-style: none none solid solid; border-color: darkblue; border-width: 1px; } #info{ background-image: url("../../static/hviolet.jpg"); border-radius: 4px; font-family: Verdana; font-size: 18px; color: white; padding: 7px 14px 7px 14px; text-shadow: 1px 1px black; margin-top: -5px; } </style> </head> <div id="Results"> <h1>{{question.question_text}}</h1> <ul> {% for choice in question.choice_set.all %} <li id="votes"><img style="border-radius: 2px; border-width: 2px; border-style: none solid solid none; border-color: darkblue;" src='{{choice.image2.url}}'/><div style=" float: right; width: 88%;"><b>{{choice.choice_text}}</b> | {{choice.votes}} vote{{choice.votes|pluralize}} </div></li> {% endfor %} </ul> <p id="info">Your Vote Has Been Stored!!</p> <br> </div> {% endblock %} My current code outcome gives a list of choices with votes … -
How to return a python list to Django
What I want to do is get the user to enter some information via HTML and it passes that as an argument to a python script, and then that python script will return a list which i can then pick apart with Jinja and display with html. I'm using Django and have seen many pages offering solutions but not found one that has worked. Below is a simple version of what my code does - which is that it returns a list: def return_list(arg): list_ = [arg, 1, 2, 3] return list_ return_list("argument") I can figure out how to get input from user another day but my main problem is passing it information and getting it to display something from within Django -
Tornado with Django authentication
Here's my idea: have a Django Website that receives / send JSON information so that I can create a JavaScript client for a Webbrowser, or a Unity / UE client I want a new functionality only for Unity / UE client: realtime chat. I'd like to use a tornado server on a specific port, let's say 8666. Here's what I've done so far: authenticate on the Django web site make everything work on the Django web site Now I'd like the client to connect to the port 8666 (pure TCP) and to send its cookie so that I can see on the tornado web server whether the client is authenticated. I didn't find any documentation about that. Do you know how to handle this? Any example, or if I'm not on the right track what should I do then? -
How can I set/replicate in a (model)form, a Model Choice Field that should be hidden?
How can I set/replicate in a (model)form, a Model Choice Field: document_type = models.CharField(max_length=100, choices=DOC_CHOICES, default=DOC_TYPE_DATASHEET)` I don't need the field in the form, because I will be set from the code base on rules. I tried, blocked on queryset: document_type = forms.ModelChoiceField(widget=forms.MultipleHiddenInput, ) or should I just don't add it in the form, and override form def save ? -
How to user Django REST serializer do validation on reserved key?
It might a simple question with eye blink workaround. But I can not be able to get it done. I am now creating the webhook endpoint. And stuck at serializer class My class can not use from as a class property @pytest.fixture def like_object(): """LIKE object response from Facebook""" return { "object": "page", "entry": [{ "changes": [{ "field": "feed", "value": { "item": "reaction", "verb": "add", "reaction_type": "like", "created_time": 1516183830, "post_id": "1331351323541869_1844740022202994", "from": { "name": "Elcoie Sieve", "id": "1639217166122728" }, "parent_id": "1331351323541869_1844740022202994" } }], "time": 1516183830, "id": "1331351323541869" }] } serializers.py class FacebookReactionSerializer(serializers.Serializer): """ value serializer the inner most of the payload """ item = serializers.CharField() verb = serializers.CharField() reaction_type = serializers.CharField() created_time = serializers.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(4086831600)] ) # Limit the maximum epoch to 2099 July 4th 7:00AM post_id = serializers.CharField(max_length=40) from = FromSerializer() parent_id = serializers.CharField() def validate(self, attrs): """ `from` is a python reserved word the add _ to distinguish it from them :param attrs: :return: """ from_ = attrs.get('from') pass def create(self, validated_data): pass def update(self, instance, validated_data): pass Question: What is your workaround when from(reserved word) is a key and that key is a python class property? -
Django: LDAP E-Mail Authentication
I am trying to authenticate against the e-mail adress of a ldap-user by creating a LDAPbackend class. This is my settings.py: AUTH_LDAP_SERVER_URI = "ldap://192.168.1.18" AUTH_LDAP_BIND_DN = "Test" AUTH_LDAP_BIND_PASSWORD = "Password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=ch", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=ipa-users,cn=users,DC=domain,DC=com", "is_staff": "CN=ipa-users,cn=users,DC=domain,DC=com", "is_superuser": "CN=ipa-users,cn=users,DC=domain,DC=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTH_LDAP_E_USER_SEARCH = LDAPSearch("dc=sbvg,dc=ch", ldap.SCOPE_ONELEVEL, "(mail=%(user)s)") AUTH_LDAP_E_USER_ATTR_MAP = AUTH_LDAP_USER_ATTR_MAP AUTH_LDAP_E_ALWAYS_UPDATE_USER = AUTH_LDAP_ALWAYS_UPDATE_USER AUTHENTICATION_BACKENDS = ( #'django_auth_ldap.backend.LDAPBackend', #'django.contrib.auth.backends.ModelBackend', 'accounts.backends.LDAPEmailBackend', ) And this is the backend (backends.py): class LDAPEmailBackend(LDAPBackend): settings_prefix = "AUTH_LDAP_E_" def get_or_create_user(self, email, ldap_user): """ Use the Posixuser uid field as username instead of form value (email). This must return a (User, created) 2-tuple for the given LDAP user. username is the Django-friendly username of the user. ldap_user.dn is the user's DN and ldap_user.attrs contains all of their LDAP attributes. """ model = self.get_user_model() username_field = getattr(model, 'USERNAME_FIELD', 'username') kwargs = { username_field + '__iexact': ldap_user.attrs['uid'][0], 'defaults': { username_field: ldap_user.attrs['uid'][0].lower(), 'email': email } } return model.objects.get_or_create(**kwargs) If I try to lofin with the right credentials this is the … -
Adding custom pages to django admin
I am developing a website with its back end powered by Django. I am very new to Django. What I need is to add custom pages (HTML,CSS, js) to Django admin panel so admin can make changes to models which will then be reflected onto the website say changing images or text on the website. I tried adding pages to Django admin urls but since the pages contains references to CSS and JS files so it does not work properly. How can i solve this problem? -
Django modeltranslation - can't get original values
I'm trying to use django-modeltranslation in my project. For now, just for Tag model with one field - name. I've created and registered TranslationOptions, then makemigrations and migrate. Now I can't access the original name text. It seems to be replaced with '' (empty string) but it isn't: In [6]: Tag.objects.first() Out[6]: <Tag: > In [7]: Tag.objects.first().name Out[7]: u'' In [8]: Tag.objects.first().__dict__ Out[8]: {'_state': <django.db.models.base.ModelState at 0x7fc96ad41710>, 'id': 1, 'name': u'Sport', 'name_cs': None, 'name_de': None, 'name_en': None, 'name_es': None, 'name_fr': None, 'name_ru': None, 'name_sk': None} In [9]: Tag.objects.first().name Out[9]: u'' Do you know how to access the field/s? -
What is the best way to time django query in shell?
I have sometimes to optimize my django queries and want to compare the speed of different queries in django shell. Of course, I can use django-debug-toolbar or smth similar, but I prefer to do it in shell. For now, I use %timeit in django shell_plus. But maybe there is a better way? -
ImportError: No module named 'project.app'
Getting this error whenever I use python manage.py test. It fails to import all of my apps. Here's an example: ImportError: No module named 'project.profiles' My project tree is: /project /project /profiles ... /bin /lib /include Any idea what the problem is?