Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket error using Django Channels with EC2
I'm trying to build an app in Django that uses Django Channels. I'm deploying on Elastic Beanstalk. My understanding is that the application load balancer supports websockets and I can route websocket traffic to the appropriate port. The websockets work on my localhost:8000. I'm using the free tier Redis Labs for my channel layer. I followed this tutorial. https://blog.mangoforbreakfast.com/2017/02/13/django-channels-on-aws-elastic-beanstalk-using-an-alb/#comment-43 Following this tutorial it appears I can get Daphne and the workers running on the correct ports. I SSHed into the EC2 instance to get the following output. $ sudo /usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf status Daphne RUNNING pid 4240, uptime 0:05:51 Worker:Worker_00 RUNNING pid 4242, uptime 0:05:51 Worker:Worker_01 RUNNING pid 4243, uptime 0:05:51 Worker:Worker_02 RUNNING pid 4244, uptime 0:05:51 Worker:Worker_03 RUNNING pid 4245, uptime 0:05:51 httpd RUNNING pid 4248, uptime 0:05:51 My daphne.out.log and workers.out.log look fine. $ cat daphne.out.log 2017-07-20 21:41:43,693 INFO Starting server at tcp:port=5000:interface=0.0.0.0, channel layer mysite.asgi:channel_layer. 2017-07-20 21:41:43,693 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2017-07-20 21:41:43,694 INFO Using busy-loop synchronous mode on channel layer 2017-07-20 21:41:43,694 INFO Listening on endpoint tcp:port=5000:interface=0.0.0.0 $ cat workers.out.log 2017-07-20 21:41:44,114 - INFO - runworker - Using single-threaded worker. 2017-07-20 21:41:44,120 - INFO - runworker - Using … -
Django issue uploading files to server
I believe I have a permission's issue with how my Django instance is set up. The site is up but when I try to upload an image file from the admin it upload and the field has the proper filename but the file isn't uploaded to the server. server { listen 80; server_name pluscolor.co.ke www.pluscolor.co.ke 138.197.124.71; client_max_body_size 32m; location /static/ { root /home/sammy/revamp/revamp; } location /media/ { root /home/sammy/revamp/revamp; } location / { include proxy_params; proxy_pass http://unix:/home/sammy/revamp/revamp.sock; } } -
Pass value from Django to Ajax, how to identify variable type?
In Django, I have a variable flag=True. I pass it to script in Html : <script> if({{flag}}==True) do something </script> I assume do something will be called, but it is not. It looks like True not equal to True. Could anyone teach me how to fix it? -
React.js using JQuery to Post Django got 403
I know this should be csrf problem. But it works differently on different port. The Django server is on 8000 and then I test the front end on both 3000 and 8000, I got: When I test front end on localhost:3000, I can get the post work; When I test front end on localhost:8000, I get 403; $.post("http://localhost:8000/todos/", {title:this.refs.title.value,text:this.refs.text.value }); Any ideas how it works? -
Django_filters with django-autocomplete-light
I am using django-autocomplete-light with django_filters. I looked django-filter with django autocomplete-light, but my autocomplete doesn't work. Models.py: class ProfessionalDevelopment(models.Model): Name = models.CharField("Professional Development", max_length=20,default = "None") ProfessionalExperience = models.ManyToManyField(Person, through='PersonToProfessionalDevelopment') class PersonToProfessionalDevelopment(models.Model): PersonID = models.ForeignKey(Person, on_delete=models.CASCADE) ProfID = models.ForeignKey(ProfessionalDevelopment, on_delete=models.CASCADE) Desc = models.CharField("Professional Development Description", max_length=30, default="None") Views.py: class ProfessionalDevelopmentAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = ProfessionalDevelopment.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs urls.py urlpatterns = [url(r'^search/ProfessionalDevelopment-autocomplete/$', ProfessionalDevelopmentAutocomplete.as_view(), name='ProfessionalDevelopment-autocomplete'] Filters.py: ProfessionalDevelopment = django_filters.CharFilter(name='professionaldevelopment__Name', lookup_expr='icontains', widget=autocomplete.ModelSelect2(url='RSR:ProfessionalDevelopment-autocomplete')) I got an error says 'list' object has no attribute 'queryset'. Then I changed the code to autocomplete.Select2 instead of autocomplete.ModelSelect2 (according to https://github.com/yourlabs/django-autocomplete-light/issues/763). Although no error, but I can not type in the text input box. Could someone help me? Thanks -
Django rest-auth password reset not working
I'm using Django for building a RESTful API for a mobile app, I use django rest-auth library for authentication, but I get the following error when I try using password reset: NoReverseMatch at /auth/password/reset/ Reverse for 'auth_password_reset_confirm' with arguments '(b'OQ', '4nx- 6653c24101b5443f726b')' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Given this snippet from my url patterns url(r'^', include('django.contrib.auth.urls')), url(r'^auth/', include('rest_auth.urls')), url(r'^auth/registration/', include('rest_auth.registration.urls')), I tried some solutions mentioned here (as adding this first pattern in the snippet) but still having the same error. -
possible to filter the queryset after querying? django
Sorry if the question sounds weird. I am just wondering if there is possible to make new queryset when I already have a queryset. For example here... everyone = User.objects.filter(is_active=True) # this would of course return all users that's active not_deleted = User.objects.filter(is_active=True, is_deleted=False) # return user that's active and not deleted is_deleted = User.objects.filter(is_active=True, is_deleted=True) # return user that's active and is already deleted What my question is...for not_deleted and is_deleted they both have active is true with is the same as everyone is there a possible way to use everyone and then somehow filter out is_deleted=True or is_deleted=False? So then I believe the querying would be faster and better if this is possible right? All three variables everyone, not_deleted and is_deleted will then be used for something else. Hopefully I made my question quiet clear. Thanks in advance. -
Can `Man In Middle Attack` break The CSRF_TOKEN protection?
I am looking into the django csrf_token protection, I have known about how it works, but there is still a question that I want to know.For example, in a http request, if the attacker can sniffer all of a user's network traffic, which means the attacker can still get the csrf_token and make a fake request with the valid csrf_token. As mentioned CSRF, I have the same doubt about JSON WEB TOKEN, if the attacker get a user's TOKEN ,he\she can still make a fake request. Could you please explain if my example description is correct? And if so, what can we do to handle this? -
Django Finite State Machine and FSMKeyField - saving forms
I have implemented django-fsm's FSMKeyField as documented: class ClaimState(models.Model): id = models.CharField(primary_key=True, max_length=50) label = models.CharField(max_length=255) def __str__(self): return self.label and have populated the ClaimState model with states via fixture, and am using an FSMKeyField pointer from another model: class Claim(models.Model): state = FSMKeyField(ClaimState, default='new') ... The foreign key works fine from a Django shell - I can do: s = ClaimState.objects.first() Claim.objects.create(state=s) No problem. But when I try to save a claim from the Django Admin or from my own form, I get the error: claim state instance with id <ClaimState: Rejected> does not exist. If I view source, I can see that the dropdown values are the PKs, so it's not clear why it's treating the whole object as if it were the ID. Not sure what's causing this or the best way to solve? -
django ModelForms - am I doing it right?
I have a polls app extension that uses a 6-field or 8-field answer. I've defined these ModelForms very minimally. class expert_judgement_three_form(ModelForm): """From Burgman "Trusting Judgements" 2016 p95. Values are probabilities """ class Meta: model = EJ_three_field exclude = ['question','user'] [The forms seem to need a lot of manual config in the template to get them into estimate : rationale pairs] To prepopulate the fields, I'm creating an object instance of the model, then passing that to the form, then getting it back from the form. The example in the docs steps through the cleaned_data dictionary item by item - it doesn't seem to reduce boilerplate all that much. I note this reply and I've seen this answer and am probably going to work this way. I can't escape the feeling that I've misunderstood or misread the key features of how forms, and in particular modelforms, should be used, because so much is still visible (and giving me trouble). A good answer to this question would be the sparsest possible model, ModelForm, and View for a multi-field form that always prefills from the users previous answers to questions. -
Base Admin class with a dynamic list_display
I have written a base class for admin classes for all of my classes that have a field called is_active. It enables the user to see the records of the table along with the is_active field so that they can see which record is active or not and they can edit it. For most of the classes that I have in my models, there is a field called name so I can easily write 2 lines of the code in admin.py and have a customized admin representation, but the problem is for the classes that don't have a field called name so I have to use a different field in list_display . Since the number of these classes is high, I am looking for a solution to either dynamically get the name of the field that must be in the list_display. Any ideas to solve this problem would be much appreciated. models.py: class BaseAdmin(admin.ModelAdmin): list_display=('id','name','is_active') list_editable = ('is_active',) # this MUST only contain fields that also are in "list_display" search_fields=('name',) class ClassA(models.Model): name=models.CharField(max_length=20, blank=False, unique=True,) is_active=models.BooleanField(default=True,) def __str__(self): return self.name class ClassB(models.Model): my_field=models.CharField(max_length=20, blank=False, unique=True,) is_active=models.BooleanField(default=True,) def __str__(self): return self.my_field admin.py class ClassAAdmin(BaseAdmin): pass class ClassBAdmin(BaseAdmin): pass -
Python Django - Passing 2 Parameters To View - NoReverseMatch at /malware/
So I am creating an application in Django. I am passing 1 parameter fine in other parts of the application however when adding two i think i get the regex wrong. This is the part of the url.py: url(r'^(?P<uuid>(\d+))/(?P<malware>(\d+))/$', views.execute, name='execute'), This is the html file: <li><a tabindex="-1" href="{% url 'execute' malware=malware uuid=uuid %}"> {{ vm }}</a></li> This is the error: Reverse for 'execute' with keyword arguments '{'uuid': '2932b679-787a-48e0-a4f7-be020b8e4734', 'malware': 'calc.exe'}' not found. 1 pattern(s) tried: ['(?P<uuid>(\\d+))/(?P<malware>(\\d+))/$'] I am assuming this error is due to the regex. Any help would be very much appreciated. -
Running django in virtualenv - ImportError: No module named django.core.management - Windows 7
I am attempting to configure a virtual environment on a Windows machine with virtualenv and I have been unable to to run manage.py I reviewed a few other stackoverflow answers (Running django in virtualenv - ImportError: No module named django.core.management?) and was unable to resolve the issue that I am having. Here is where I am at... C:\Users\tyarboro\Documents\Project (master) (venv) λ pip freeze Django==1.7 django-admin-sso==2.1.0 django-social-auth==0.7.28 httplib2==0.9.2 json2html==1.0.1 oauth2==1.9.0.post1 oauth2client==2.2.0 pyasn1==0.1.9 pyasn1-modules==0.0.8 python-openid==2.2.5 rsa==3.4.2 six==1.10.0 C:\Users\tyarboro\Documents\Project (master) (venv) λ manage.py Traceback (most recent call last): File "C:\Users\tyarboro\Documents\Project\manage.py", line 9, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' I have attempted the following modifications to the manage.py Removed the first line of the file #!/usr/bin/env python Set the sys.path.append to the directory that contains the site-packages in my virtual environment. sys.path.append('C:\Users\tyarboro\Documents\Project\venv\bin\activate\Lib\site-packages') I think the issue is that the virtual environment is running Python outside of the virtual environment instead of within the virtual environment. Any suggestions on how to fix this? Thanks! -
How to send files from one View to another (django sessions)
So i'm trying to send a image object from one view to another. Is there a way to get the image file in View1 to View2 without changing the data. I'v tried converting the image data into a string so it can be JSON serializable, however doing this i run into some problems with manipulating the string. So i figured the best way would be to just send the whole image (untouched). The code below spits out a error: <InMemoryUploadedFile: image.jpg (image/jpeg)> is not JSON serializable def View1(request): form = FileForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): image = request.FILES.get('image') request.session['image_file'] = image return redirect('View2') def View2(request): img_string = request.session.get('image_file') -
What SQL query should I write to copy two dimensional data into table?
I'm new to SQL and trying to solve this problem. I want to copy this table (attached pic) into the database from csv file. I have created three tables: YEAR Table: I have already inserted years 2014, 2015 and 2016 in it. COMPANY Table: I created two companies 'Alpha' and 'Bravo' in it. FINANCIAL_DATA Table: I have created the revenue and costs categories with Decimal Fields and have put two Foreign Keys one for YEAR table and other for COMPANY table. This data relates to one of the company say 'Alpha' company. What SQL query should I write to copy this data into the FINANCIAL_DATA table? I'm just guessing it will be something like: COPY financial_data (2014, 2015, 2015) FROM '/Desktop/financial_data.csv' DELIMITER ',' CSV HEADER WHERE I'm not sure what statement should I write for condition WHERE. Can you please also confirm if my use of Foreignkey is correct in this case or should I use ManyToMany key or anything else? Really appreciate your help. -
Graphene-Django Filenaming Conventions
I'm rebuilding a former Django REST API project as a GraphQL one. I now have queries & mutations working properly. Most of my learning came from looking at existing Graphene-Django & Graphene-Python code samples. There seem to be a lot of inconsistencies amongst them. In some it was suggested that the GraphQL queries should be placed in schema.py whereas the mutations should be placed in mutation.py. What I'm thinking makes more sense is to instead have these two files hold their respective code: - queries.py - mutations.py I'm relatively new to Django & Python though so want to be sure that I'm not violating any conventions. Interested in your thoughts! Robert -
About developping a web based GUI of a simple hydrological simulation tool
I am developing a web based GUI for a modelling software. I have already done the source code of it with python 2.7 in an object-oriented way. It runs correctly in a shell. Then the second part comes: I need to make it as a web app. My supervisors recommended me to use Django. I am new to use Django and web development. I have just used ruby and rails to develop a personal blog before. My questions are: The web app will allow users to input parameters (par and config, dictionaries). And data is a list of dictionaries generated from a csv file uploaded by user. The program will run when users press a button. But I don't know if I have to create Django models in database for my classes below. Because I only need to run the program with these information, and the website will be open access so everybody can use without authentication. Can I just let the server play with the user in a session where the input and output are all stored in RAM ? If the first question not feasible, I found that dictionaries can be converted into textField to be stored in … -
Register button not working in registration_form.html django
I've been following the How to Django 1.9 tutorials and I came across a problem. My registration_form.html has been working properly ever since installment but after adding bootstrap to the template, the registration button has no action. This is the registration_form.html without the bootstrap {% extends "rango/base.html" %} {% block body_block %} <h1>Register Here</h1> <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> {% endblock %} This is the registration_template with the bootstrap {% extends 'rango/base.html' %} {% block body_block %} <link href="http://v4-alpha.getbootstrap.com/examples/signin/signin.css" rel="stylesheet"> <div class="jumbotron"> <h1 class="display-5">Register</h1> </div> <form role="form" method='post' action='.'> {% csrf_token %} <div class="form-group"> <p class="required"><label class="required" for="id_username">Username:</label> <input class="form-control" id="id_username" maxlength="30" name="username" type="text" /> <span class="helptext"> Required. 30 charachters or fewer. Letters, digits and @/./+/-/_ only. </span> </p> <p class="required"><label class="required" for="id_email">Email:</label> <input class="form-control" id="id_email" name="email" type="email"/> </p> <p class="required"><label class="required" for="id_password1">Password:</label> <input class="form-control" id="id_password1" name="password1" type="password"/> </p> <p class="required"><label class="required" for="id_password2">Password Confirmation:</label> <input class="form-control" id="id_password2" name="password2" type="password" /> </p> </div> <button type="submit" class="btn btn-primary" value='Submit'>Submit</button> </form> <p> Already a member? <a href="{% url 'auth_login' %}">Log In Here!</a> </p> {% endblock %} Thanks in advance :) -
How can I make categories in a image gallery in Django
Hi I'm a graphic designer and very new in programing, I've been learning Python for a while and wanna try something with Django, I'm making my website with Django just for fun and practice and I made this image gallery following some tutorials, but I want to add categorization to the images so in my website I can call some images by categorization and not showing up all the images at once. How can I do that? MODELS.PY from __future__ import unicode_literals from django.db import models # Create your models here. class Photo(models.Model): title = models.CharField(max_length = 200) width = models.IntegerField(default = 0) height = models.IntegerField(default = 0) image = models.ImageField(null= False, blank = False, width_field="width", height_field="height") timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) def __unicode__(self): return self.title class Meta: ordering = ["-timestamp"] VIEWS.PY from django.shortcuts import render, redirect from django.http import HttpResponse from apps.photos.models import Photo # Create your views here. def photo_list(request): queryset = Photo.objects.all() context = { "photos": queryset, } return render(request, 'photos/photos.html', context) PHOTOS.HTML {% extends 'base/base.html' %} {% block contenido %} <br> <br> {% for photo in photos %} <h1>{{ photo.title }}</h1> {% if photo.image %} <img src="{{ photo.image.url }}" class="img-responsive"> {% endif %} … -
Django: populate the field based on previous field value - missing the last step ti make it work
Like many, I want to populate a field in a django form based on what is selected in another field. I've read alot of answers with javascript(I struggle in javscript, so that's where I'm having trouble with the exemples), and I almost got it working, but the last step(updating the field itself) isn't working so I'd love some help with that part. Here are the 2 fields. The first fieldthat gets populated from a query and is located in a div named #merch in the form merchandise = forms.ModelChoiceField(label='Merchandise', queryset=Merchandise.objects.all(), merch_price = forms.DecimalField(label='Price', min_value=0, max_value=800, initial='0.00',decimal_places = 2, max_digits=10) Upon selection, the second field(div named #price) should then display the price based on the merchandise selected. I created the view for the ajax request: def check_item_price(request): if request.method == "GET": item = request.GET.get('item', '0')#the zero as default doesn't seem to work. To verify price = Merchandise.objects.get(id = item) return JsonResponse(price.item_price, safe=False)#is it safe to turn safe off? and the url url(r'^_item_price', views.check_item_price, name='_item_price' ) Calling the url manually works great, it returns the price in json format And here is the javascript that is in the html form. The first part works, upon change it calls the url and a … -
Wrong results when using two annotate expressions concurrently
Assume the following tables: class Table1(models.Model): #Merchandise Column1 = models.IntegerField() class Table2(models.Model): #PurchaseInvoice Column2 = models.IntegerField() class Table3(models.Model): #PurchaseInvoiceItem Table1 = models.ForeignKey(Table1, null=False, on_delete=models.CASCADE) Table2 = models.ForeignKey(Table2, null=False, on_delete=models.CASCADE) Column3 = models.IntegerField() class Table4(models.Model): #warehouseinputoutput Table1 = models.ForeignKey(Table1, null=False, on_delete=models.CASCADE) Table3 = models.ForeignKey(Table3, null=False, on_delete=models.CASCADE) Column4 = models.IntegerField() This annotate expression returns right answer: print(Table1.objects.annotate(Exp1=Sum( Case( When(table3__Table2__Column2__in=[2, 3], then=F('table3__Column3')), default=Value(0) ), )).values('Exp1')) That is: <QuerySet [{'Exp1': 96}]> And I need to define another annotate expression as below: print(Table1.objects.annotate(Exp2=Sum( Case( When(table4__Table3__Table2__Column2=3, then=F('table4__Column4')), default=Value(0) ), )).values('Exp2')) Again the result is correct: <QuerySet [{'Exp2': 0}]> Finally, I want to combine these two in one command: print(Table1.objects.annotate(Exp1=Sum( Case( When(table3__Table2__Column2__in=[2, 3], then=F('table3__Column3')), default=Value(0) ), ), Exp2=Sum( Case( When(table4__Table3__Table2__Column2=3, then=F('table4__Column4')), default=Value(0) ), )).values('Exp1', 'Exp2')) But unfortunately the result is not correct: <QuerySet [{'Exp2': 0, 'Exp1': 480}]> -
How to create a link between users so they are friends on a social network? [on hold]
I'm learning Web development using Python and Django. I'm creating a social network where users can become friends and are able to see each other's posts on their separate news feeds and interact like in Facebook, for instance. Essentially, I'd like to know how the participating users of my website can become friends, based on the Python code I'd have to write to create that link. -
Enabling a selection element only when two other selections have been made
This is my html: <div> <select name="State" class="state"> <option value="Z">Select a state</option> </select> <select name="City" class="city"> <option value="Z">Select a city</option> </select> <select name="Building" class="to" disabled="true"> <option value="Z">Select a Building</option> </select> </div> <div> <select name="State" class="state"> <option value="Z">Select a state</option> </select> <select name="City" class="city"> <option value="Z">Select a city</option> </select> <select name="Building" class="to" disabled="true"> <option value="Z">Select a Building</option> </select> </div> Desired behaviour: A jquery call is made to a django backend to find the possible selection choices for building, only when non-Z value is selected for both state and city. There are multiple (unknown number) of state, city, building selection sets. Here is what I am contemplating in pseudo code. One difficulty I have is if a .state or .city has change, how do you find the value for the corresponding .city or .state within the same . $(document).ready(function() { $('form').on("change", ".state, .city", function(){ [pseudo] if $(this) is not Z AND adjacent (state or city) is not Z fetch building options in the backend [end pseudo] } }) }); -
Django Messages, How to Hide Specific Ones
I am using Django's messages framework to indicate successful actions and failed actions. How can I exclude account sign in and sign out messages? Currently, landing on a page after signing in displays " Successfully signed in as 'username'". I do not want this message to be displayed, but all other success messages should be displayed. What I attempted is shown below. I tried using logic to find if the message had the word "signed" in it. If it did, do not display it. That however is not working though. {% if messages %} <div class="db-section"> <ul class="messages"> {% for message in messages %} {% if "signed" in message %} # Don't display anything {% else %} <div class="alert alert-error"> <strong style="color:{% if 'success' in message.tags %}green{% else %} red {% endif %};padding-bottom:10px;">{{ message }}</strong> </div> {% endif %} {% endfor %} </ul> </div> {% endif %} Could someone possibly explain why the above code is still displaying messages that even contain "signed" in it? -
Libraries needed to Use Spark from Python (PySpark)
I am using PySpark from Django and connect to a spark master node using SparkSession to execute a job on the cluster. My question is do I need a full install of spark on my local machine? All the documentation has me install spark and then add the PySpark libraries to the python path. I don't believe I need all ~500mb of that to connect to an existing cluster. I'm trying to lighten my docker containers. Thanks for the help.