Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript syntax error in Django Template when variable value is missing
I have a Django template with an AJAX menu (where clicking on different menu items reloads a part of the page). Each menu click invokes a Django view function through AJAX and returns some data to be shown on the page. I am loading all the JS required for all the menu items in the main page only (as I learnt that it is not a good idea for AJAX to return JS in a and then use eval() to execute it). Since I am loading all the JS on the menu's main page only, the data obviously isn't there for other menu options at start since it will come later when the corresponding view is invoked (when the menu option is clicked) Because of that, code like the one below gives a syntax error on the console since JS is parsed the very first time only. <script> var data = {{se_data|safe}}; </script> Now I am not able to use the data returned from the view, even after I click the menu options, since the JS parsing failed in the first place. I tried using if to execute the code only when the corresponding menu option is selected but that … -
Difference between using url tag and get_absolute_url
If I have a model like this: class Article(models.Model): title = models.CharField(max_length=200) # ... rest of the code ... def get_absolute_url(self): return reverse('article-detail', args=[str(self.pk)]) and I have an url mapping like this: url(r'^article/(?P<pk>[0-9]+)/$', views.ArticleView.as_view(), name='article-detail'), In template should I use: <a href="{{ article.get_absolute_url }}">{{ article.title }}</a> or <a href="{% url 'article-detail' article.pk %}">{{ article.title }}</a> I'm still thinking both are good ideas, but which is the best? In the first code I've written args=[str(self.pk)], why I must convert self.pk into string? URLs must be strings? In my generic view, how do I use pk variable? I'm really confused with that slug_field, slug_url_kwarg, pk_url_kwarg, query_pk_and_slug. Which matches which? If I set query_pk_and_slug to True, slug_field = pk? -
Django Admin escaping text
I recently upgraded Django from 1.3 to 1.8.18 and been having issues with links custom made to pre-fill forms in Django admin. For example, I have the following link: /admin/miscellaneous/whatsnew/add/?title=...%20competition%20results%20uploaded&pub_date=21-04-2017&body=&link= When executed the pre-filled data in the form looks like: Where it should look like this: What can I do to resolve this? -
Django psycopg2.OperationalError: fe_sendauth error but not connecting to postgresql database
I am using the following sqlite connection in my myapp/settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':testdb:', #I also tried 'NAME': 'testdb', }, } in my manage.py file I am using: if __name__ == "__main__": os.environ.setdefault("myapp.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) On running ./manage.py migrate on the command line I get the following error: django.db.utils.OperationalError: fe_sendauth: no password supplied I tried removing psycopg2 and re-ran the migration and get the following error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' I can't work out why django is trying to connect to a psql database where the only DATABSES configuration in the application is for sqlite3. Could this be due to a dependency? -
Use multiple models in a single django form
I have a django application and for a particular form,the data comes from different models with one common field(id) across all models.Instead of using multiple forms and same id for all forms,I want to use a single form to take data from multiple models.How can this be done? -
call Rest Api from Django admin form
My model has 2 values.One is url and other one is price.When creating a new object via django admin i want when i input url in input field,a request should be sent to that specific url and fetched the updated price for the field and populate it.Any help in this matter is highly appreciated Thanks -
Error: object of type 'zip' has no len() after adding extra header by using zip
I try to follow this link pandas dataframe with 2-rows header and export to csv in order for me to created extra header without remove the original header, below is my coding: df.columns = pd.MultiIndex.from_tuples((zip(df.columns,[uniquevaluesfirstcolumnww, '', uniquevaluesfirstcolumnww1, ' ',uniquevaluesfirstcolumnww2, ' ']))) I get the error such as this: object of type 'zip' has no len() Anyone have any idea? even though I try to add list before zip but fail also. -
Django ORM Join Query Issue
pp.pprint(AppUser.objects.filter(directory__user_id=F('id')).query.str()) ('SELECT "users_appuser"."id", "users_appuser"."password", ' '"users_appuser"."last_login", "users_appuser"."is_superuser", ' '"users_appuser"."username", "users_appuser"."first_name", ' '"users_appuser"."last_name", "users_appuser"."email", ' '"users_appuser"."is_staff", "users_appuser"."is_active", ' '"users_appuser"."date_joined", "users_appuser"."gender", ' '"users_appuser"."age", "users_appuser"."avatar", "users_appuser"."about", ' '"users_appuser"."city", "users_appuser"."state", ' '"users_appuser"."location", "users_appuser"."location_updated", ' '"users_appuser"."online", "users_appuser"."entered_offline", ' '"users_appuser"."notifications", "users_appuser"."checkins", ' '"users_appuser"."lock_expiration" FROM "users_appuser" INNER JOIN ' '"chat_membershiphistory" ON ("users_appuser"."id" = ' '"chat_membershiphistory"."user_id") WHERE ' '"chat_membershiphistory"."user_id" = ("users_appuser"."id")') I need to include all values from chat_membership into the final query this is my Model class class MembershipHistory(TimeStampedModel): Active = "A" Offline = "O" Away = "X" NEVER_JOINED = "N" Locked = "L" _STATUSES = ((Active, 'Active'), (Offline, 'Offline'), (Away, 'Away'), (Locked, 'Locked'), (NEVER_JOINED, 'Never joined')) room = models.ForeignKey('places.Place', related_name='directory') user = models.ForeignKey(AppUser, related_name='directory') lock_expiration = models.DateTimeField(null=True, blank=True, editable=True) type = models.CharField(max_length=1, blank=False, null=False, choices=_STATUSES, default="A") class Meta: ordering = ('room', 'user') unique_together = ('room', 'user') verbose_name = "Member" verbose_name_plural = "Members" If I try select_related I always get the following error Invalid field name(s) given in select_related: 'directory'. Choices are: auth_token -
want to build query in django
I have mysql query, Which i want to change in django framework. I have two tables one is job that contain job data, another one is job_applied table that contain candidate who are applying on jobs, I have fetch number of candidate how many applied on particular job and rejected, onhold and selected on condition base. select job.id, count(job_applied.job_id) as applied_count , sum(case when job_applied.status = 2 then 1 else 0 end) rejected_count, sum(case when job_applied.status = 3 then 1 else 0 end) onhold_count, sum(case when job_applied.status = 1 then 1 else 0 end) selected_count from job left join job_applied on job.id = job_applied.job_id group by job.id Query Result id applied_count rejected_count onhold_count selected_count 124 15 5 6 4 415 10 5 3 2 511 5 3 1 1 115 2 0 2 0 126 7 4 1 2 -
python 3 and django-python3-ldap - user can't login
I am using python 3.6, Django 1.10 and django-python3-ldap with following settings as described in https://github.com/etianen/django-python3-ldap LDAP_AUTH_URL = "ldap://ldap.something.com:389" LDAP_AUTH_USE_TLS = False LDAP_AUTH_SEARCH_BASE = "DC=hello,DC=something,DC=com" LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'django_python3_ldap.auth.LDAPBackend', ) LDAP_AUTH_USER_FIELDS = { "username": "uid", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_openldap" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = None LDAP_AUTH_CONNECTION_USERNAME = None LDAP_AUTH_CONNECTION_PASSWORD = None LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } ldap user cannot login and i see following warnings - i am sure that username and password is correct : LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - 80090308: LdapErr: DSID-0C0903A8, comment: AcceptSecurityContext error, data 52e, v1db1 - bindResponse - None -
How to test a Django app in Pybuilder?
can anyone tell me how to test Django app inside Pybuilder? -
DRF Relate query set with name of other table
I followed suggestion from this question But i need to name one field of query_set to date filed of another object My models are class Choice(models.Model): question = models.ForeignKey(Question, related_name='choice', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class ChoiceWithTime(models.Model): choiceTime = models.ForeignKey(Choice,related_name='choiceTime', on_delete=models.CASCADE) choice_date=models.DateField() My view class QuestionChoicesViewSet(viewsets.ModelViewSet): queryset = Choice.objects.all() serializer_class = ChoiceDateSerializer def get_queryset(self): return Choice.objects.values('choiceTime__choice_date','choice_text').annotate( total_votes=Count('choiceTime__choice_date'), ) I need to count number of submission in particular dates I don't know how to name choiceTime__choice_date that serializer recognizes field in query set class ChoiceDateSerializer(serializers.ModelSerializer): choiceTime__choice_date = serializers.DateTimeField() total_votes = serializers.IntegerField() class Meta: model = Choice fields = ('id', 'choice_text','total_votes','choiceTime__choice_date') i receive { "choice_text": "ant tower", "total_votes": 3, "choiceTime__choice_date": "2017-04-20" } But i want to recieve { "choice_text": "ant tower", "total_votes": 3, "choice_date": "2017-04-20" } Tried different options with no success. Definitely i am missing the point. For my purposes it is working, but i want to have well written API. 2 option change time submission model? class ChoiceWithTime(models.Model): choiceTime = models.ForeignKey(Choice,related_name='choiceTime', on_delete=models.CASCADE) choice_date=models.DateField() coutner = models.IntegerField(default=0) Is 2 option considers to be better approach to my particular problem? -
Loading choices into choicefield - strange behavior
I have a django form with a choicefield, where I dynamically load some choices into the field: class EntryForm(forms.Form): project = forms.ChoiceField() def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(EntryForm, self).__init__( *args, **kwargs) CHOICES2=[] for x in Project.objects.all() : if user in x.users.all(): CHOICES2.append((x.name,x.name)) CHOICES1 = [(x.name,x.name) for x in Project.objects.all()] print CHOICES2==CHOICES1 #this is True in this case self.fields['project']=forms.ChoiceField(choices=CHOICES2) The form is loaded into the template with {{form.as_table}}. The form does not show a dropdown for the project field. Now the strange thing: if I change the last line to: self.fields['project']=forms.ChoiceField(choices=CHOICES1) it works, although the print statement of the "=="" comparison returns True (the lists are purposely the same - this is just for testing). I really have no idea how this can even work technically. -
no module named stevedore
my problem is mkvirtualenv ImportError: No module named stevedore, below is something you might want to read in adv. When I installed virtualenv, i typed sudo pip install virtualenv without using -h flag for sudo command. so bash tells me The directory '/Users/RJ/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/RJ/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. When I installed virtualenvwrapper, i did so with sudo pip install --no-deps virtualenvwrapper (otherwise it wouldn't work) Any help would be appreciated! -
How to hide pk from django url?
how do i hide pk from my URL url(r'^update/(?P<pk>\d+)$', views.update, name='update'), my URL is like **localhost/update/1** i want to hide the pk from my url -
How to get python list from bytes object from urllib3
python 3.6.0 django==1.11 djangorestframework==3.6.2 I have 2 Django server running on my local machine. First server running on 8000 http://localhost:8000/api/branches Second server running on 8080 This server shoot the endpoint and response is a bytes class Here is my request from 2nd server to 1st server forms.py import urllib3 from django import forms from django.conf import settings from apps.factories_pos.models import FactoryPOS http = urllib3.PoolManager() class FactoryPOSForm(forms.ModelForm): class Meta: model = FactoryPOS fields = [ 'branch_name', 'dealer_name', 'shop_name', 'factory', ] def __init__(self): choices = self.get_choices() self.fields['branch_name'] = forms.ChoiceField( choices=choices ) @staticmethod def get_choices(): url = settings.ENEOS_POS_WEB + '/api/branches' response = http.request('GET', url) import pdb; pdb.set_trace() choices = [item.get('name') for item in response.get('results')] return choices Result from debuggin line. (Pdb) response <urllib3.response.HTTPResponse object at 0x106d78a90> (Pdb) dir(response) ['CONTENT_DECODERS', 'REDIRECT_STATUSES', '__abstractmethods__', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_abc_cache', '_abc_negative_cache', '_abc_negative_cache_version', '_abc_registry', '_body', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_connection', '_decode', '_decoder', '_error_catcher', '_flush_decoder', '_fp', '_fp_bytes_read', '_handle_chunk', '_init_decoder', '_init_length', '_original_response', '_pool', '_update_chunk_length', 'chunk_left', 'chunked', 'close', 'closed', 'connection', 'data', 'decode_content', 'enforce_content_length', 'fileno', 'flush', 'from_httplib', 'get_redirect_location', 'getheader', 'getheaders', 'headers', 'isatty', 'length_remaining', 'read', 'read_chunked', 'readable', … -
authenticate always returns None,Django
I want to add the authentication functionality in my application. I have below code snippet: user = User.objects.create_user('jkd') user.set_password('space') user.save user = authenticate(username='jkd', password='space') print "User:",user It always prints the "User:None". I have also added below in my settings.py file: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # default # any other authentication backends ) I have gone through answers of same question in different thread but it doesn't help me. -
Django, view get list of dictionaries from request
I have an AJAX request call (with JQuery) to my django view. It sends to view this kind of data: {"cityId": 1, "products_with_priority": [{"id": 1, "priority": 1}, {"id": 2, "priority": 2}, {"id": 3, "priority": 3}, {"id": 4, "priority": 4}, {"id": 5, "priority": 5}]} In my django view, I'm trying to get this list like this: def my_view(request): city_id = request.POST.get('city_id') products_priorities = request.POST.getlist("products_with_priority") Where city_id returns 1 and products_with_priority returns empty array. How it is possible to receive array of dictionaries from request? -
model shows last for loop image
Hey guys I was just wondering how come in my for loop my images show up each time on the page but in my pop out model it shows the last image the for loop gave out for each model. I even tried to make a different html which shows the details of the full view to see what picture it shows and it still shows the last image the for loop gave, which is the last image that gets posted up. {% extends 'navbar.html'%} {% load staticfiles%} {% block styles %} <link rel="stylesheet" type="text/css" href="{% static 'css/accounts/profile.css' %}" /> {% endblock %} {% block content %} <div class="row"> <div class="col-lg-4 col-md-6 col-xs-12" style="background-color:red"> <h1>Profile of {{user}}</h1> </div> <div class="col-lg-4 col-md-6 col-xs-12"> {% for post in posts%} <div class="thumbnail" style="background-color: yellow"> <img src="{{post.image.url}}" class="image" data-toggle="modal" data-target="#myModal"> <div class="middle"> <div class="text">{{post.title}}</div> </div> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h1 class="modal-title" id="myModalLabel"><a href="{% url 'posts:detail' post.slug%}">{{post.title}}</a></h1> <h6>Posted: {{ post.pub_date| timesince}}</h6> by <a href="{% url 'posts:userpost' post.author.id%}">{{post.author.username}}</a> </div> <div class="modal-body"> <div class="thumbnail"> <img src="{{post.image.url}}" class="image" data-toggle="modal" data-target="#myModal"> </div> <p>{{post.description|linebreaks|truncatechars:120}}</p> <p><a href="{% url 'posts:detail' post.slug%}" class="btn btn-primary" role="button">View</a></p> </div> … -
Django: How to Convert QuerySet into String
I'm using Python 3 and trying to convert a QuerySet into human-readable text. I have a line like this: top_post = Post.objects.filter(category='1')[:1] That prints like this: <QuerySet [<Post: Test Post 1>]> What makes me scratch my head is a similar QuerySet successfully converts when displayed via a template: latest = Post.objects.order_by('-published_date')[:5] "Latest" uses a for...loop in the template: {% for latest_posts in latest %} <h1>{{ latest_posts }}</h1> While "top_post" displays only a blank: <h1>{{ top_post }}</h1> Anyone see what's missing? -
uploading camera data to django filefield
I am trying to build a simple app that would allow user to capture his/her image using a webcam and pass it to django clicking 'Submit' button. I use https://amw.github.io/jpeg_camera/ jQuery package to capture the photo (but I guess, any other would also work). And I pass the model field ImageField (I believe I could also use FileField). my_image = django_models.ImageField(upload_to = 'pic_folder/') The problem is that I can't figure out how to convert the data from jQuery capture (which is a blob) to a input of the form, so it can be transmitted as file and saved by Django. What should I do? -
Multiple instances in one form
Trying to implement poll-creating system, where I can create questions with choices (previously I did this all in the admin, and had to create an individual choice object for every choice) Here's my models: class Question(models.Model): has_answered = models.ManyToManyField(User, through="Vote") question_text = models.CharField(max_length=80) date = models.DateTimeField(auto_now=True) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=100) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text So right now here's the template: <form method="post" action="">{% csrf_token %} {{ question_form.question_text }} <br><br> <!--{{ choice_form.choice_text|placeholder:"Choice" }}--> <input class="choice" name="choice_text" placeholder="Choice" type="text" /> <input class="choice" name="choice_text" placeholder="Choice" type="text" /> <input class="choice" name="choice_text" placeholder="Choice" type="text" /> <img src="{% static 'images/plus.png' %}" class="add_choice" /> <br> <button class="submit" type="submit">Create question</button> </form> As you can see I'm not sure whether using multiple {{ choice_form.choice_text|placeholder:"Choice" }} is possible. So I paste multiple input fields and tried to get all of them by using getList(). However I get this error: 'QueryDict' object has no attribute 'getList' Any idea why? Here's my views: def questions(request): question_form = QuestionForm(request.POST or None) choice_form = ChoiceForm(request.POST or None) if request.POST: choice = request.POST.getList('choice_text') print(choice) if request.user.is_authenticated(): if question_form.is_valid(): print('valid question') #question = question_form.save(commit=False) return render(request, 'questions.html', {'question_form': question_form, 'choice_form': choice_form}) So how exactly … -
The view blog.views.post_list didn't return an HttpResponse object. It returned None instead
I cant fix this Help!!!!! The view blog.views.post_list didn't return an HttpResponse object. It returned None instead. from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Post def post_list(request): object_list = Post.published.all() paginator = Paginator(object_list, 3) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) -
Using the Django admin for the Admin website
We have a project in which we have to use 3 different backend frameworks/programming language and integrate them together to form one correlated website: Java(Spring MVC) for the customer end website, PHP(CodeIgniter) for the service provider website, and Python(Django) for the admin site. My question is, can I use the admin site of Django alone? I will only use it for accepting user registrations, deactivation, and tracking transactions. So it's all just going to be basic CRUD functions for the database. Or is there an alternative framework for me to use? Thank you. -
Domain Masking & Allowed Host Issue in Django
I am having an issue with Domain Name masking. Let's say my domain name is www.example.com & my client's domain name is www.client1.com. We are a SaaS business & the client wants domain name masking. We are doing the masking from domain registrar companies (eg: GoDaddy). My doubt is, do we need to have the client's domain name in the allowed_host list as well? If that is the case, can the allowed host list be dynamically filled from DB? And even better, can we re-write the get_host() function, so that somehow the django app would know that www.client1.com is actually a mask of www.example.com?