Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create input mask for use in django forms
Good evening. I'm needing to figure out how to apply input masks in django's forms to a project, however, none of the previous attempts as successful. On the last test: from input_mask.widgets import InputMask However, perhaps for inexperience on my part, when using it not achieved in the desired result. What will be the mistake? Or in another case how do I use other alternatives to deal with this problem? Thank you very much in advance. -
Adding another database to Django and it says "Apps aren't loaded yet"
I'm new to Django. I'm trying to add another database to my project. I got this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Based on this, I added this code to my settings: import django django.setup() Now I have this error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. A few solutions pointed to django.contrib.sites and django.contrib.contenttypes. So I made sure they're in settings.py: INSTALLED_APPS = [ 'theme', 'myapp', 'debug_toolbar', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ] SITE_ID = 1 A couple of solutions said to remove the apps one by one to see what's wrong, so I removed theme, myapp, and debug_toolbar one by one, and then all at the same time. But I still got the error. I point to a database router in settings.py too: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'movies': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'movie_data.sql'), } } from . import router # I shifted this to the top of the file later. DATABASE_ROUTERS = [router.MoviesRouter] This solution makes sense so I tried putting DATABASE_ROUTERS = [router.MoviesRouter] all the way down at the end of settings.py, but it didn't help. urls.py in … -
How are streams and groups related in Django Channels
Regarding data binding in Django channels, I don't see how the concept of stream is necessary. Perhaps I am failing to see the big picture here and I hope that someone can point out my misunderstanding. Let me use an example to articulate my confusion. I have a Django-based message model. I wish to broadcast updates to my client whenever a message is created, updated, or destroyed. So I create two things, a data binding and a demultiplexer. class MessageDemultiplexer(WebsocketDemultiplexer): consumers = { 'message-stream': MessageBinding.consumer, } def connection-groups(self): return ['message-update'] I route my websocket traffic to this demultiplexer through channel routing. route_class(MessageDemultiplexer, path="^/messages/") From what I understand, whenever client is connected, he/she is being put into a group called message-update. Thus, if I were to broadcast anything to this group, my clients will all receive a message. Now, let's take a look at the binding class class MessageBinding(WebsocketBinding): model = Message stream = 'message-stream' fields = ['__all__'] def group_names(cls, instance): return ['message-update'] def has_permission(self, user, action, pk): return True The model and fields class attributes make sense to me. The group names also seem reasonable because we would want to know which group to broadcast the updates to. The permission … -
Server status dashboard using Django
I want to develop a server status dashboard which internally call ping command and show host status in red(in dashboard)if host is unreachable. As I am new to Django so just want to check if that possible via Django? -
Django send mail from smtp.office365.com
system support messages has to go from smtp.office365.com mail account. settings are: EMAIL_USE_TLS = True EMAIL_HOST = 'outlook-nameast4.office365.com' EMAIL_HOST_USER = '*********' EMAIL_HOST_PASSWORD = '*******' EMAIL_PORT = 587 hosts like: smtp.office365.com etc (this was the initial one), and other obtained with dig smtp.office365.com were tested so as the PORT 25: I don't receive any error notifications, but messages are not received. Whole system works perfect with gmail settings. Note: I tried both dynamic and static IPs -
Django method for loading Foreign Key objects
Suppose I have model Parent that has a ForeignKey to model Child: class Parent(models.Model): child = models.ForeignKey(Child, related_name='parents') class Child(models.Model): some fields here I know that if I have a Parent object and want to get the related Child object, I can simply use: childObj=parent.child If child has not already been loaded, the above will make another query to the DB to instantiate the Child in parent.child. But, suppose that every time I want to do something like this, I also want to do some additional processing. In other words, whatever method gets called when I invoke parent.child is a method I want to override so I can do additional processing. Does anyone know what this method is or how I can accomplish this? -
UnboundLocalError at /org_list/ local variable 'orgs' referenced before assignment
I encounter a problem when i wanted to do pagination. here is my view.py: class OrgView(View): def get(self,request): all_orgs=CourseOrg.objects.all() org_nums=all_orgs.count() all_citys=CityDict.objects.all() try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 p = Paginator(all_orgs, 5, request=request) orgs = p.page(page) return render(request,'org-list.html',{ "all_orgs":orgs, "all_citys":all_citys, "org_nums":org_nums, }) here is org-list.html: {% for course_org in all_orgs.object_list %} <dl class="des difdes"> <dt> <a href="org-detail-homepage.html"> <img width="200" height="120" class="scrollLoading" data-url="{{ MEDIA_URL }}{{ course_org.image }}"/> </a> </dt> <dd> <div class="clearfix"> <a href="org-detail-homepage.html"> <h1>{{ course_org.name }}</h1> <div class="pic fl"> <img src="{% static 'images/authentication.png' %}"/> <img src="{% static 'images/gold.png' %}"/> </div> </a> </div> <ul class="cont"> <li class="first"><p class="pic9">course number:<span>{{ course_org.click_nums}}</span></p><p class="c7">student number:<span>{{ course_org.fav_nums }}</span></p></li> <li class="c8" style="padding-left:18px;">{{ course_org.address }}</li> </ul> </dd> </dl> {% endfor %} when i run the org-list.html, the error is :UnboundLocalError at /org_list/ local variable 'orgs' referenced before assignment my python is 3.6.4 and django is 2.0.1 thanks for all your help -
Django Forms not Validating
Recently on a project, We have started to face an issue where sometimes the data is not validated ie. the clean methods are not run and the default values are passed when cleaned_data is invoked. We process a couple of tasks through a queue and send the task data to an API URL(using DRF). One of the fields in the task data should be changed based on some flags. Sometimes it seems the field is not changed and the task fails. But we re-queue the task if it has failed, and in subsequent runs, it runs properly. Task Data is not changed at all if the result is fail or pass. The only logical explanation looking at logs, to me is that the clean methods do not run when this happens but we still get form.is_valid() as True and form.cleaned_data['some_field'] as the same value that was being passed to the form. It seems the code in the Form is solid, because the same data passes in subsequent runs, which is confusing. Python is Python 2.7.6 (default, Nov 23 2017, 15:49:48) Django is 1.8.18 Is there some kind of known bug or anything, or anyone having expeirienced this kind of issue … -
Django sending chunked responses
My setup is Django->Gunicorn->Nginx Although I don't use HttpStreamingResponse, browser sees Transfer-encoding: chunked This causes problems with Cloudfront (it doesn't autocompress chunked responses) My gunicorn runs with default values, so default worker etc. and I couldn't find any option in nginx regarding this. Should I stop using chunked? If so how? I found this https://github.com/abrookins/streaming_django which mentions First, some conditions must be true: - The client must be speaking HTTP/1.1 or newer - The request method wasn't a HEAD - The response does not include a Content-Length header - The response status wasn't 204 or 304 If these conditions are true, then Gunicorn will add a Transfer-Encoding: chunked header to the response, signaling to the client that the response will stream in chunks. In fact, Gunicorn will respond with Transfer-Encoding: chunked even if you used an HttpResponse, if those conditions are true! but does it mean I should go to each view and add my content-length? Is my Django failing to do this? -
Queryset after login in created login panel doesn't display in html
I have a little problem. I've create a login and registration site seperated from Admin Login. When I login to panel as for example John i have a choise to add new record via forms. After that I want on dashboard display the records created exacly and only by user John. Problem is that, if I wrote in my dashboard.html the code <h1>Strony www</h1> {% for website in website_list %} {{website.website}} {% endfor %} {% endif %} the html responde me only label Strony www and thats all. It's not displaying me records created by the users from dashboard panel. I have in my view def website(request): website_list = Website.objects.filter(user=request.user).order_by('-User') context = {'website_list:', website_list} return render(request, 'konto/dashboard.html', context=context) If I create the records using Django Admin Panel, the records are visible in dashboard. Where is a problem in my project? I want to say in every html file I using the code on the beggining {% if request.user.is_authenticated %} -
django filters and checked box in results
I have my filters working correctly, but I want to also filter on a checkbox that's in my result set, is this possible with Django filters? My filter.py is the following: class UserFilter(django_filters.FilterSet): class Meta: model = Employee fields = ['employeeusername', 'employeefirstname', 'employeelastname', 'statusid', 'positiondesc'] My search form is the following: <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-4"> <label/> 3-4 User ID {% render_field filter.form.employeeusername class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> First Name {% render_field filter.form.employeefirstname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Last Name {% render_field filter.form.employeelastname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Status {% render_field filter.form.statusid class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Title {% render_field filter.form.positiondesc class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> In my result set I have the following: <table class="table table-bordered"> <thead> <tr> <th>User name</th> <th>First name</th> <th>Last name</th> <th>Title</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <td>{{ user.employeeusername }}</td> <td>{{ user.employeefirstname }}</td> <td>{{ user.employeelastname }}</td> <td>{{ user.positiondesc }}</td> <td>{{ user.statusid }}</td> <td><input type="checkbox" name="usercheck" />&nbsp;</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> … -
geo Django: get the neighbors of a house
i have a house model with these properties centerpoint = PointField(srid=0, null=True, blank=True) front_left = PointField(srid=0, null=True, blank=True) front_right = PointField(srid=0, null=True, blank=True) rear_left = PointField(srid=0, null=True, blank=True) rear_right = PointField(srid=0, null=True, blank=True) polygon = PolygonField(srid=0, null=True, blank=True) direction = FloatField(null=True, blank=True) # the direction this house faces, in degrees and i want to get the houses in front of a specific house... im having a hard time trying to use Distance and polygon__dwithin i need to get the ones that are touching and the ones that have relative direction of less than 160 degrees: for that i do: House.objects.filter(polygon__touches=house_instance.polygon, direction__lt=160) how can i modify this query to get the houses that are in front maximum one block and the ones that are one house away from my reference house? -
Stop coreapi displaying the admin api docs
I am currently documenting the API I have created for an app. I'm using the built in documentation system that comes with Django Rest Framework and coreapi (as described here). The problem I have is that when I visit the docs I see the admin API docs alongside my API docs. I've tried using the answer to this question: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } But the admin docs still show up. Is there a way to hide the admin docs? -
Saving Django model throws OperationalError: cannot start a transaction within a transaction
I'm seeing a weird error in a Django unittest where, on rare occasions, attempting to save a model instance will throw the exception: OperationalError: cannot start a transaction within a transaction What would cause this? The really odd thing is that this is happening in a loop like: for i in range(10): obj = MyModel(name='blah %i' % i) obj.save() and it'll get through several iterations before throwing the exception. Since it's non-deterministic, it's incredibly frustrating to diagnose, and I have no clear idea what's happening. Since I'm using Django's standard TransactionTestCase, I would have thought this error was impossible, since the TestCase wraps each test in an atomic() context manager to wrap all changes in a transaction. There should be nothing attempting to create another transaction. The only other thing I could think might effect this is that my model has a post_save signal handler, and that that might be someone breaking outside of the transaction, or otherwise interfering, but I'm not sure how to test it, since I can't reliably reproduce the error. -
django update record in database
I tried following code to update records in table but this creates new record instead of updating. Here is my code , thank you: view : class ReservationCancelView(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,mixins.UpdateModelMixin, viewsets.GenericViewSet): #Model = Reservation serializer_class = ReservationCSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): resid = self.request.POST.get('id') Res= Reservation.objects.get(id=resid) #Res.reservedplaces =F('reservedplaces ') - 1 #Res.save() return Res def post(self, request, token=None, format=None): resid = self.request.POST.get('id') travel_id = self.request.POST.get('travel_id') Res= Reservation.objects.get(id=resid) Res.reservedplaces =F('reservedplaces ') - 1 Res.travel_id = travel_id Res.save() serializer class ReservationCSerializer(serializers.ModelSerializer): user = Serializers.PrimaryKeyRelatedField(read_only=True,default=serializers.CurrentUserDefault()) class Meta: model = Reservation fields = ('all') urls.py router.register(r'cancelreservation', ReservationCancelView,'reservationcancel') -
How to use social-auth-app-django with Facebook JavaScript SDK
I wan't to use Facebook JavaScript SDK with Python Social Auth I'm using next authentication backend: AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', ) Firstly I find this example in django-social-auth(what was deprecated in favor of python-social-auth) and it seems like what I seek, but It doesn't work. FB.login() returns data like { status: 'connected', authResponse: { granted_scopes: '...', accessToken: '...', expiresIn:'...', signedRequest:'...', userID:'...' } } But PSA wan't to get data like /complete/facebook/?granted_scopes='...'&code='...'&state='...' Where state is parameter generated on backend for preventing CSRF. Am I missing something? -
Dynamically pull API data based on form field value in Wagtail/Django
I'm trying to create a form where users can search for a medical facility in a location using Django. The search results come from an API that displays countries, regions, cities, and the medical facilities within those locations. So far I have created the functions that pull in ALL of the data: import requests MAIN_URL = 'https://www.sample.com' API_KEY = 123456789 def get_countries(): response = requests.get('{}/GetCountryList?apikey={}'.format(MAIN_URL, API_KEY)) json_response = response.json() countries = json_response['GetCountryListResult'] return countries def get_regions(country): response = requests.get('{}/GetRegionList?countrycode={}&apikey={}'.format(MAIN_URL, country, API_KEY)) json_response = response.json() regions = json_response['GetRegionListResult'] return regions def get_cities(country, region): response = requests.get('{}/GetCityList?countrycode={}&regioncode={}&apikey={}'.format(MAIN_URL, country, region, API_KEY)) json_response = response.json() cities = json_response['GetCityListResult'] return cities def get_facilities(country, region, city): response = requests.get('{}/SearchByCity?city={}&regioncode={}&countrycode={}&apikey={}'.format(MAIN_URL, city, region, country, API_KEY)) json_response = response.json() facilities = json_response['GetFacilitiesByCityResult'] return facilities I have also created the view and passed these items through in context: class MedicalFacilitiesPage(Page, TranslatablePageMixin): def get_context(self, request): context = super(MedicalFacilitiesPage, self).get_context(request) context['countries'] = get_countries() context['regions'] = get_regions(country) context['cities'] = get_cities(country, region) context['facilities'] = get_facilities(country, region, city) return context The data is showing up in the select boxes when I do something like this: <select class="form-control searchOption" id="Country" name="Country"> <option value="">Select</option> {% for country in countries %} <option value="{{ country.CountryCode }}">{{ country.CountryName }}</option> {% … -
NoReverseMatch at /blog/ Using Django 2
Hello guys i am receiving this error : enter image description here this my main url urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls',namespace='blog')), ] My blog/url.py app_name = 'blog' urlpatterns = [ path('',views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<int:post>',views.post_detail,name='post_detail'), ] view.py class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published',publish__year=year,publish__month=month,publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) list.html {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2> <p class="date">Published {{ post.publish }} by {{ post.author }}</p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% include "pagination.html" with page=page_obj %} {% endblock %} I don't know what is the problem. Need a help pl -
Syntax behind how as_view() delivers callable, DJANGO
I will keep this question short. Similar questions on S/O do not address what I am wondering about, and I have struggled to find an answer. When I point to a CBV in my urls.py, I use the as_view class method: ...MyView.as_view()... Looking at the actual script (django/django/views/generic/base.py), the as_view returns a function 'view' that is specified within the actual class method itself. How come it returns the function with this line: return view Why does it not have to specify: return view(request, *args, **kwargs) I tried this out myself. I went and created a FBV_1 that returned yet another FBV_2 (the view responsible for delivering all functionality), in this same manner: return fbv_2 It generated an error. I had to return fbv_2(request) to access it. Thank you in advance. Apologies for any idiomatic expression-errors, my Swedish sometimes gets the best of me. -
How can I save image from MS AD, into the field of django model?
I tried ContentFile and save() method from FieldFile in views.py, but in the model I'm using ImageField. It even works. But the Image saving with strange id like NameOfImage_gdicbHhvd.jpg. How can I save it normally? -
Trying to edit profile for two different user types in Django
I have 2 user types, teacher and student. I have built the view to be able to edit a student profile. But I also needed a different one for teacher. I didn't want 2 views, because that would be pointless. Now, for teacher it works as intended, but for some reason for student, the same form as for teacher is displayed... a student has different attributes so it has a different form I need to show. @login_required def profile_edit(request): user = request.user student = request.user.student teacher = request.user.teacher if user == teacher.user: if request.method != 'POST': form = TeacherEditForm(instance=teacher) else: form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') elif user == student.user: if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') context = { "form": form, } return render(request, "registration/profile_edit.html", context) I think there is something wrong with the way I pass data to student and teacher and the view can't differentiate between user types. -
Django "UPDATE `django_session`" killing performances
My Django client was very slow during MySQL queries. Doing a tcpdump on the MySQL server, I saw that the following SQL query "UPDATE `django_session` SET `session_data`" [...] seems very long. What is the simplest way to solve this problem ? Thank you. -
Django Wagtail wagtailcore_tags image TemplateSyntaxError
I am following this Tutorial from Wagtail in Images Section to build my blog, I am having this weird TemplateSyntax Error which shouldn't be there. Please help me This is my HTML code. I use image from wagtailcore_tags. <div class="container"> <h1>Blog</h1> <div class="card-columns"> {% for post in blogpages %} {% with post=post.specific %} <a href="{% pageurl post %}"> <div class="card"> {% with post.main_image as main_image %} {% if main_image %}{% image main_image fill-160x100 %}{% endif %} {% endwith %} <h5> {{ post.title }} </h3> <p> {{ post.date }}</p> </div> </a> {% endwith %} {% endfor %} </div> </div> This is my models.py class BlogPage(Page): body = RichTextField() date = models.DateField("Post date") def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('body', classname="full"), InlinePanel('gallery_images',label= "Gallery images"), ] class BlogPageGalleryImage(Orderable): page = ParentalKey(BlogPage, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] And, this is the error I am getting -
How to compare form, model and auth_User in Django
I have a idea to create something like a admin panel. In that panel the user (or admin as well) for example in my case will can add a field named "website". And in this moment I have a problem. I've create in myapp model Website: from django.db import models from django.contrib.auth.models import User class Website(models.Model): user = models.ForeignKey(User,related_name="website_user", on_delete=models.CASCADE) website = models.CharField(help_text="Podaj stronę wraz z http lub https",max_length=250,verbose_name='Strona www', unique=True) class Meta: verbose_name = 'Strona www' verbose_name_plural = 'Strony www' def __str__(self): return self.website after that I've create a form to display for the user when is loggin: from django import forms from django.contrib.auth.models import User from .models import Website class WebsiteForm(forms.ModelForm): class Meta: model = Website fields = ('website',) Next step was a creating view : from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from .forms import LoginForm, UserRegistrationForm, WebsiteForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import Website ... @login_required def add_website(request): if request.method == 'POST': website_form = WebsiteForm(data=request.POST) if website_form.is_valid(): new_website = website_form.save(commit=False) new_website.post = add_website new_website.save() else: website_form = WebsiteForm() return render(request, 'konto/add_website.html', {'add_website': add_website, 'website_form': website_form}) and on the end I've create … -
In Django, how to add payments with fees to a freelance website?
I have a freelance website, written in Django. I need to implement a payment system: user should be able to pay to another user (it must be card transaction) and I have to receive some fee from each payment. How can I implement it?