Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. ` -
django-file upload request refresh
everything is ok when i am testing with django test server (manage.py runserver) but when i'm using it with apache2, after POSTing a form containing pdf file, The request with POST data get closed and a second request with no POST data is sent, enter image description here why this is happening and what i must do to solve it? -
Django - wkhtmlpdfkit 'utf-8' codec can't decode byte, invalid start byte
I use wkhtmltopdf to generate pdf, but I have problem with decode utf-8. 'utf-8' codec can't decode byte 0xfe in position 28: invalid start byte Some code with errors: area=Area.objects.get(pk=area_pk) logs=HuntingLog.objects.filter(area=area).order_by("pk") if request.POST: logs=filterLogs(request.POST['daterange'],request.session['area']) name="logs_"+datetime.now().strftime("%Y%m%d")+".pdf" temp=render_to_string("tables_raport/logs.html", {"log" : logs}) pdf=pdfkit.PDFKit(temp, "string").to_pdf() #HERE IS ERROR response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s"'%(name) return response And one more: if 'cannot connect to X server' in stderr.decode('utf-8'): I use Debian. -
Django makemigrations continues to detect removing of translated fields
I'm using django 1.10 and django-modeltranslation. I've removed registrations of translated fields for my models and applied sync_translation_fields management command. But now, everytime I run makemigrations, django produce migrations to remove fields and, although I can fake these, running tests gives errors because migrations try to remove those non existing fields. How to clean up this situation? -
Django 3rd party packages not working
Good day I'm working through a Django projects book called Django by example I am stuck working through the projects because I seem to be having trouble with 3rd party packages, namely taggit and pillow Using pillow as an example.. This is the error I get when I makemigrations for my apps model: (shop) PS C:\dan_projects\django_by_example_shop\myshop> py -3 .\manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". Yet 'pip freeze' is telling me that pillow is installed: (shop) PS C:\dan_projects\django_by_example_shop\myshop> pip freeze Django==1.8.5 Pillow==2.9.0 Any help would be greatly appreciated!! -
if condition within for loop of template is not working
This is my template.My for loop is working but not working when if is included. <table class="table" style="text-align: left;"> <thead> <tr> <th>Requested by</th> <th>Requested on</th> </tr> </thead> {% for request in all_requests %} <tbody> {% if request.dept is users.dept %} <td>{{ request.name }}</td> <td>{{ request.date }}</td> <td><button onclick="location.href= '/retest/{{ request.id }}/';">View details</button></td> <tr> {% endif %} </tbody> {% endfor %} </table> -
Prefetching FK objects chain in django for a Model
this question doesn't seem to have an answer since it's a slightly different problem. I have 1 abstract class and 4 concrete models hierarchically organized as below: class LevelAbstract(models.Model): class Meta: abstract = True name = models.CharField('name', max_length=255) class LevelA(LevelAbstract): class Meta(LevelAbstract.Meta): verbose_name = 'Level A' class LevelB(LevelAbstract): parent = models.ForeignKey(LevelA, related_name='children') class Meta(LevelAbstract.Meta): verbose_name = 'Level B' class LevelC(LevelAbstract): parent = models.ForeignKey(LevelB, related_name='children') class Meta(LevelAbstract.Meta): verbose_name = 'Level C' class LevelD(LevelAbstract): parent = models.ForeignKey(LevelC, related_name='children') class Meta(LevelAbstract.Meta): verbose_name = 'Level D' Now I would like to optimize this method in LevelD class that avoid multiple queries: @property def main_level(self): return self.parent.parent.parent I've tried to implement like: @property def main_level(self): self_prefetched_obj = LevelD.objects.select_related('parent', 'parent__parent', 'parent__parent__parent') return self_prefetched_obj.parent.parent.parent I'm not sure if I can call it 'optimization' as it re-fetch self object from DB and I'm wondering if there is any better way (before to take the decision to migrate to django-mptt). Thanks! -
django built in login view error messages
In django built in login view, if username or password is wrong, I want make an error messages with django messages. my template view, {% extends 'registration/base_nav.html' %} {% block content %} <div class="jumbotron"> <div class="container"> <div class="box"> <h2>Login</h2> <form class="form" method="post" action="{% url 'login' %}"> {% csrf_token %} <input type="text" placeholder="username" name="username"> <input type="password" placeholder="password" name="password"> <button class="btn btn-default full-width">Login</button> <input type="hidden" name="next" value="{{ request.path }}" /> <a class="reg" href="{% url 'signup' %}"> <p> <hr />Register. </p></a> </form> </div> </div> </div> {% endblock %} and error messages in base_nav {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}" style = "height:35px;padding-top:8px;width:50%;Float:left;margin-left:10%;"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <span class="glyphicon glyphicon-ok"></span> {{ message }} </div> {% endfor %} {% endif %} -
django : ContentType.objects.get_for_model(instance.__class__) giving wrong class name
i have a model named classPost and when i use c = ContentType.objects.get_for_model(instance.__class__) it gives me output: class post and when i try to get ContentType object of model using ContentType.objects.get(model=c) it gives me error: ContentType matching query does not exist. why it is giving me this error and why get_for_model() gives me wrong class name. models.py: class classPost(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=120) slug = models.SlugField(unique=True, blank = True) content = models.TextField() choice = ( ('post','post'), ('anouncement','anouncement'), ('question', 'question') ) post_type = models.CharField(choices = choice, default = 'post', max_length = 12) classroom = models.ForeignKey(Classroom) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.title def __str__(self): return self.title @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type views.py where i am using ContentType.objects.get() method. initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } print(initial_data) form = CommentForm(request.POST or None, initial= initial_data) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") print('c_type : ',c_type) content_type = ContentType.objects.get(model=c_type) print(content_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None -
How to get values from this json in python?
I am currently working in python and getting some json response from API. but after trying my best to fetch data from json, i am always getting this error, TypeError: string indices must be integers, not str here is my JSON file that i received, {"from":1,"to":10,"currentPage":1,"total":72,"totalPages":8,"queryTime":"0.023","totalTime":"0.059","partial":false,"canonicalUrl":"/v1/products(categoryPath.name=All Flat-Panel TVs)?show=sku,name,salePrice&format=json&apiKey=APIKEY","products":[{"sku":3813048,"name":"Samsung - 32\" Class (31-1/2\" Diag.) - LED - 1080p - HDTV - Black","salePrice":229.99},{"sku":4340402,"name":"Samsung - 43\" Class (42.5\" Diag.) - LED - 1080p - Smart - HDTV - Black","salePrice":429.99},{"sku":4380083,"name":"Samsung - 32\" Class (31.5\" Diag.) - LED - 1080p - Smart - HDTV - Silver","salePrice":299.99},{"sku":4405201,"name":"Samsung - 50\" Class (49.5\" Diag.) - LED - 1080p - Smart - HDTV - Black","salePrice":499.99},{"sku":4559300,"name":"VIZIO - 39\" Class (38.5\" Diag.) - LED - 720p - Smart - HDTV - Black","salePrice":269.99},{"sku":4562031,"name":"Samsung - 58\" Class (57.5\" Diag.) - LED - 1080p - Smart - HDTV - Black","salePrice":649.99},{"sku":4569901,"name":"LG - 24\" Class (23.6\" Diag.) - LED - 720p - HDTV - Black","salePrice":84.99},{"sku":4613600,"name":"Samsung - 32\" Class (31.5\" Diag.) - LED - 720p - Smart - HDTV - Black","salePrice":219.99},{"sku":4629257,"name":"Samsung - 32\" Class (31.5\" Diag.) - LED - 720p - HDTV - Black","salePrice":199.99},{"sku":4673800,"name":"Insignia™ - 24\" Class (23.6\" Diag.) - LED -720p - Smart - Roku TV - Black","salePrice":139.99}]} and i have tried in following ways, for … -
Having troubles uploading image through model form
I am having trouble uploading the image field on my model form. views.py: @user_passes_test(lambda x: x.is_superuser) def add_books(request): if request.method == 'POST': form = BooksForm(request.POST, request.FILES) if form.is_valid(): form.save() redirect('/') else: form = BooksForm() return render(request, 'library/books/addbook.html', {'form': form}) models.py: class Books(models.Model): picture = models.ImageField(upload_to='images/') name = models.CharField(max_length=100) publisher = models.CharField(max_length=200) author = models.CharField(max_length=100) member = models.ForeignKey(Member, related_name="books", null=True) def get_absolute_url(self): return reverse('library:detail_book', kwargs={'book_id': self.id}) def __unicode__(self): return "%s %s" % (self, self.name, self.author) def __str__(self): return "{0} {1}".format(self.name, self.author) forms.py: class BooksForm(ModelForm): class Meta: model = Books fields = ('picture', 'name', 'publisher', 'author') def clean_name(self): name = self.cleaned_data['name'] if Books.objects.filter(name=name).exists(): raise ValidationError("A Book with that name already exists!") return name addbook.html: {% extends "library/base.html" %} {% block content %} <div align="center"> <tr> <form method="POST"> {% csrf_token %} <h2>Book:</h2> {{ form.as_p }} <input type="submit" value="submit"> </form> </tr> </div> {% endblock %} settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Once, I try to add a book and i add the image field and hit the button, the form tells me that the image field is required and it does not let me upload the image. Thank you ahead for your help!