Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert JS date string into django datetime format?
I have a Bootstrap datepicker and on date selection I make an ajax call and send in the user selected date, I want to change the date of the object in the database, but I get this error from django: [u"'04/23/2018' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] How do I convert it to the specified format? This is my code: Template: $('#project_date').on('changeDate',function() { $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', data: { new_date: $('#project_date_input').val() }, success: function(data){ //do something } views.py def project_change_date(request, pk): data = dict() project = get_object_or_404(Project, pk=pk) project.end_date = request.GET.get('new_date') opp.save() -
Image not uploading in db django cbv
I am using class based views for a form but image is not uploading in db, not showing any errors. here is my models.py class ProductCreateModel(models.Model): user = models.ForeignKey('accounts.SellerProfileModel', related_name='product_seller', on_delete=models.CASCADE,editable=False) title = models.CharField(max_length=120) slug = models/.SlugField(max_length=255,unique=True,blank=True) description = models.TextField(max_length=250) orignal_price = models.DecimalField(decimal_places=2, max_digits=8) discount = models.DecimalField(decimal_places=2,max_digits=4) discount_price = models.DecimalField(decimal_places=2,max_digits=8) image1 = models.ImageField(upload_to=upload_image_path,blank=True,null=True) here is my forms.py from django import forms from .models import ProductCreateModel class ProductCreateForm(forms.ModelForm): class Meta: model = ProductCreateModel fields = '__all__' here is my views.py class ProductCreateView(views.LoginRequiredMixin,ActiveSellerOnlyMixin,generic.CreateView,): template_name = 'products/create_new_product.html' model = ProductCreateModel form_class = ProductCreateForm success_url = reverse_lazy('home') def form_valid(self, form): product = form.save(commit=False) user = get_current_user(self.request) image1 = form.cleaned_data['image1'] form.instance.user = request.user return super(ProductCreateView, self).form_valid(form) # product.save() Now the form is submitted successfully but image is empty. -
django rest framework autorization returns wrong status code
I am new to django. I have a project that mobiles can have interaction with server using a token. In settings.py I have: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'UPLOADED_FILES_USE_URL': False, 'DEFAULT_PAGINATION_CLASS': None, 'PAGE_SIZE': DEFAULT_PAGE_SIZE, # For views using PageNumberPagination } but when using postman I send a request with an invalid token, istead of 401 (unauthorized), 403 (forbidden) is returning. Is there anything special I can do to fix this? tnx -
Django: Proper way to display options to the user in this case
EDIT Why would you downvote this question? Is there any question on SO that answers this that would show i didn't try to find it or google has answer to it that I missed? Or this is not the proper place to ask such questions? This is a simple question asking for advice on how to display options keeping MY particular data structure in mind. Please mention the reason for downvote. ORIGINAL I am trying to make my first website. I am using Django for it. I need advice from you people regarding UI of a portion of my template. I have a doctor user who will have to choose his clinic timings. So he has to choose from 7 days of week. Each day will have three shifts(Morning, Afternoon, Evening). He may choose 1 or more days and then for each day he may choose 1 or more shifts and provide time for each shift. How should I go about making options available to him so that it is easier for him to choose days-shifts-time and at the same time not clutter the UI? One way is to display all 7 days then under each day display three shift … -
How to differentiate between two user who are using same logIn and SignUp form in django?
This is my user's models.py. class User(AbstractUser): is_company = models.BooleanField(default= False) REQUIRED_FIELDS = ['email'] class InternProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name='intern_profile',primary_key=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): print('****', created) InternProfile.objects.get_or_create(user = instance) This is my Company's models.py. class CompanyProfile(models.Model): company = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=True, related_name='company_profile') Now, I am using boolean field 'is_company'. If company will register to the site then value of 'is_company' will become True. So, how can achieve this using allauth? -
Should I use Celery for the task
I am doing a project which would be a terminal server monitor for the company. The website is for engineers within the company to search for terminal information and session information. Now I have almost finished it with PHP and Vue.js. But when I test it, there is a problem, because there is some large query in the database(like searching for total sessions), it would take about one minute when we open the URL(cause I would display the summary information when users open the URL, so it would not open until large query finished). Also, I would do the periodical query(check terminal server state every 30mins, if it fails, notifying the admins). So for these two tasks, it is a good fit to use Celery and Redis as a broker? I think if I use Celery, it would do the large query in the backend so it would not slow down the website, and Celery is also good for periodic query. Is it right? Also, Does anyone use Celery with PHP and PostgreSQL before? I find a link about Celery api for PHP, but I hardly see anyone using Celery with PHP, Should I change to Django? Thank you so … -
Django full text search: says unaccent does not exist
I am using Django 2.0 and postgresql 9.6 I have created and empty migration file in my app (articles) with the following content to add unaccent and trigram extensions # Generated by Django 2.0 on 2018-02-06 22:34 from django.db import migrations from django.contrib.postgres.operations import UnaccentExtension, TrigramExtension class Migration(migrations.Migration): dependencies = [ ('articles', '0012_auto_20180205_2234'), ] operations = [ UnaccentExtension(), TrigramExtension() ] Then i try to run the following query: from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector vector = SearchVector('title',config='unaccent', weight='A') + SearchVector('description',config='unaccent', weight='B') query = SearchQuery('india') Article.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank') ProgrammingError: text search configuration "unaccent" does not exist LINE 1: ...rticle"."qa_bool", ts_rank((setweight(to_tsvector('unaccent'... -
How to remove a field and set default value for a ModelForm in Django?
I have a ModelForm in my forms.py as follows: class ChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text', 'is_choice_correct'] labels = { 'choice_text': "", 'is_choice_correct': "" } widgets = { "choice_text": forms.Textarea(), "is_choice_correct": "", } Based on some conditions, I would like the is_correct_field, a boolean field to not display in the form and set default value for the field (because it is required) so that when I write form.save() in my views, there occurs no error. However, I don't want to hide the form field. To make it more clear, here's what I want to say. I submit the form with only choice_text in my form. The form does not contain the field is_choice_correct, either hidden or displayed. When I save the form with form.save(), I want the is_choice_correct to be True. -
Django: Redirect to different page if logged in in urls.py
I have this url: url(r'^signup/$', TemplateView.as_view(template_name='users/signup.html')), and I want the user to be redirected to a different url, if they try access this page and are already logged in. Is there anyway I can do this in the urls.py or will I have to write a view for it? -
Should my site be connecting to the websocket on *every* page, and not only on the pages requiring websockets?
I've implemented Django-Channels to use with a particular feature of the site--instant chat. The JS required as part of allowing channels is run on every page, and I'm wondering if this could potentially lead to any security holes. For example, here's the JS required by Channels. The socket connects and opens with every page, regardless of whether the user is using the chat feature or not. $(function () { // Correctly decide between ws:// and wss:// var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var ws_path = ws_scheme + '://' + window.location.host + "/chat/stream/"; console.log("Connecting to " + ws_path); var socket = new ReconnectingWebSocket(ws_path); socket.onopen = function () { console.log("Connected to chat socket"); }; ... Is this acceptable? If not, how should I adjust? -
PostgreSql and Django How to store large data (6GB+) per entry or row
Recently, I'm working with one project (Django + PostgreSQL), I store record as normal text type after encode to base64. After awhile I came to realize that storing record that I store some record size is around 6GB which is over max-size of 1 GB in text of postgres. I try to search around and got some recommend of using BLOB in Postgres. I further research more in how to use it with sample ,but seem no answer. Anyone use to Experience it, really appreciate ? -
Accidental GET request before/after POST in Django + Ajax
I have made a simple Django + Ajax web app: The inline form in bootstrap has two controls: Input and a Button. When the user stops typing, the suggestions are shown and the user can select any one of them. After selecting and clicking on Search, it should show an alert with the "description". I get the alert only sometimes, but when I do, the url changes to: http://localhost:8000/?csrfmiddlewaretoken=CYTL3UgoNA8fcZQVZRftxsFEZk0wJHEt8je13lB02IhoGJmWS2GxrmILcwPgM9Bw Timelog: 08:32 - First try, gave no alert due to the output in the console 08:33 - Got the alert and the url changed in the browser How do I prevent the change in the url? And how to prevent the error: ConnectionAbortedError: [WinError 10053]? Python console output: [07/Feb/2018 08:32:49] "GET /boards/autocomplete/?q=Dummy HTTP/1.1" 200 27 [07/Feb/2018 08:32:52] "GET /boards/autocomplete/?q=Dummy%20Board HTTP/1.1" 200 27 [07/Feb/2018 08:32:52] "GET /?csrfmiddlewaretoken=iZ5IFGniIEiM78GqxYovvBHW9f0EvdbuOkqYF7IUXMrVBScrq9PzpvK3mrPoyF8x HTTP/1.1" 200 5385 [07/Feb/2018 08:32:53] "POST /boards/get-description/ HTTP/1.1" 200 15 Traceback (most recent call last): File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "c:\users\90348325\python\Lib\socketserver.py", line … -
python remove ss from HH:MM:ss and display only HH:MM
I have an input string like this HH:MM:ss 01:22:00 I want to remove seconds (ss), so that it is only HH:MM 01:22 How can I achieve that in python ? -
How to handle already registered social user in frontend (django-rest-auth)?
I've been using django-rest-auth, which has been great for email signup flow. I've been trying to implement social login (via FB), and in the latest version, it seems if someone has already created an account via email, they just raise an error if that user tries to login via social. This comment is in the commit: # We have an account already signed up in a different flow + # with the same email address: raise an exception. + # This needs to be handled in the frontend. We can not just + # link up the accounts due to security constraints Couple of questions (posted this in the github issues as well): Why is this a security issue? Isn't the whole point of social authentication that you trust the OAuth provider (FB in this case)? Second, how is one supposed to handle this in the frontend? It's a common occurrence that people sign up for email first (often simply because a site or app adds social login later in the development cycle). It seems to me the only option this leaves me with is to tell the user "Sorry, you can only login with your email account." Or to … -
Can't I use images from lists in the same order?
Can't I use images from lists in the same order? I wrote in views.py import os import cv2 from pathlib import Path path1 = Path(__file__).parent path1 /= "../test1" path2 = Path(__file__).parent path2 /= "../test2" index_list =[] for i in path1.iterdir(): i = str(i) if i.split(".")[-1].lower() in {"jpeg", "jpg", "png"}: img = cv2.imread(i) if img is None: print("Couldn't open file %s" % i) else: index_list.append(img) index_list1 =[] for j in path2.iterdir(): j = str(j) if j.split(".")[-1].lower() in {"jpeg", "jpg", "png"}: img1 = cv2.imread(j) if img1 is None: print("Couldn't open file %s" % j) else: index_list1.append(img1) index = index_list[0] index1 = index_list1[0] In test1 & test2's folder,same images are in there.So I think index_list & index_list1 have same images in the same order.But when I access codes like index = index_list[0] & index1 = index_list1[0],index & index1 's variable have different images.I really cannot understand why such a thing happens.I wanna get same image in these 2 variable,so how can I fix this?What is wrong in my code? -
implementing Post/Redirect/Get pattern, Django Pagination Post method
Using django 2.0 When I click on the link to take me to page 2 of results it takes me to the original query page. Views.py def profile_advanced_show(request): q = filter() qlist = q count = q.count() paginator = Paginator(q, 5) page = request.GET.get('page') contacts = paginator.get_page(page) return render(request, 'saferdb/list.html', {'contacts': contacts}) class QueryView(ListView): template_name= 'saferdb/query.html' def post(self, request): return profile_advanced_show(request) URLS.py url(r'^$', views.index, name='index'), url(r'/(?P<page>\d+)/$', views.profile_advanced_show), url(r'^query/$', views.QueryView.as_view(), name='query'), I want my URLS.py to redirect everything that ends with /?page=2 to be handles by the profile_advanved_show method. I was trying to follow this response. -
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?