Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - modify css in result list item
I have simple result list in my admin panel. For example it is something like that: id name description category In my admin panel there is result list with classes "row1", "row2". I would like to add another class depending of obj value (obj.group_id which is not listed). I mean: if obj.group_id == 2: add class "premium" to result list item # whole row with this item I would like to simply distinguish some rows in my django admin panel. I don't have any idea how can I achieve that. Any clues? -
django admin cascade dropdownlist
model.py class CaseTitle(BaseModel): Description = models.CharField(max_length=500) def __str__(self): return self.Description class CaseCategory(BaseModel): Description = models.CharField(max_length=500) CaseTitle = models.ManyToManyField(CaseTitle) my scenario is when select casetitle dropdown, CaseCategory must be fill according to CaseTitleID -
Can I use the python object directly in template?
in the views.py I pass the data to the template: data = { "net_title":"private", "server_data":OneObject, } return render(request, "index.html", {"data":data}) In the index.html template, I want to use the data.net_title as the key to get value. I don't know whether it is feasible: {{ data.server_data.THE_NET_TITLE }} # THE_NET_TITLE should be `data.net_title`. Can realize this requirement? -
How can I run a background-task in django and when it's done, I can push information to front end.
Since one of my tasks in views.py is time-consuming, so I think I'd better put it in the background. But also, I want to make sure when this task finished, I'll receive something in the front end. How can I achieve this? I've searched and found django-channels, but still, I can't combine the two goals together. Hope someone will help me. -
defining multiple variabless within a form issue
Hi guys I have something that I do not know how to make it work. I am working on a questionnaire like, where on a page will show up the questionn and a radio like form list of answers that the user can select. I gave it a try but I do not know how to link a question to my form, could you please help ? models.py: from django.db import models # Create your models here. class Questionnaire(models.Model): question = models.CharField(max_length=600) multiple_answer = models.BooleanField(default=False) def __str__(self): return self.question class Answers(models.Model): question_id = models.ForeignKey('Questionnaire', on_delete=models.CASCADE) answer = models.CharField(max_length = 600) def __str__(self): return self.answer class Test(models.Model): user = models.ForeignKey('registration.MyUser') created_at = models.TimeField(auto_now_add=True) closed = models.BooleanField(default=False) class UserAnswer(models.Model): test_id = models.ForeignKey('Test') question = models.ForeignKey('Questionnaire') answer = models.ForeignKey('Answers') views.py: def AnswerChoiceSelect(request): #import pdb; pdb.set_trace() if request.method == "POST": answer_form = QuestionChoices(request.POST) if answer_form.is_valid(): print("working") else: print('Non Valid form') else: answer_form = QuestionChoices(request.user) return render(request,'question_template.html', {'answer_form':answer_form }) forms.py: from django import forms from django.contrib.auth.models import User from registration.models import MyUser from .models import Questionnaire, Answers, Test, UserAnswer from django.contrib.auth import get_user_model User = get_user_model() class QuestionChoices(forms.Form): question_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None) def __init__(self,questionnaire, *args, **kwargs): super(QuestionChoices, self).__init__(*args, **kwargs) current_question = Questionnaire.objects.get(id = question_id) self.fields['question_choice'].queryset … -
Uncaught TypeError: Cannot set property 'onclick' of null- I moved the script upper now code
I got an error,Uncaught TypeError: Cannot set property 'onclick' of null. I wrote <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> //this code let key = "prop"; let value = "value"; document.querySelector("input[type=button]").onclick = e => { const test = window.open(`test.html?${key}=${value}`, "_blank"); console.log(test); } </script> </body> I moved up codes within script tag in the place is under body tag to solve this error, but same error happens.How can I fix this? -
design pattern for masking group of objects as one
I'm working on a simple messaging app using Django. here is a problem I encountered. I want users to be able to send message to a group of other users. I also want to show the last sent and received messages for each user. the problem is when you send out a message to a lot of people. your messages Interface will be filled with the same message (one for each receiver). what I want to do is have the same UI as group messaging in smartphones meaning all the messages in a group message will be shown as one unless someone answers the message in which case a new conversation will be displayed for that user. I don't want to create a new model (class) for group messages and it would be inefficient to manage this in front end level. is there any design pattern that helps me do this? how can I do this without iterating over all the messages and finding the ones that belong to the same group? thanks in advance. what I have now: message for person 1: hi message for person 2: hi message for person 3: hi message for person 4: hi message … -
Deploying django app in google cloud
I am looking for a good tutorial for deploying django app to google cloud. Do you have any recommendations? I have tried this https://cloud.google.com/python/django/flexible-environment#setting_up_your_local_environment But I am stuck in this part. I used this command: ./cloud_sql_proxy -instances="[YOUR_INSTANCE_CONNECTION_NAME]"=tcp:5432 And the output is the screenshot below. It's taking to forever or is it normal? ; Since I was stuck in it. I proceeded to the next steps which is creating a new sql database and new user and password in google cloud. Then proceeded to the 'Configure the database settings', then 'Running app on local computer'. Now, I also have errors when I run: python manage.py migrate Error: So, I proceeded again to next steps. By modifying the settings.py and app.yaml. Then, errors occurred like invalid google cloud sql name I know it was not a good thing proceeding to the next steps without fixing first the first encountered errors, but it was taking me too long to wait like 2 hours. -
Can I use the python object directly in template?
In my views.py I get the bellow Object(openstack.compute.v2.server.ServerDetail): openstack.compute.v2.server.ServerDetail( OS-EXT-STS:task_state=None, addresses={u'private': [{u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:08:bf:54', u'version': 4, u'addr': u'192.168.1.8', u'OS-EXT-IPS:type': u'fixed'}, {u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:08:bf:54', u'version': 4, u'addr': u'103.35.202.3', u'OS-EXT-IPS:type': u'floating'}]}, links=[{u'href': u'http://controller:8774/v2.1/99a50773b170406b8902227118bb72bf/servers/d0ba93a8-952f-4c7f-a439-d4722c4100f8', u'rel': u'self'}, {u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/servers/d0ba93a8-952f-4c7f-a439-d4722c4100f8', u'rel': u'bookmark'}], image={u'id': u'ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/images/ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'rel': u'bookmark'}]}, OS-EXT-STS:vm_state=active, OS-EXT-SRV-ATTR:instance_name=instance-0000003a, OS-SRV-USG:launched_at=2017-09-28T07:20:57.000000, flavor={u'id': u'1', u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/flavors/1', u'rel': u'bookmark'}]}, id=d0ba93a8-952f-4c7f-a439-d4722c4100f8, security_groups=[{u'name': u'default'}], user_id=fb52853bde3d4d3e8e831749781f8671, OS-DCF:diskConfig=MANUAL, accessIPv4=, accessIPv6=, progress=0, OS-EXT-STS:power_state=1, OS-EXT-AZ:availability_zone=nova, metadata={}, status=ACTIVE, updated=2017-09-28T07:20:58Z, hostId=76f61a58cf6d411a30e3e34da4dd252a03aa0093d9dd19c653b234b3, OS-SRV-USG:terminated_at=None, key_name=None, OS-EXT-SRV-ATTR:hypervisor_hostname=controller, name=liao01, created=2017-09-28T07:20:44Z, tenant_id=99a50773b170406b8902227118bb72bf, os-extended-volumes:volumes_attached=[], config_drive=) I make it as a list(server_list) to pass to the template, can I use the object directly in the template? I tried bellow method, but can not get the values. {% for server in server_list %} {{server.name}} .... {% endfor %} But can not get the server.name. -
Django oscar uk and uk_UA translations
I have faced with such weird problem: I use django-oscar in my project. And need to translate the site to Ukrainian. There are two translation files in django-oscar core: uk and uk_UA. But the difference is that there are not all translated strings in uk_UA: https://github.com/django-oscar/django-oscar/blob/master/src/oscar/locale/uk/LC_MESSAGES/django.po#L4759 - uk strings and https://github.com/django-oscar/django-oscar/blob/master/src/oscar/locale/uk_UA/LC_MESSAGES/django.po#L4763 - uk_UA My django project determines to use a uk_UA file and there are not needed for my translations. I need a uk... My django settings: LANGUAGE_CODE = 'ru' LANGUAGES = [ ('ru', _('Russian')), ('uk', _('Ukrainian')), ] USE_I18N = True USE_L10N = True LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),) PARLER_LANGUAGES = { None: ( {'code': 'ru',}, {'code': 'uk',}, ), 'default': { 'fallback': 'uk', 'hide_untranslated': False, } } Why django select uk_UA but not uk files? How to fix it? I mean to choose uk files. Why there are not translations in django-oscar files? Thanks a lot! -
Error getting route from urls.py
I'm testing the application. It is necessary to test the method of processing requests coming to the address 'http://127.0.0.1:8000/api/v1/test/api_address/'. Tell me, please, as through reverse () the full address to the client class MyTestCase(APITestCase): def setUp(self): self.message = { 'username': 'user_name', 'password': 'user_password', } def test_get_token(self): response = self.client.post(reverse('api_address'), self.message) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Code for urls.py: users_router = DefaultRouter() users_router.register(r'test', TestViewSet, 'test') users_router.register(r'test/api_address', APIAddressRequestSet, 'api_address') with the current implementation, reverse ('map address') does not work, falling with an error: django.urls.exceptions.NoReverseMatch -
How can I send user ID in Angular using both REST API and websockets
I am going to create chatbot using websockets. Each user can have their own account. I have Django backend and frontend written in Angular. I am not sure how can I send my user_id from frontend to backend, because I use in my project both Django Rest Framework and websockets, so it seems to me that frontend has to authenticate user both using websockets and REST and has to know that it is the same one user. However it seems to me that it is impossible to have one common authentication for REST and websockets. This is example JSON data that my backend has to receive: { "user_id":2, "message":"My message" } Any ideas how can I solve it? This is part of my Angular component: export class HomeComponent { response: string; response2: string; constructor( private chatService: ChatService, private router: Router, private http: Http, ) { chatService.messages.subscribe(msg => { this.response = msg.message; console.log("Response from backend: " + msg.message); }); } private message = { message: 'this is a test message' } sendMsg() { console.log('new message from client to websocket: ', this.message); this.chatService.messages.next(this.message); return this.message.message; } send(msg) { this.message.message = msg; this.sendMsg(); } login() { return this.http.get('/data', ) .map(response => response.json()) .subscribe(response2 … -
Django preventing the loading of django-compressor if DEBUG is True
I am using django-compressor with a remote site on an Ubuntu server. In my local environment, I'm on Windows, where django-compressor doesn't work. Therefore I can't load django-compressor in my installed apps in my development settings (I have a settings folder with a base.py with dev.py and prod.py inheriting from that). The problem is in my base.html template where I need to load the compress module {% load compress %} at the top of the document, and of course compress my css and js files accordingly. Clearly this doesn't work on my local environment, with DEBUG set to True because the app can't exist in my installed apps. What I am trying to do is prevent this app being loaded dependent on the value of settings.DEBUG. I have tried an assignment tag which returns settings.DEBUG but that doesn't work. Is this possible to achieve? Many thanks in advance. -
Using Django with Redis and Backgroundworker, Architectur Explain
I found this Example https://medium.com/@johngrant/raspberry-pi-and-django-channels-8d5cddb36226 I want to understand the system architecture. How is the connection between BackgroundWorker and Redis and how is the connection between Webserver and Redis in context with websocket. I draw a picture about the architecture. But im nut sure about it. Click here for architecture -
django-python3-ldap LDAPInvalidCredential error
I don't know if I'm doing it right, because i'm fairly new to LDAP and django. Here's my settings file: # The URL of the LDAP server. LDAP_AUTH_URL = "url" # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "OU=someOU,DC=someDC,DC=someDC,DC=net" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } # A tuple of django model fields used to uniquely identify a user. LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) # Path to a callable that takes a dict of {ldap_field_name: value}, # returning a list of [ldap_search_filter]. The search filters will then be AND'd # together when creating the final search filter. LDAP_AUTH_FORMAT_SEARCH_FILTERS = "app.views.search_filter" Again, I dont know if this is the right thing, but I have a LDAP working code(Python 2.7 and non Django) for reference, If you could look at that and tell me where I should make changes for making the Error go away, that would be very helpful, The below Code is what I did to make ldap authentication in python2.7 work, seeing below, the package:- django-python3-ldap is very confusing to me. username=data['username'].value username=username+"@somecompany.net" password=data['password'].value ldap_server="url" base_dn="OU=someOU,DC=someDC,DC=someDC,DC=net" connect=ldap.open(ldap_server) connect.bind_s(username,password) search_filter="uid="+username … -
the loop does not iterate on factory boy class
I'm using factory boy for the testing my user (Customer). I have created class UserFactoryCustomer for my customer User. # factories.py class UserFactoryCustomer(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ('first_name', 'last_name', 'username', 'email', 'user_type', 'balance') first_name = 'Ahmed' last_name = 'Asadov' username = factory.LazyAttribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower()) user_type = 1 balance = 10000.00 # test_serializers.py class ApiSerilizerTestCase(TestCase): def test_get_status_code_200(self): customers = factories.UserFactoryExecutor.objects.all() for customer in customers: self.assertEqual(customer.get('username').status_code, 200) I'm getting this mistake Creating test database for alias 'default'... System check identified no issues (0 silenced). ..E ====================================================================== ERROR: test_get_status_code_200 (tests.test_serializers.ApiSerilizerTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/heartprogrammer/Desktop/freelance-with-api/freelance/tests/test_serializers.py", line 20, in test_get_status_code_200 customers = factories.UserFactoryExecutor.objects.all() AttributeError: type object 'UserFactoryExecutor' has no attribute 'objects' ---------------------------------------------------------------------- Ran 3 tests in 0.246s FAILED (errors=1) I want to bring all my customers who are in the class and UserFactoryCustomer to test them -
Django sub-packages in django Admin
I have a project that I need to split in multiple sections that have a commune denominator. So, I do something similar to Django: INSTALLED_APPS = ( ... 'section1.subapp1', 'section2.subapp2', 'section2.subapp1', 'section2.subapp2', ... ) For example I have a social media section with twitter app, linkedin app, facebook app etc. My question is how I group this apps also as section in Django Admin and not as separate apps ? (for example Social media Panel) -
Compiled Sass files not found by Django-pipeline
I'm having trouble with running django-pipeline because I keep receiving errors similar to: ValueError: The file 'css/main.b7ade0b8392c.css' could not be found with <pipeline.storage.PipelineCachedStorage object at 0x7f66c22ef550>. When I perform an ls operation in my css folder, the css file that is present is called main.c2b6ea9fa0e1.css, which is different from the file that django-pipline is looking for. My django-pipeline configuration looks like this: PIPELINE = { 'PIPELINE_ENABLED': True, 'STYLESHEETS': { 'main': { 'source_filenames': ( 'css/main.scss', ), 'output_filename': 'css/main.css' }, 'COMPILERS': ( 'pipeline.compilers.sass.SASSCompiler', ), 'CSS_COMPRESSOR': 'pipeline.compressors.NoopCompressor', 'JS_COMPRESSOR': 'pipeline.compressors.NoopCompressor' } This problem only seems to be happening when I have DEBUG=False. I try to perform python manage.py collectserver before restarting the Apache server, but to no avail. I'm using Apache, Django 1.9.9, Python 2.7. -
How can I send form data to test.html by using asynchronous communication?
I wanna send form data to test.html by using asynchronous communication. I wrote in index.html <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> $('[name=type]').change(function() { var array1 = []; var array2 =[]; $('[name=main] option:selected').each(function() { array1 = $(this).text(); console.log(array1); }); $('[name=type] option:selected').each(function() { array2 = $(this).text(); console.log(array2); }); }); $.ajax({ url: 'test.html', dataType: 'html', timeout:3000, async: true, success: function(html) { $('.newsarea').html(html).fadeIn(5000); }, error: function() { alert('Error'); } }); </script> </body> I wanna send selected i & value's variables to test.html.Now when I put send button,nothing is shown in test.html. I wrote test.html like <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RESULT</title> </head> <body> <h2>TOPIC</h2> <div … -
Django: Storing Images Database
Earlier I was using default database sqlite3, but today i've changed it to postgresql. I wants to save the image files in database not in project directory itself. How can I do that? Thank You :) -
Django admin search for multi-word phrase with ^ and = operators
Assume a model admin has: search_fields = ("^name", "=kind") If name is "Leonardo Da Vinci", it can be found using the query Leon or Leonardo, but not Leonardo Da or Leonardo Da Vinci. If kind is e.g. "polymath genius", such a value cannot be found with any query. Ideally, one would be able to post "multiple words" "Leonardo Da" and get this record; but given how Django splits the query, it doesn't do what one might expect. This problem was apparently raised 9 years ago in this ticket, and solved. Then Django got rewritten and apparently this got dropped somewhere. Does anyone have an idea if this is possible? I'm probably thinking I'd need to override ModelAdmin.get_search_results... Anything more elegant? -
Need help in understand Django-Facebook API and the Post extraction form a profile suing Python2
I am working on my machine learning project where I am in a great need to access the textual posts of the people from Facebook, of course with permission, and then process it to find the best personality traits. I am struggling to find a way to merge my application with something that can give me the post of the people from their profiles. Hence, I found something in the documentation of the Django-Facebook API. Here is the link for the documentation: http://django-facebook.readthedocs.io/en/latest/installation.html Here what I am not able to understand is how I can use this for extracting the post of the people? Can anyone give a small example that can be helpful in understanding what I can do to extract the text from the people profile and use it in my application. -
GAE: ImportError while using google-auth
I am using google-auth to allow firebase authentication in my GAE project. Everything works fine when I run the code locally using dev_appserver.py or when I deploy it to google app engine. But I get this ImportError exceptions when I try to use Django's manage.py script to create/run migrations. ```ImportError: Could not import 'firebase.authentication.FirebaseAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: No module named auth.transport.requests. The google-auth module is installed under lib directory and has this structure: - lib - google - auth - oauth2 These import cause the ImportErrors: import google.auth.transport.requests from google.oauth2 import id_token My guess is that there might be naming conflicts as other imports work fine. Please help! -
Reverse for 'about' with no arguments not found
So I'm attempting to Django, and I've gotten a few urls working but one set just wont work. It keeps asking for a argument but it shouldn't require one. Error below. NoReverseMatch at / Reverse for 'about' with no arguments not found. 1 pattern(s) tried: ['$about/'] Error during template rendering In template hub\templates\partials\footer.html, error at line 33 hub\templates\partials\footer.html line 33 <a href="{% url 'hub:about' %}" class="nav__link">About</a> hub/urls.py urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='index') ] storyarchive/urls.py urlpatterns = [ url(r'^$', include('hub.urls', namespace='hub')) ] It worked before I started to use the {% url %} builtin. Django Version: 1.11.5 Python Version: 3.4.4 -
how to send data from HTML to python and get the result back to HTML?
I know nothing about the interface between HTML and python so I come here to ask for help hope you guys can help me. HTML are now post on apache server,and I visit this web by the address "http://127.0.0.1/name.html". Here is what I want to achieve: There is a form on HTML getting the data,and by clicking the button "submit",the data should be send to python.exe,and the python.exe runs itself and send the result back to HTML(by poping a new dialog). I searched on the Internet and was wondering will Django help?? Is this even possible?Can anybody help me ?