Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter with OR statement
I need to write filter that will check situation like: if there are an actors with name "John" than return these actors, otherwise search actors with name "David". Pseudocode may look like: Actors.filter(name="John" or name="David") Can i do something like this in Django using one query? or do I have to use if ? actors = Actor.filter(name="John") if not actors.exists(): actors = Actors.filter(name="David") -
How to fetch nested dictionnaries in JSON?
I'm having some trouble understanding why I am not able to fetch some datas in my JSON datas. I'm on Django using JSONField, I'd like to change some specific datas after fetching them. Here's what I wrote : for apple in Apples.objects.filter(json__contains=[{'provenance': 'Spain'}]): for ap in apple.json: for key, value in ap.items(): print(value.color) AttributeError: 'dict' object has no attribute 'color' when I print value I have something like this : {'color': 'red', 'size': '20x20', 'good_till': '01.08.2017'} So I don't understand why the error says that there's no attribute color while there's one ? What am I doing wrong ? -
Two uwsgi django websites on same domain using nginx
I have a django website site1 running on a linux machine. It has the following config: site1_nginx.conf upstream django { server unix:///var/www/site1/site1.sock; } server { listen 80; server_name site.com; charset utf-8; client_max_body_size 75M; location /media { alias /var/www/site1/media; } location /static { alias /var/www/site1/static; } location / { uwsgi_pass django; include /var/www/site1/uwsgi_params; } } site1_uwsgi.ini [uwsgi] chdir = /var/www/site1 module = site1.wsgi home = /var/www/virtualenv/site1 master = true processes = 10 socket = /var/www/site1/site1.sock chmod-socket = 666 vacuum = true It has a domain site.com. I have another django website site2 at hand. It's different, has a different virtualenv. I can't add it to the existing website as an app or via django routing. I want the sites to not be related, so that they track sessions separately. I want the other website site2 available by address www.site.com/site2. So I want all requests for static files of site2 redirected to www.site.com/site2/static and all the rest to 'www.site.com/site2/`. Is it possible? What's the best way to do it? I checked uwsgi emperor mode, but it seems I need different domains for that. -
Log every processed line of django python script in a file
I need to log line numbers of my django python script in a text file. Tried to install 'inspect' module but i failed (pip and easy_install does not find any modules with that name, and django-inspect broke my django installation. i had to re-install django). The only thing i need to log is the processed script lines, to see where my script breaks and what it does until then. -
logout by deleting cookies
I used this code to logout from django web app. but if I add url manually, it easily redirect me to that page,but that shouldn't happen as I'm logged out. def logout_view(request): user = check_validation(request) response = HttpResponseRedirect('/login/') #redirect to login page stoken = SessionToken(user=user) #stoken is object for SessionToken response.delete_cookie(stoken.session_token) return response Please tell me any solution to this problem,or anything that i am missing in this code. Thanks in advance :) -
Django RestFramework Serialization Example - Lexers and Styles
from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ('created',) Hello! I'm studying Django Rest Framework. In serialization tutorial(http://www.django-rest-framework.org/tutorial/1-serialization/#creating-a-model-to-work-with), I have a question in 'Creating a model with work' part(above code). I don't know what LANGUAGE_CHOICES and STYLE_CHOICES definitely means. What they do in this code? Thank you! -
Django: how to match apostrophe in URL
Regex [\w-.']+ (tested in http://regexr.com/) seems to match correctly for my needs. I need to be able to match English words like "don't", "e.g.", "air-condition" in URLs. I also need to support underscore since I replace spaces in words with it (for example, "air balloon" becomes "air_balloon" in URL). So I tried URL configuration r"^(?P<word>[\w-.']+)/$" in Django but it gives me an error: ImproperlyConfigured ... is not a valid regular expression. If I alter this a little and use configuration r"^(?P<word>[\w\-.\']+)/$" then I don't get the error and words like "dog", "e.g." etc. works normally. But in case of "don't", I get an error: NoReverseMatch at /application/don't/: Reverse for "view" with arguments '('n#39;t')' not found. Word "n't" as an argument is expected in results but it shouldn't give me an error. I supposed I could fix this by using safe and/or safeseq template filters but no success. My question is that how I should configure my URLs in Django to match also apostrophe correctly in URL? And is there anything else I need to consider to implement this in a secure and optimal Django way? Also, I would like to understand why Django gives me an error for a regex … -
Can't pull text field value into Backend. Django
I'm using a simple HTML form to pass data to my Django app's backend. The reason I'm not using a Django form is because I don't need to update the database. However, I'm unable to pull data from the form. HTML code: <form onsubmit="return false;"> {% csrf_token %} <div class="col-md-6"> <div class="input-group input-group-lg wow fadeInUp" data-wow-delay='0.8s'> <input type="text" id="fullname" required> </div> <button onclick="SendMessage()">Send Your Message</button> </div> <div id="output"></div> </form> JQuery code: <script type="text/javascript"> function SendMessage() { // $('.ajaxProgress').show(); $.ajax({ type: 'POST', url: ' {% url "payligent:send_message" %} ', dataType: 'json', async: true, data: { csrfmiddlewaretoken: '{{csrf_token}}', fullname: $('#fullname').val() }, success: function (json) { $('output').html(json.message); $('ajaxProgress').hide(); } }); } </script> view: def send_message(request): test = request.POST.get('fullname') response_data = {} try: response_data['message'] = test except: response_data['message'] = 'Oh Snap! message was not sent correctly' return HttpResponse(json.dumps(response_data), content_type='text/html') When I browse into: http://127.0.0.1:8000/sendmessage/ I get null instead of the name I filled in the form: {"message": null} I'm following this tutorial. -
Dynamic join of some filters in django
I want to get three fields form user, two fields are database fields one is a radio box for mode of joining of these fields i.e. and/or . The problem is that i don't know how to join these two filter based on the join filed. I want to use a line that can tell field1 join filed2, where join is the variable of user specified join mode. -
django modelsTypeError: decoding str is not supported
I'm a beginner trying to view a basic queryset with two records. I'm not able to process the request. Looking for some help. class TestVenue(models.Model): venue_name = models.CharField(max_length=40) venue_city = models.CharField(max_length=20, null=True, blank=True) venue_province = models.CharField(max_length=20, null=True, blank=True) venue_shortcode = models.CharField(max_length=20, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) my_date_field = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.venue_name my views.py is pretty simple def venues_listview(request): template_name = 'venues_list.html' queryset = TestVenue.objects.all() context = { "object_list": queryset } return render(request, template_name, context) from the shell i want to see my queryset but i get the following error: >>> from venues.models import TestVenue >>> TestVenue.object.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: type object 'TestVenue' has no attribute 'object' >>> TestVenue.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\users\frank\desktop\test_env\lib\site-packages\django\db\models\query.py", line 229, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "C:\users\frank\desktop\test_env\lib\site-packages\django\db\models\base.py", line 589, in __repr__ u = six.text_type(self) File "C:\users\frank\desktop\test_env\src\venues\models.py", line 14, in __str__ # return self.venue_name TypeError: decoding str is not supported -
Solving N+1 problems with cache_tree_children() doesn't work, blocking DRF's serialization
I have a Django-MPTT model called Category and a model called Channel. Using DRF, I want to serialize the Category children in tree order and it's parents. I can do it with the following which generates N+1 problems: #models.py class Category(MPTTModel): name = models.CharField(max_length=50, blank=False) channel = models.ForeignKey(Channel, null=False, blank=False) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class Channel(models.Model): name = models.CharField(max_length=50, blank=False) slug = models.SlugField(blank=True, unique=False, db_index=True) #views.py class CategoryUniqueViewSet(generics.ListAPIView): serializer_class = UniqueCategorySerializer def get_queryset(self): category_slug = self.kwargs['category_slug'] queryset = Category.objects.filter(slug__iexact=category_slug) return queryset #serializers.py class ParentSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('name',) class RootSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() channel = serializers.ReadOnlyField(source='channel.name') def get_children(self, category): queryset = category.get_children() serialized_data = RootSerializer(queryset, many=True, read_only=True) return serialized_data.data class Meta: model = Category fields = ('name', 'channel', 'children') class UniqueCategorySerializer(serializers.ModelSerializer): parents = serializers.SerializerMethodField() channel = serializers.ReadOnlyField(source='channel.name') children = serializers.SerializerMethodField() def get_parents(self, category): queryset = category.get_ancestors() serialized_data = ParentSerializer(queryset, read_only=True, many=True) return serialized_data.data def get_children(self, category): queryset = category.get_children() serialized_data = RootSerializer(queryset, read_only=True, many=True) return serialized_data.data class Meta: model = Category fields = ('name', 'channel', 'parents', 'children') This is my output when the result of my queryset is the Computer object: "name": "Computers", "channel": "walmart", "parents": [ { "name": "Books", "name": "Tech", } … -
Trying to get previous and next object in template Django
I need to get the previous & next value of the object (col2 from the object) in the same for loop iteration. Below is my index.html code: <script> var i = 1; var j = 0; </script> {% for b in obj %} <tr> <td>{{ b.col1 }}</td> <td><span class="wrapped"><span>{{ obj.j.col2 }}</span></span> </td> <td id='myTable'></td> <td id='myTable'></td> <td>{{ b.col5 }}</td> <td>{{ b.col6 }}</td> <td>{{ b.col7 }}</td> </tr> <script>j=j+1;</script> {% endfor %} </table> views.py: def display(request): return render_to_response('index.html', {'obj': my_model.objects.order_by('col2')}) What I tried was that when using: {{ obj.0.col2 }} or {{ obj.1.col2 }}, it displays the value of that cell correctly. However, when using {{ obj.j.col2 }}, it does not display anything. Why is this happening?? Why is it not reading j's value?? When I'm initializing j to 0 outside the loop and am incrementing value of j at the end of the loop as well!! -
Python If Statement Not Working when Testing Numbers Between 1 and 10
Trying to get the if statement to work. from __future__ import unicode_literals from django.shortcuts import render def index(request): return render(request, 'landscapes/index.html') def landscape(request, id): print id if id>=1 and id<=10: print 'true' landscape = 'https://wildwithgrace.files.wordpress.com/2010/12/snowy-landscape.jpg' context = { 'landscape': landscape } return render(request, 'landscapes/landscape.html', context) Only will ever return UnboundLocalError at /# even when the number is Greater than 1 and Less than 10. -
editing JSON in the admin interface django1.4 with mysql
I want to implement JSON editor in the django admin interface. I googled it and found some cool stuff to implement it but those are for postgresql or/and higher version of django. Please help me with some js library which works for me. thanks in advance -
read the data from database and print it using django
I have database created by django, but I can't print a text in my page from database. What function I will learn to make that. -
Updating a model using Django Rest Framework and ViewSets
I'm new to DRF, and I'm trying to build a webhook that gives out lists of model objects and also allows these objects to be updated. I followed this tutorial http://www.django-rest-framework.org/tutorial/quickstart/, and have the following serializer and view: class Task(serializers.ModelSerializer): class Meta: model = Task fields = ('user', 'task', 'unixTime') View: class RequestViewSet(viewsets.ModelViewSet): """ API endpoint that allows reqests to be viewed or edited. """ queryset = Task.objects.filter(done = False).order_by('-unixTime') serializer_class = Task paginate_by = None def list(self, request, *args, **kwargs): self.object_list = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(self.object_list, many=True) return Response({'results': serializer.data}) I'm pretty sure I have to include a def update under def list, but the online resources I found were a bit unclear on how to implement them and what they do. Any help is appreciated. -
Django Wagtail Documents Select a valid choice. That choice is not one of the available choices
I am using Django==1.11.3 and wagtail==1.11.1 I created a custom snippet in Django Wagtail CMS that includes wagtaildocs. When I try and attache a document, I get an error that says 'Select a valid choice. That choice is not one of the available choices.' I includes a screenshot below as well as my snippet. Thank you. class NewsletterTag(TaggedItemBase): content_object = ParentalKey('Newsletter', related_name='tagged_items') @register_snippet class Newsletter(ClusterableModel): title = models.CharField(max_length=255, blank=True) pubdate = models.DateField('Publication Date') thumbnail = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', verbose_name='Newsletter Thumbnail Image' ) link_document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, related_name='+', verbose_name='Choose Newsletter' ) tags = TaggableManager(through=NewsletterTag, blank=True) @property def link(self): if self.link_document: return self.link_document.url panels = [ FieldPanel('title'), FieldPanel('pubdate'), ImageChooserPanel('thumbnail'), DocumentChooserPanel('link_document'), FieldPanel('tags'), ] class Meta: verbose_name = 'Newsletter' -
Retrieve DB objects by id field in django
I'm trying to retrieve Instance object in another view by it's id which has been passed by a hidden input field from template, but couldn't get the object. Here's my files: BuildImage.html {% block content %} <form class="form-horizontal" method="POST" id="dockerForm"> {% csrf_token %} <fieldset> <div class="form-group"> <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-user bigicon"></i><label for="package">Docker Image Tag Name:</label></span> <div class="col-md-8"> <input type="text" name="tagName" id="tagName" placeholder="e.g node_image/istiogui" class="form-control" required> <input type="hidden" id="id" name="id" value="{{ id }}"> </div> </div> <div class="form-group"> <div class="col-xl-12 text-center"> <button type="button" class="btn btn-primary btn-info"><a href="/gui" style="color:white">Back</a></button> <button type="submit" class="btn btn-primary btn-info">Build</button> </div> </div> </fieldset> </form> {{ id }} is working as I have placed it at another place in this template. models.py class Instance(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, related_name='instances') name = models.CharField(max_length=255) serverFile = models.TextField(default='', blank=False) jsonPackageFile = models.TextField(default='', blank=False) created_at = models.DateTimeField(default=timezone.now, editable=False) class Meta: ordering = ['-created_at'] class ImageModel(models.Model): tagName = models.CharField(max_length=255) id = models.ForeignKey(Instance, primary_key=True) views.py class BuildImage(LoginRequiredMixin, CreateView): def get(self, request, *args, **kwargs): return render(request, 'instances/BuildImage.html', {}) def post(self, request, *args, **kwargs): if request.method == 'POST': pathlib.Path("mydir").mkdir(parents=True, exist_ok=True) dockerfile = """ FROM node # Create app directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/ap # Install app dependencies COPY package.json /usr/src/app/ RUN npm … -
Django, showing only matches condition in lookup
Apologies if this is a really stupid question... Say I have a model in personnel apps, like this, class Crew(models.Model): nik = models.CharField(max_length=20) name = models.CharField(max_length=30) phone = models.CharField(max_length=20) isActive = models.NullBooleanField(verbose_name='Active') class Meta: ordering = ('name',) def __str__(self): return self.name i'm also create a models in vehicle apps, like this: from personnel.models import Crew class Vehicle(models.Model): plateNumber = models.CharField(max_length=10) regDate = models.DateField(verbose_name='Date') driver = models.ForeignKey(Crew, on_delete=models.CASCADE) def __str__(self): return self.plateNumber now i want to get list of driver, where isActive = True in my lookup. how i make it..? this is what i mean -
Django Rest Framework returns 500 for Authentication Failure instead of 403
Here is the stack trace that I get: 500 : AuthenticationFailed at /api/docs Invalid username/password. Request Method: GET Request URL: http://192.168.56.101:8000/api/docs?format=openapi Django Version: 1.10.6 Python Executable: /project/bin/python2.7 Python Version: 2.7.6 Python Path: ['/home/john/tilda' Traceback: File "/project/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/project/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/project/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/project/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args **callback_kwargs) File "/project/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/project/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/project/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 489. response = self.handle_exception(exc) File "/project/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "/project/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 477. self.initial(request, *args, **kwargs) File "/project/local/lib/python2.7/site-packages/rest_framework/views.py" in initial 394. self.perform_authentication(request) File "/project/local/lib/python2.7/site-packages/rest_framework/views.py" in perform_authentication 320. request.user File "/project/local/lib/python2.7/site-packages/rest_framework/request.py" in __getattribute__ 378. return super(Request, self).__getattribute__(attr) File "/project/local/lib/python2.7/site-packages/rest_framework/request.py" in user 196. self._authenticate() File "/project/local/lib/python2.7/site-packages/rest_framework/request.py" in _authenticate 342. user_auth_tuple = authenticator.authenticate(self) File "/project/local/lib/python2.7/site-packages/rest_framework/authentication.py" in authenticate 86. return self.authenticate_credentials(userid password) File "/project/local/lib/python2.7/site-packages/rest_framework/authentication.py" in authenticate_credentials 99. raise exceptions.AuthenticationFailed(_('Invalid username/password.')) Exception Type: AuthenticationFailed at /api/docs Exception Value: Invalid username/password. Request information: USER: AnonymousUser GET: format = u'openapi' POST: No POST data FILES: No FILES data COOKIES: What is the recommended way to handle these errors with a proper HTML response status? (403 … -
How do I render a Django template as a string when using the include tag?
Long story short, I am trying to include a Django template as a string, and I would like to do something like this in a script tag: <script> var template = '{% include "mytemplate.html" %}'; </script> Right now I keep getting an invalid or unexpected token error, with the following output: var template = '<h1>Hello World</h1> ' Which makes me wonder if there's some sort of newline character taking effect at the end? And it seems to be taking effect before I can do anything about it since things like .trim() don't seem to work. -
Storing Config in Environment Python / Django
I have been wondering about this for awhile. Namely, how does one go about isolating the config from the codebase when doing projects in Python and/or Django. In particular, these thoughts have been inspired by one of Heroku's 12 Factors: III Config What are some ways one could do this? How could he comply with this requirement when writing projects in Python, especially Django? -
Django Model Design for "Wall"-type app
I am messing about with Django trying to learn more and I'm hitting a bit of a roadblock with understanding of the model design. I'm attempting to create an app that is like the facebook "wall" but it's purely albums with photos and videos, with comments and votes. My struggle is understanding how to design the relationship for items that could have many relationships. As an example, you can upvote photos, videos, comments, albums, and whatever else. What is the appropriate model design to address non-specific items? Here is my proposed structure thus far. Album --primary --id --datetime --created by --title --photo(s) --comment(s) --+1(s) photo --id --foreignkey album --datetime --uploaded by --caption --comment(s) --path --+1(s) video --id --foreignkey album --datetime --caption --comment(s) --path --+1(s) comments --id --user --datetime +1(s) +1s --id --user -
django sending email (delivery report)
I'm a beginner who is trying to use "Django" to send mail to multiple recipients. How could I get a delivery report that tells me that: "the mail delivered to recipients a,b,c and d". "The delivery failed to recipient (e) because his mail box is full". The delivery failed to recipient (f) because your message considered as spam". ... etc. Thanks in advance. -
How to get the index of the object being rendered in HTML using Django
I'm displaying a mysql database using Django on a webpage. I'm rendering the database as obj from views.py and using it in index.html. I want to know is it possible to get the index of this object obj? i.e., In the same loop iteration I want the next row's value, for example in row 10th's iteration, with {{ b.col2 }} I get col2's value for the 10th row, how can get I 11th row's b.col2 value in the same loop iteration and store it in a temporary variable for comparison. Is there a way I could get index of the object? <script> var i = 1; </script> {% for b in obj %} <tr> <td>{{ b.col1 }}</td> <td><span class="wrapped"><span>{{ b.col2 }}</span></span> </td> <td id='myTable'></td> <td id='myTable'></td> <td>{{ b.col5 }}</td> <td>{{ b.col6 }}</td> <td>{{ b.col7 }}</td> </tr> {% endfor %} </table>