Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to adding comments option on a post
I am developing a blog which i want to add comment form option to it, i have added the form to the same page directly under the article, i want that went a user comment it should redirect to the same page with the article but i keep getting and error here is my code view def comment(request, article_id): try: article = Article.objects.get(pk=article_id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.cleaned_data['comment'] article.comments_set.create(comment=comment) #messages.infos(request,comment) return redirect('blog:_article') #else: #pass #form = CommentForm() #context['form'] = form #return render(request,'blog/comment.html', context) except Exception as e: #wriet error to file return render(request,'blog/404.html') urls from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.index, name='index'), path('<int:article_id>/article', views._article, name='_article'), path('<int:article_id>/comment', views.comment, name='comment'), ] models class Comments(models.Model): comment = models.TextField() date = models.DateTimeField(default=timezone.now) article = models.ForeignKey(Article, on_delete=models.CASCADE) def __str__(self): return self.comment form <form method="post" action="{% url 'blog:comment' article.id %}"> {% csrf_token %} {% for field in form %} {{ field.label_tag }} {% render_field field class="form-control is-valid" rows="4" %} {% endfor %}<br> <button class="btn btn-success">Post</button> </form> -
Django Channels ws url not connecting when page loads
I'm trying to setup django channels with the following code consumery.py from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) routing.py from django.conf.urls import url from consumers import ChatConsumer #supposed to be on the main routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter websocket_urlpatterns = [ url(r'^ws/chat/$', ChatConsumer), ] #after linking to above as chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) settings.py ASGI_APPLICATION = 'chatsys.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } INSTALLED_APPS = [ ... 'channels', ] script.js //Sockets var myWebSocket = new WebSocket("ws://" + window.location.host + "/chat/"); myWebSocket.onopen = … -
Cannot resolve keyword 'user' into field. Choices are:
I am new to django. I created a page to get the user to login to my app after registration but when I try to login I get the exception saying: Cannot resolve keyword 'user' into field. Choices are: id, rating, video_details, video_logo, video_name Here is my view for the login : def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) videos = Video.objects.filter(user=request.user) return render(request, 'dash_interface/index.html', {'videos': videos}) else: return render(request, 'dash_interface/login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'dash_interface/login.html', {'error_message': 'Invalid login'}) return render(request, 'dash_interface/login.html') the forms.py: from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'password'] I've set the login url: url(r'^login_user/$', views.login_user, name='login_user'), and here is my HTML code: {% extends 'dash_interface/base_visitor.html' %} {% block title %}Log In{% endblock %} {% block login_active %}active{% endblock %} {% block body %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="panel panel-default"> <div class="panel-body"> <h3>Log In</h3> <form class="form-horizontal" role="form" action="{% url 'dash_interface:login_user'%}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="control-label col-sm-2" for="id_username"> Username: </label> <div class="col-sm-10"> <input … -
Unable to display the image in the Template
I am using the models.ImageField in Django to store the images in the MEDIA_ROOT folder that I declared to be static/img/. When I try to display the image I am unable to. I omitted the futile fields to this context models.py class Blog(models.Model): image_url = models.ImageField() def __str__(self): return f'{self.title} create on {self.datetime}' views.py def blog(request): blog_view = Blog.objects.all() return render(request, 'blog/blog.html', {'blog': blog_view}) blog.html {% for i in blog %} <img src="{{ MEDIA_URL }} {{i.image_url.url}}" alt="Avatar" style="width:100%"> <div class="container"> <h4><b>{{ i.title }}</b></h4> <p>{{i.content}}</p> </div> {% endfor %} I have already tried settings.py MEDIA_ROOT = r'A:\Jetbrains\Pycharmprojects\project\static\img' -
Nginx - Landing Page Redirects
I have a website running on django, python. Google PageSpeed Insights shows an error that Your page has 3 redirects. Redirects introduce additional delays before the page can be loaded. http://www.example.com/ https://example.com/ https://www.example.com/ Here's my nginx server configuration, server { listen 80; server_name example.com www.example.com; rewrite ^/(.*) https://example.com/$1 permanent; } server { listen 443 ssl; server_name www.example.com; ssl_certificate /home/data/example.com.chained.crt; ssl_certificate_key /home/data/example.com.key; . . . } So, how can I prevent these server redirects for a better response time? -
Use query result from semantic UI inside Django URL Template tag
I'm using django and semantic UI to create a search box. Everything works fine except for the URL parameters. $('.ui.search').search({ type : 'standard', minCharacters : 2, apiSettings : { onResponse: function(parcelleResponse) { //DO Something return response; }, url: "/myUrl/{query}" } }); I would like to use the URL template tag system to specify the URL : {% url 'searchParcelle' {query} %} But as the results returned by Semantic UI are stored inside a variable {query}, I've got a template error : Could not parse the remainder: '{query}' from '{query}' Do you know how I could resolve that ? I could keep it like this, but as my Prod URL (virtual host) is a bit different is not the same, I have to change it every time. Thanks for your help -
Enforce Order for Chained Django Select2
I'm looking to create a form with dependent select drop-downs in Django. Following the docs for django-select2 and the answer here I can easily create a dependent drop-down which filters the second select based on the first. However, you can actually make a choice in the second select before the first, and have all possible cities available. What I would like is to only provide the choices for the second select (city) after the first (country) has been completed. The only solution I have come up with so far is to use JS to disable the second input until the first has a value, but this seems a fairly flimsy fix. -
Celery received unregistered task of type 'api.tasks.cl_daily_statistics'. But it task is registered
i have trouble with celery tasks, when i up docker containers get this error celery_1 | [2018-06-07 11:35:26,302: ERROR/MainProcess] Received unregistered task of type 'api.tasks.cl_daily_statistics'. celery_1 | The message has been ignored and discarded. celery_1 | celery_1 | Did you remember to import the module containing this task? celery_1 | Or maybe you're using relative imports? celery_1 | celery_1 | Please see celery_1 | http://docs.celeryq.org/en/latest/internals/protocol.html celery_1 | for more information. celery_1 | celery_1 | The full contents of the message body was: celery_1 | b'[[], {}, {"chain": null, "chord": null, "errbacks": null, "callbacks": null}]' (77b) celery_1 | Traceback (most recent call last): celery_1 | File "/usr/local/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 561, in on_task_received celery_1 | strategy = strategies[type_] celery_1 | KeyError: 'api.tasks.cl_daily_statistics' but, if i run this root@vm115056:/back_new# docker-compose exec celery bash root@da2b33f2d7a1:/app# celery -A backend inspect registered -> celery@da2b33f2d7a1: OK * Daily email statistics * FB token status * MD token status * OK token status * TW token status * VK token status * api.tasks.message_send * api.views.chord_result * backend.celery.debug_task * stats.tasks.test it's celery task, function daily_statistics in other module, in tasks.py it only imported and wrapped task decorator @task(name='Daily email statistics') def cl_daily_statistics(): daily_statistics() def daily_statistics(): try: count_users = UserProfile.objects.count() count_created_messages … -
django form validation, allow an exception in the validation?
I am using an IP address field in Django and with the form.is_valid() option unless a valid IP address is inserted the form will return errors. However, I would like to allow the word 'auto' to also be valid. Is it possible to add exceptions to the validation function? And if so would these go in forms.py or views.py? -
Django, display python execution real time output on webpage - as console
(Using Django) I'm creating a web application, this is how it's supposed to work : From the webpage - User selects an option, clicks on it The URL hits the associated view Inside the view function, another python module function start processing - which takes a while (could be 5 mins or 2 hours) The function execution logging is visible on the webpage as it happens - real time execution is visible on the webpage itself (asynchronously) I found that, this can be achieved using AJAX. And I tried something like this: views.py: from lib.testnew import testprint def printtest(request): if 'create_btn' in request.POST: test = testprint() data = test.printing() logger.info(data) return render(request, 'create.html', {'data': data}) else: logger.info("initiating") return render(request, 'createvm.html') create.html {% extends 'base.html' %} {% block content %} <script type="text/javascript"> $(document).ready(function(){ $('#create_vm_btn').click(function(){ $.ajax({ type: "POST", url: "printtest", success: function(data) { $("#output_id").html(data); alert('Done: ' + data); } }); }); }); </script> <h2>Welcome {{ user.first_name }} {{ user.last_name }}</h2> <form method="post"> <textarea id="output" row=3 cols=25></textarea> <button type="submit" class="btn btn-default" name="create_btn" id="create_btn">Create</button> </form> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> {% endblock %} The below line takes time to execute : data = test.printing() But it doesn't seem to have worked as I want it to. Kindly … -
NewRelic- Generate alert in case if application (Python/Django) service goes down?
I have a Python Django Application which is running on Amazon EC2 instance. I have setup newrelic 7 configured for performance measurement. Now I want to get a notification from newrelic if service goes down. How to setup for alert ? Please help. -
How to insert data from one table to another without knowing the number of Columns
I am trying to transfer data from a table in one RDBMS to another in a DJANGO based project.I want to automate this. I am planning to use this function. However, I can't find a way to automate this, without knowing the number of fields in each model. Is there a way to do the above task without knowing the number of fields of a given table? def sql_batch_insert(n_records): sql = 'INSERT INTO app_testmodel (field_1, field_2, field_3) VALUES {}'.format( ', '.join(['(%s, %s, %s)'] * n_records), ) params = [] for i in xrange(0, n_records): params.extend([i, str(i), timezone.now()]) with closing(connection.cursor()) as cursor: cursor.execute(sql, params) -
How do I write a django query to join on more than one condition
I'm struggling to write a django query which widens data like the below sql statement. select t1.id ,t2a.value value_a ,t2b.value value_b from t1 left join t2 as t2a on t1.id = t2a.request_id and t2a.type = 'a' left join t2 as t2b on t1.id = t2b.request_id and t2b.type = 'b' Any help would be really appreciated! -
apache- cv2.VideoCapture(0) not able to open camera
I have made a django application where I use video camera to capture an image. The app is working when I run it via django. For stability purposes I had to put apache on it and run it via mod_wsgi. I am getting a status false on line status, frame = cv2.VideoCapture(0) Is this a threading problem as I have not configured number of threads in apache conf -
Django Template loop with variable
I am having issue with django html variable so I made the below code which is working . {%for field in instance %} <tr> <td width="250"> {{ field.Item }} </td> <td> <input type="text" value={{ field.P_640 }} > </td> {% endfor %} But at the view section I have variables and sometimes I am pushing filter value. P_640 and sometimes P_630 .How can I make my template to look to the colomn 1 instead of looking the filed name, because it's not working when I push P_630. ? -
Django auth and Postman requests
How do I authenticate a Django user, when making requests with Postman? I am not using Django Rest framework, just the standard dango.cont.auth system. In Postman you have the following options for authentication: Basic Auth, OAuth, and Custom. In custom I can add some headers. How do I do this? -
Django function that returns a list of messages, then add these messages to view?
I have a function that I would like to return messages, but I dont want to include the requests into this function (as sometimes I would like it to run without requests) for example: def auto_gen_model(site_id, base_model_id): site_data = Site.objects.get(pk=site_id) try: base_model_data = SiteModels.objects.get(model_id=model_id) except: # need matching model data messages.add_message(request, messages.ERROR, 'A base model should exist before generateing a new model') return messages #continue to do more stuff ... messages.add_message(request, messages.SUCCESS, 'a new model has been auto generated') return messages the problem is that I dont send request to messages so the function will fail. how can I just create a list of messages, return the messages, then in the view send the messages to the template? Thanks -
Serialize Django object TemporaryUploadedFile to JSON
I am trying to execute celery task but i use an object <class 'django.core.files.uploadedfile.TemporaryUploadedFile'> in the calling task that i need to serialize to execute it with celery. Otherwise, i have this kombu.exceptions.EncodeError: <TemporaryUploadedFile: a_file.csv (text/csv)> is not JSON serializable error. Here the task calling function. def manager_a_file_tasks(a_file, archive_path): # serialize to json a_file = serializers.serialize("json", a_file) job = load_a.s(a_file, archive_path) job.delay() And i have this error AttributeError: 'bytes' object has no attribute '_meta' Thanks in advance for your help. -
Django query for total balance from different currency wallets
What is the best way to get total balance of the user wallets with different currencies? myapp/models.py from django.db import models from django.contrib.auth.models import User USD = 'USD' EUR = 'EUR' GBP = 'GBP' CURRENCY_CHOICES = ( (USD, 'US Dollars'), (EUR, 'Euro'), (GBP, 'UK Pounds'), ) class Wallet(models.Model): user = models.ForeignKey(User) accnumber = models.CharField(max_length=12) currency = models.CharField(choices=CURRENCY_CHOICES, default=EUR) balance = models.DecimalField(max_digits=9,decimal_places=2) Currency rates are obtained from the fixer.io myapp/views.py import requests from decimal import Decimal from django.views.generic.base import TemplateView from django.db.models import Sum from myyapp.model import Wallet, CURRENCY_CHOICES class TotalBalanceView(TemplateView): template_name = 'balance.html' def get_context_data(self, **kwargs): context = super(TotalBalanceView, self).get_context_data(**kwargs) #get current exchage rates from Fixer.IO uri = "http://data.fixer.io/api/latest?access_key=XXX&base=EUR" r = requests.get(uri) rates = r.json()['rates'] #get account for the user wallets = Wallet.objects.filter(user=self.request.user) total_usd = wallets.filter(currency=USD).aggregate( total=Sum('balance')) total_gbp = wallets.filter(currency=GBP).aggregate( total=Sum('balance')) total_eur = wallets.filter(currency=EUR).aggregate( total=Sum('balance')) context.update({ 'wallets ': wallets 'total': total_eur + total_usd * rates['USD'] + total_gbp * rates['GBP'] }) return context myapp/templates/balance.html <h1>Total is: {{ total|floatformat:2 }}</h1> {% for w in wallets %} <p>{{ w.accnumber }}</p> {% endfor %} I am sure there should be more efficient solution using Aggregate functions in one query request -
Django and Mysql : change PK type from uuid to integer and change data
I have a bunch of data like 600000000. When I add this data, I just made pk type as uuid without serious thinking. After using this table for a long time, just realized that it was no need to make pk as uuid since data is kinds of history log. Also, I just started to think that if I keep this uuid pk, It may consume more space in memory than using integer pk. So now I'm considering about changing the model column type and also replace all uuid into an autogenerated integer. However, the table is already is on production and I can't stop service. I wonder if there is a way to change pk to integer without stopping service. -
How do we dynamically add alias to complex aggregate?
for *key*,*value* in dict_test.items(): data = (Model.objects.filter(id__in=*value*) .annotate(num=Func(F('amount'), template='%(function)s(%(expressions)s AS % (type)s)', function='Cast', type='float') ).aggregate(*key*=Coalesce(Sum('num'),0)) Instead of getting 'key', I want the actual key from the for loop. I'm using Django=1.9.1 -
Django forms dynamic dropdown list creation
views.py def repair_form(request): dlist = get_my_choices(request.user) if request.method == "POST": form = RepairForm(request.POST,device_type = dlist, submitted_by = request.user) #print(form) if form.is_valid(): print("Inside repair form") post = form.save(commit=False) post.submitted_by = request.user print(post.pk) post.save() return redirect("RepairRequest") else: dlist = get_my_choices(request.user) print("Inside else of repair form") form = RepairForm( device_type = dlist, submitted_by = request.user) print("else form: ", form) return render(request, "Form_template.html", {"form": form,\ "name": "Repair Request Form"}) forms.py class RepairForm(forms.ModelForm): def __init__(self, *args, **kwargs): print("kwargs: ",kwargs) dlist = kwargs["device_type"] print("Inside init of RequestForm") super(RepairForm, self).__init__(*args, **kwargs) self.fields["device_type"] = forms.ChoiceField(choice = [dlist]) self.fields["submitted_by"] = kwargs["submitted_by"] class Meta: print("Inside Meta of RepairForm") model = Repair print("model: ", model) fields = "__all__" print("fields: ", fields) exclude = ("repair_cost_estimate","repair_status","submitted_by","repair_request_date",) I am trying to create a dynamic dropdown list in django forms. Dynamic in the sense that the dropdown list will only populate with the data that is associated with the given user. In my case, each user may have a laptop, mouse, etc. with him. I have written the code shown above. Every time I execute the code I get the following error: TypeError at /user_dashboard/RepairRequest.html __init__() got an unexpected keyword argument 'submitted_by' Request Method: GET Request URL: http://127.0.0.1:8000/user_dashboard/RepairRequest.html Django Version: 1.11.13 Exception Type: TypeError Exception … -
Django stateful connection with command line tool
I use Django as framework for a smart home. There I have a python shell script which connects to bluetooth devices and steers them. Now I want to start the bluetooth connection once e.g. by an admin and clients should be able to use the connection and the shell script. Actually I am starting and stopping the connection for each command (on a button click). This seems to be a bad solution because of the unnecessary connection overhead and furthermore the device status can change while the device is not connected - so the device status need to be polled on each connection. How can a stateful solution be implemented? -
Loop over a custom tag with a parameter that returns a query
My custom tag is: register = template.Library() @register.simple_tag def last_three_messages(request): u=User.objects.get(username=request.user) last_three_messages=Message.objects.filter(to_user=u, opened=False)[:3] return last_three_messages How can I loop over this in the template? I tried: {% for message in last_three_messages request %} do something {% endfor %} This returned an error: 'for' statements should use the format 'for x in y': for message in last_three_messages request How can I loop through the queryset and pass request as parameter? -
django, angular, csrf, rest_framework, 403,
I'm brand new to developing with only background in vbscript and html. I'm an architect by trade but, circumstances have put me in the hot seat. I'm busy developing my first project and have been blocked by CSRF for the last 4 days. I have tried everything that I could find on the net but with no success. I hope that someone can help me crack this as I have a deadline to complete for testing before end of this week. What I need to try and accomplish is: 1. Authenticated user should submit an angular form to a django rest_framework api. 2. The info submitted to the django api should then be used to submit a soap request to a 3rd party wsdl service. 3. The response should then be saved to a .pdf file and rendered on the page. I'm currently stuck on the first point of this process and have not even started on point 2 and 3 as point 1 has had me searching through the web for the last 4 days. Below is my error: Forbidden (CSRF token missing or incorrect.) Below is my html template person_search_new.html: <!DOCTYPE html> <html lang="en"> {% extends 'base/base.html' %} …