Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Get values from ManyToManyField which is foreing key
please help to understand. I have the next models : class TagsList(models.Model): tags_list = models.CharField(max_length=30) def __str__(self): return self.tags_list class Blog(models.Model): title = models.CharField(max_length=200) content = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(TagsList) how i can get related tags by object (in my case object with post_id)? It's my view file : def single(request, post_id): object_post = Blog.objects.get(id=post_id) tags = TagsList.objects.all() content = { 'object_post': object_post, 'tags': tags, } return render(request, 'single.html', content) I tried all cases, but how to include to content exactly tags which are related to this object, don't know. Thanks all, for the help. P.S. Using django 1.11 -
Which file format django imagefield(filefield) requires?
I'm trying to send file as JSON field to server for creating a new instance. This file has being saved in models.ImageField. However, I don't know which format this field requires for incoming file. I tried to send it in base64, but it isn't suitable. -
Django - Can't do a POST request, receiving 405 "Method not allowed"
i'm trying to do a simple POST request to my endpoint, but i'm getting a 405 "Method not Allowed", here's my code: urlpatterns = [ url(r'^api/exemplo/post/$', ExempleView.as_view(), name='post'), ] Post method: class ExempleView(APIView): def post(self, request, *args, **kwargs): print(request.data) Server logs: Method Not Allowed (POST): /api/exemplos/post/ [29/Apr/2017 14:30:20] "POST /api/exemplos/post/ HTTP/1.1" 405 0 I'm using Postman to do the post request and rest_framework to create my API, any suggestion? -
Why two almost identically querysets work differently?
I have comment and rate model. class Rate(models.Model): game = models.ForeignKey(Games) user = models.ForeignKey(User) rate = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)]) class Meta: unique_together = ['game', 'user'] class Comment(models.Model): game = models.ForeignKey(Games) author = models.ForeignKey(User) content = models.TextField(max_length = 2500) date_of_published = models.DateTimeField() For comments I have queryset in game view : comments = Comment.objects.filter(user=request.user) and in templates: {% for x in comments %} {{ x.content}} {% endfor %} And it works very well. I can display comments from only loggedin user. but I have too queryset for rate. user_rate = Rate.objects.filter(user=request.user) It doesn't work properly. In templates: {% if user_rate %} <h2><a href="">Edit rate</a></h2> {% else %} <h2><a href=">Add rate</a></h2> {% endif %} It doesn't work. I should display Add if user don't have rate, and Edit if user have rate. BUT, If user have rate for only game1, he see in game2, game3, and others Edit ( he should see Add, because he doesn't have rate for this game...) and {% for user_rate in user_rate %} <p> Your score : {{ user_rate.rate }} <p> {% endfor %} User should be see Your score : (rate for this game) But in this case, user see his score from all games... How to … -
Unresolved reference 'models'
I am writing custom template tag, and the error occurs that "Unresolved reference 'models'" the following is my blog_tags.py. from django import template from .models import Post register = template.Library() @register.simple_tag def total_posts(): return Post.published.count() And my directory tree is as followed blog/ __init__.py models.py ... templatetags/ __init__.py blog_tags.py And i do have a Post class in my Models. And when i click the prompt by pycharm "install package Post", after finishing installed it, the error disappear. I wonder do i have to do the same, which is install the package by the IDE, every time when i want to write a custom tag evolved with class in my Models? -
how to get specific value in python dictionary?
I call an api via python and return this code as response: { "cast": [ { "character": "Power", "name": "George" }, { "character": "Max", "job": "Sound", "name": "Jash" }, { "character": "Miranda North", "job": "Writer", "name": "Rebecca" } ] } I am trying to get the value of Rebecca because i need to get the Writer. So i wrote: for person in cast # cast is the variable keeps whole code above NOT inside the dict: if person["job"] == "Writer": writer = person["name"] but it gives me: KeyError at search/15 u'job' how can i get the value? -
Django ChoiceField, ModelChoiceField validation
I see that forms.ChoiceField is using this code to validate the value: def validate(self, value): """ Validates that the input is in self.choices. """ super(ChoiceField, self).validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages['invalid_choice'], code='invalid_choice', params={'value': value}, ) def valid_value(self, value): "Check to see if the provided value is a valid choice" text_value = force_text(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == k2 or text_value == force_text(k2): return True else: if value == k or text_value == force_text(k): return True return False and forms.models.ModelChoiceField this code: def validate(self, value): return Field.validate(self, value) Q1. Why Django uses validation to check if the selected value (from dropdown) is indeed in the choice list for forms.ChoiceField? Q2. When Django uses the validation from Q1, to check if the value is indeed in the choice list, why does not also check if the selected value is in the model records for forms.models.ModelChoiceField? -
Django - delete particular cron job (django-crontab)
I am trying to use cron in my django app. I use django-crontab package. This is part of my setings.py: cron1_time = '* * * * *' cron2_time = '*/2 * * * *' CRONJOBS = [ (cron1_time, 'mainapp.cron.print_inactive', '>> /home/user/Desktop/file.log'), (cron2_time, 'mainapp.cron.print_inactive1', '>> /home/user/Desktop/file.log') ] I would like to add an option to disable/enable particular cron jobs from my django admin panel. Is it possible to stop only one job? Crontab add adds every job which exists in CRONJOBS. I think I can use: call_command('crontab', 'remove') command but I don't know how can I delete/add particular cron job. -
Import not importing all functions?
https://github.com/ezhome/django-webpack-loader For some reason when I import webpack_loader.utils like in the README.md of the repo, it only imports get_loader (I want get_static). Anyone know why might be going on here? I have a view where I am attempting to use get_static. from webpack_loader import utils def app(request): url = utils.get_static('index')['url'] print (url) import types from inspect import getmembers, isfunction print ('meow') print ([o for o in getmembers(utils) if isfunction(o[1])]) This throws an error: AttributeError: module 'webpack_loader.utils' has no attribute 'get_static' If I comment it out the url code, it shows that only get_loader is being loaded. I'm confused as to why this is considering the file here: https://github.com/ezhome/django-webpack-loader/blob/master/webpack_loader/utils.py -
django - redirect to a page after registering a user
After a user successfully registers an account (creates a username and password) the webpage returns a blank registration form. I would like to redirect to the 'landingpage' url after successful registration. Here is the html form: <form method="post" action="{% url 'register' %}"> {% csrf_token %} <table>{{ form.as_table }}</table> <input type="submit" value="register" /> <input type="hidden" name="next" value="{{ next }}" /> </form> and urls.py: from django.views.generic.edit import CreateView from django.contrib.auth.forms import UserCreationForm urlpatterns = [ url('^accounts/register/', CreateView.as_view( template_name='registration/register.html', form_class=UserCreationForm, success_url='landingpage' ), name='register'), url('^accounts/', include('django.contrib.auth.urls')), url(r'^$', views.landingpage, name='landingpage'), ] Should the success_url='landingpage' redirect to the landingpage url? How do I redirect to the landingpage url after a successful registration? -
Django How to access another object by having a user name?
I have this in models: class CustomUser(AbstractUser): selectat = models.BooleanField(default=False) def __str__(self): return self.username class Score(models.Model): VALUE = ( (1, "Nota 1"), (2, "Nota 2"), (3, "Nota 3"), (4, "Nota 4"), (5, "Nota 5"), (6, "Nota 6"), (7, "Nota 7"), (8, "Nota 8"), (9, "Nota 9"), (10, "Nota 10"), ) user_from = models.ForeignKey(settings.AUTH_USER_MODEL, default=0) user_to = models.ForeignKey(settings.AUTH_USER_MODEL, default=0, related_name='user_to') nota = models.PositiveSmallIntegerField(default=0, choices=VALUE) def __str__(self): return str(self.user_to) How can i access the score objects by having the user? When i use the user by score object i can get the notes. x = Score.objects.filter(user_to__username='Fane') x <QuerySet [<Punctaj: Fane>, <Punctaj: Fane>]> for a in x: print(a.nota) 1 5 I want to use something like this: y = CustomUser.objects.get(id=7) x = x.score.all() for a in x: print(a.nota) 1 5 But this won't work, it's giving me: Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'CustomUser' object has no attribute 'score' -
Django - Private messaging conversation view
I have built a very basic private messaging module for my Django project. I have a Message model which consists of: sender (Foreign key to the member model) recipient (Foreign key to the member model) message date (Datetime of which the message was created) Now my issue is i would like to create a new view which returns a list of conversations based on these messages. I am trying to write a query which returns the latest messages but unique where sender = current user OR recipient = current user. This is so that i have a list of latest messages, which should be the equivalent of a conversation list. Have i got that bit right or am i completely over thinking things? Any help would be greatly appreciated. -
Unable to use gunicorn.service without import module error?
Here is my gunicorn service file, [Unit] Description=gunicorn daemon After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myproject ExecStart=/home/sammy/myproject/venv/bin/gunicorn --workers 3 --bind unix:/home/sammy/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target There is no error when I execute gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application, But using the gunicorn.service with sudo systemctl start gunicorn sudo systemctl enable gunicornIget this error, ImportError: No module named 'myproject' What is wrong? -
Django: NOT Null constraint failed for SQLIte
Below are my models. I am keep getting error when running python manage.py migrate django.db.utils.IntegrityError: NOT NULL constraint failed: app_project.description Models given below: from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=2000, blank=True, default='') progress = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=100) severity = models.SmallIntegerField(default=0) open_date = models.DateTimeField() close_date = models.DateTimeField() status = models.SmallIntegerField(default=0) def __str__(self): return self.title I am on Django 1.10 -
How do i stream video files in django via HttpResponse
i need your help, i am working on a project where videos will be a big part of it so for now i play video files by accessing their absolute urls but i want to stream them via HttpResponse to the template i'm using django framework, how can i do that? -
Django Json response Error message
I went through couple of questions but coulnd`t find an answer. I want to display error message on modal, and i was suggested to use Json. My views.py: @login_required def create_exam(request, letnik_id, classes_id, subject_id): if subject_id in SUBJECTS: path = letnik_id + '/' + classes_id + '/' + subject_id formone = ExamForm(request.POST or None, request.FILES or None) formtwo = FileForm(request.POST or None, request.FILES or None) if formone.is_valid() and formtwo.is_valid(): exam_form = formone.save(commit=False) exam_form.exam_user = request.user exam_form.exam_path = path if Exam.objects.filter(exam_path=path, exam_number=exam_form.exam_number): #here i want the json saying that model exists already exam_form.save() exam_id = exam_form.id exam = get_object_or_404(Exam, id=exam_id) files = request.FILES.getlist('exam_file') for file in files: instance = ExamFile( exam_file=file, exam=exam, ) instance.save() return redirect('subject_id', letnik_id=letnik_id, classes_id=classes_id, subject_id=subject_id) #here the json response should say that form is not valid raise Http404("Website doesnt exist") I want to pass error message in the views and display it in the html without refreshing. How would i achieve this, using json response and passing the error in template with javascript? -
Using views to change DRF response
I would like to alter the response from an API. However, it does not alter the result properly. I get a `KeyError: 'game'. I am not sure, as my API response (via URL) seems to have the value. I have a sample of the API response below results from API { "pk": 995, "game": [ { "name": "Finance", "gamelevel": 3 }, { "name": "Data", "gamelevel": 1 } ] }, serializers.py class TagList(viewsets.ModelViewSet): queryset = Task.objects.filter(tag__isnull=False).all() serializer_class = TagSortSerializer def get_queryset(self): test = self.queryset.values('title', 'tag__name') result = defaultdict(set) for item in queryset: parent = {'name': 'NoLevel_1'} children = [] for game in item['game']: if game['gamelevel'] == 1: parent = game else: children.append((game['gamelevel'], game['name'])) result[parent['name']].update(children) result = [ { 'name': parent, 'game_child': [ {'name': name, 'gamelevel': gamelevel} for gamelevel, name in games ], 'gamelevel': 1, } for parent, games in result.items() ] return result -
Setting input image default value
I want to set input tag default value to "http://websamplenow.com/30/userprofile/images/avatar.jpg" background-image is useless.. I am using django and bootstrap. My template. {% extends 'base.html' %} {% block content %} <style> textarea.form-control { height: 500%; } </style> <div class="container" style="padding-top: 60px;"> <h1 class="page-header">Edit Profile</h1> <div class="row"> <form class="form-horizontal" method="post" enctype="multipart/form-data"> {% csrf_token %} <!-- left column --> <div class="col-md-2 hidden-xs"> <img id="image" class="img-responsive img-thumbnail" /> <input name="image" id="files" type="file" class="text-center well-xs"> </div> <!-- edit form column --> <div class="col-md-8 col-sm-6 col-xs-12 personal-info"> <div class="form-group"> <label class="col-md-3 control-label"></label> <div class="col-md-8"> <button class="btn btn-primary" type="submit">submit</button> <span></span> <a class="btn btn-default" href="{% url 'soldier-list' %}">&nbsp;&nbsp;cancel&nbsp;&nbsp;</a> </div> </div> </div> </form> </div> </div> <script> document.getElementById("files").onchange = function () { var reader = new FileReader(); reader.onload = function (e) { // get loaded data and render thumbnail. document.getElementById("image").src = e.target.result; }; // read the image file as a data URL. reader.readAsDataURL(this.files[0]); }; </script> {% endblock %} Please help me. Thanks. -
How to display an animated icon during python function processing in django?
I am trying to develop an application with Django. I have a form in my HTML file which will pass same data to the server. At server side, my python function(called submit) will receive the posted values and process them and then redirect the user to a new page. Question: How can I show a loading gif to the user until my python function is processing posted data and finished? I searched on the stackoverflow about this question and there are some answers (this and this and this) but the answers are for finishing Ajax functions, or there is no explanation how can I identify when my python function has been finished or is for flask framework. Any help would be greatly appreciated. -
Check authentication with a key pair
I'm using Android and Django (Python) like WebService. I generate the key pair with Python in the server side (when the user registers in the application). The server sends the public key to the client (Android) and I need to sign the message with that public key to send it to the server signed. Finally, the server verify the sign of the message with the private key. ¿How can I do this? Because I have different languages... In Python I generate the key pair like this: random_generator = Random.new().read key = RSA.generate(2048, random_generator) #generate public and private keys public_key = key.publickey().exportKey() private_key = key.exportKey() public_key = public_key,usuario=user) I'm reading about Android and the code is something like this: Signature sg = Signature.newInstance("SHA256withRSA"); sg.inicialize(publicKey); sg.update(msg.getBytes()); sg.verify(msg.getBytes()); -
using JS Modal with Django logic
i have a modal which opens when the user clicks on an image. The modal is supposed to show the (clicked on) picture and some extra information which is saved in the PostModel. Im using django and I have a for loop on the template so I have a lot of different pictures with the same class. so naturally I tried to put {{post}}/{{post.slug}} into the modal but It always showed the first element from the for loop. I found this solution with JS $("img").on('click', function () { var image = $(this).attr('src'); var title = $(this).attr('abc'); $('#myModal4').on('show.bs.modal', function () { console.log("helllllo2") $(".img-responsive").attr("src", image); $(".modalTit").text(title); }); }); and In the modal I put <img class="img-responsive" src=""/> so this is working but now I would need some extra information about the post(slug, title,comments,likes etc). I could get all the information I need using the same logic but this requires a lot of coding and the site would load a lot of things it does not need to load. is there a way use the advantages django logic with {{post}} in the modal so I could do {{post.comments/likes/title etc.}}? I hope somebody can help me to make this more efficient. Thanks in advise -
How to convert file to send it to FileField?
I'm writing a test, in which a client sends json data. And this data has image fields. How should I convert files for further handling them by models.ImageField? Currently I tried to read them like f.read(), and during tests django showed an error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte. I tried to open them with 'rb' mode, and console was overflowed by symbol codes. My code: def test_sign_up_with_valid_data(self): with open('test/bg.jpg', 'rb') as bg: valid_registration_data = json.dumps({ ... 'background': bg.read(), ... }) response = self.c.post('/persons/sign_up', valid_registration_data, content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 201) Also I tried to encode the file to base64 like base64.b64encode(bg.read()), however it called the same error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte. What should I do with file before send it to server for saving in model? -
Reversing results for current page (django paginator generic view)
I'm using the standard django paginator in my generic view like this: def get_context_data(self, **kwargs): context = super(ArchivePagedView, self).get_context_data(**kwargs) article_list = Article.published #===================================== paginator = Paginator(article_list, self.paginate_by) page = self.request.GET.get('page') try: article_list = paginator.page(page) except PageNotAnInteger: article_list = paginator.page(1) except EmptyPage: article_list = paginator.page(paginator.num_pages) if 'reverse' in self.request.GET: article_list = article_list.reverse() #This doesn't work! else: article_list = article_list.all() context['article_list'] = article_list return context As you can see I want to override article_list with the same list, but in reversed direction, if reverse is in the URL in behind the question mark. That information I get by 'reverse' in self.request.GET. But I get an error: AttributeError: 'Page' object has no attribute 'reverse'. How do I reverse this? (I don't want to have duplicated code in my template.) Before I fixed this by making an extra context variable (context['reverse']) which says whether the list should be reversed or not, and then I used duplicated code like this: {% if reverse %} {% for article in article_list reversed %} ... some code {% endfor %} {% else %} {% for article in article_list %} ... the same code {% endfor %} {% endif %} I wonder if there was no better solution. -
Form in Footer and multi form in Django
Hello Is there any way to accept a input from footer? I have a footer which is for Newsletter signup. Users insert their mail there. How could I accept that data? Do I need to send form via views every time. or there is a way to accept form from that included template code? Well I also have A feed back form in the footer which in included in all the pages I want the feedsback to be stored in my DB. I cannot figure out how I can accept the form data from all pages. (Sending forms in all page through views is possible But I think there is A easy (good Looking) idea) and also There are more them one Post method. I really don't know how to Explain. But I expect you can understand me. -
Django form checkbox unable to save data
I am trying to display a form (with multiple select checkbox) and save the data in database. But having some problem. Here is My Model:- class Preference(models.Model): CLASS_CHOICES = [('1', '1'), ('2', '2'), ('3', '3')] BOARD_CHOICES = [('C', 'CBSE'), ('I', 'ICSE'), ('S', 'State Board')] SUBJECT_CHOICES = [('H', 'HINDI'), ('M', 'MATH'), ('E', 'ENGLISH')] Class = models.CharField(max_length=2, choices=CLASS_CHOICES, default='1', blank=False) Board = models.CharField(max_length=2, choices=BOARD_CHOICES, default='C', blank=False) Subject = models.CharField(max_length=2, choices=SUBJECT_CHOICES, default='M', blank=False) My form:- class PreferenceForm(forms.ModelForm): class Meta: model = Preference fields = ['Class', 'Board', 'Subject'] widgets = { 'Board': forms.RadioSelect(), 'Subject': forms.CheckboxSelectMultiple } My View:- def pref2(request): form = PreferenceForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'website/thanks.html') else: print(form.errors) return render(request, 'website/pref2.html', {'form': form}) It displays the checkbox but I am unable to save that data to database even when I select a single choice. It displays the error:- ` <ul class="errorlist"><li>Subject<ul class="errorlist"><li>Select a valid choice. [&#39;H&#39;, &#39;M&#39;] is not one of the available choices.</li></ul></li></ul> All help/suggestions are appreciated, thanks. `