Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS Elastic Beanstalk not deploying code fixes
I'm using aws EB to deploy my django app. I use the AWSEBCLI. Everything works fine but if for some reason I mistakenly deploy broken code the ebcli will never deploy a new corrected version. I'll have to SSH into the EC2 instance and fix it manually. Why? is there a way to force new code? For example, I do some edits and I run git add . then git commit -m 'xx' then eb deploy the result is: TabError: inconsistent use of tabs and spaces in indentation. container_command 01_migrate in .ebextensions/02_python.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. INFO: Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. ERROR: Unsuccessful command execution on instance id(s) 'i-xxx'. Aborting the operation. ERROR: Failed to deploy application. At this point even if I edit the code, fix the indentation make the new git adds & commits eb will always show me this error until I SSH into the instance and I fix it manually. Only then it will start to accept new commits. I really don't understand why and is rather annoying. Any ideas on how to skip the whole SSH part? -
How to join 3 tables in query with Django
models.py class Employee(models.Model): emp_no = models.IntegerField(primary_key=True) first_name = ... last_name = ... # emp_no first_name last_name ------ ---------- ---------- 10005 Christian Erde class DeptEmp(models.Model): emp_no = models.ForeignKey(Employee, on_delete=models.CASCADE) dept_no = models.ForeignKey(Department, on_delete=models.CASCADE) # dept_no_id emp_no_id ---------- ---------- d003 10005 class Department(models.Model): dept_no = models.CharField(primary_key=True, max_length=4) dept_name = models.CharField(unique=True, max_length=40) # dept_no dept_name ---------- --------------- d003 Human Resources views.py class EmpList(ListView): queryset = Employee.objects.all().select_related('deptemp').select_related('department') employee_list.html {{ employee.emp_no }} {{ employee.first_name }} {{ employee.last_name }} {{ department.dept_name }} I don't know how to write a queryset to join 3 tables. I wrote it but I don't think it's right because i'm not getting any data in the template. All the variables in the template contain empty values. -
Loading a fixture is trying to match the wrong db fields. How to fix?
I get this error message: django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'billing_receipt' with primary key '8' has an invalid foreign key: billing_receipt.number_id contains a value '7038' that does not have a corresponding value in billing_receiptnumber.number. My models should be (simplified): class ReceiptNumber(models.Model): id = models.AutoField(primary_key=True) ... class Receipt(models.Model): number = models.OneToOneField("ReceiptNumber", blank=True, related_name="receipt", null=True) ... But then it gives me very random error messages that point to a missing number field. So I added the number field. This was there at some earlier time, but does not do anything right now. It is simply there to get to the bottom of the problem. class ReceiptNumber(models.Model): id = models.AutoField(primary_key=True) number = models.IntegerField(null=True) Finally here is the JSON that causes this error in the fixture. As you can see there is nothing said about using the "number" field as a pk. Instead it should look for the standard id field. {"model": "billing.receiptnumber", "pk": 7038, "fields": {}}, {"model": "billing.receipt", "pk": 8, "fields": {"number": 7038, "vat": 7, "amount": "250.00", "body": "Interview mit Michael Kellner von den Gr\u00fcnen", "date": "2017-05-02", "task": 40}}, Why does it do that and where can I fix this? For some reason Django still uses the removed "number" as … -
Run Python on Website Using Django
Say I have a website I've already made and a python battleship game. How do I run the game on a page of the extant website using django? -
Unicode search key lead to no relevant results in database search. Django + Python 2.7
I am working with cyrillic text. There is parser written in python2.7 which saves strings from another site into database, which are saved as unicode to database [u'\u041a\u043e\u043d\u0446\u0435\u0440\u0442\u044b'] type: <type 'lxml.etree._ElementUnicodeResult'> In templates it's shown as normal text (russian this case), but search doesn't work. In this case using django filters(any)(and the relevant data is present)do not return by the normal key? Is it correct behaviour? What is the right solution? Tired cyrillic letter, and the must be results by this search. The type of string is unicode, but find nothing among many result starting with the following letter, so something is wrong, but I can't understand why. And at the same time english search keys give relevant search result to english words, while russian do not. var = u'б' print(type(var)) result = Event.objects.filter(title__istartswith= var) -
Django query: get value from not directly related model
I want to get value from not directly related model in Django. I have following models: class Platform(models.Model): platform = models.CharField() class Game(models.Model): game = models.CharField() genre = models.CharField() class Link(models.Model): game = models.ForeignKey(Game) platform = models.ForeignKey(Platform) How could I get QuerySet of Game objects where game title (Game.game field) would be replaced to following pattern: Game (Platform) (eg. 'Battlefield (PS3)') without extra hits to database? In SQL it would look like this: SELECT g.id, g.game || ' (' || p.platform || ')' AS game FROM game g INNER JOIN link l ON g.id = l.game_id LEFT JOIN platform p ON l.platform_id = p.id; -
linking users in the comments with Django
Hello Community I am using Django and I would like to "tag" or "link" users in a comment (like you do it in Facebook or Reddit). The goal should be that the user can write a comment and write a "#" or a "@" to refer to a user in the comment, this user should get some kind f Notification. I thought to try something with RegEx (like if "#" in comment...) so the username is a link to the profile, but even if i get this to work, i have no idea how to send a user a message/notification that he got mentioned. Any suggestions how to approach this Problem? Im feeling kind of lost here since i don't know where to start. -
what is no such column: REFERRED.number?
I'm trying to load a fixture and it gives me: django.db.utils.OperationalError: Problem installing fixtures: no such column: REFERRED.number Unfortunately, I cannot show the json, because there is all kind of private stuff in there, but I was hoping someone might explain to me what the REFERRED might mean. What kind of error am I looking for? I made a few migrations and now the DB is out of wack. So the json is slightly off to the DB. There are multiple things called number though. Referred sounds it's some kind of foreignkey error!? Can you give me any hint what to look for? -
Adding a value to the user input
I am trying to create a management system with django framework. I am asking if there a way when one tries to input a withdraw, the system stores that withdraw+200 in the database. For example if one input 10000, it stores in the database(models) 10200, thanx -
Restoring Django Model Field after accidental deletion
I have an existing events model in my django app that lists events. The events has a poster field that was using the models.ImageField for storing the related poster. The uploading of events was controlled from the admin only so no public uploading. The database had about 50 entries of events and things were working fine. Since the images was getting heavier, I tried adding the sorl.thumnail to django. In my models.py file, I imported the ImageField from sorl.thumbnails and added it to the poster field. When I ran makemigrations, it reported 'alter field poster' Then I ran migrate and on reloading, I do not see the Poster field in the admin. Even the existing events have lost the poster field and the images cannot be shown in the templates too. I have reverted the changes and run migrations again, but the poster field is still not visible. Is there any way to restore the model, and reconnect it with existing poster images? I am using python 3.5 and django 1.11 Everything else works fine, this seems like a stupid mistake for the sake of getting a little more speed. Will be grateful for any suggestions. -
DRF 3.6: How to document input parameters in APIView (for automatic doc generation)?
I'm struggling with DRF 3.6 auto-generated interactive documentation to provide input parameters to fill in interactive mode. As a result, I get an empty windows for my POST request (which would require 3 parameters actually): With Swagger, I could do it directly in docstring with some YAML. Now, after browsing DRF documentation, I can't find the way to do it. class ActivateCustomerView(APIView): permission_classes = (AllowAny,) def post(self, request): """ View dedicated to activating a pre-recorded customer # Should I add some parameters here? """ serializer = ActivateCustomerSerializer(data=request.data) serializer.is_valid(raise_exception=True) # ... -
Web Scraper Using django (python for web)
It's been a month or so, yeah? I've been searching the web for web scraping using python and I have found beautifulSoup and lots of other scraping tools such as Scrapy, scraper, etc. All of them are the same...a little differences there might be.. Most tutorials I watch or read, are the same to... Okay, what I am trying to do here is the following: Except of putting the URL that I wanna scrape into the code...I want the USER to INPUT the url and then the scraper scrapes that url that the user has pasted in the HTML field All tutorials have the code like this: url = (http://......) No...I want it somehow like this: url = (USER INPUT) Example video: Link scraper It's funny how he didn't actually to this in his tutorials...I think? but yes, that's what I am trying to do, if you have any tutorial or documentation of doing this, please please help me out!! Thank you! -
Pass context through multiple nested inclusion tags in Django
I'd like to pass the 'context' variable through multiple inclusion tags in Django like so: base.html: {% load extras %} {% table_of_contents course %} table-of-contents.html: {% load extras %} <h1>Table of contents</h1> {% for section in course.sections %} {% display_section section %} {% endfor %} extras.py: @register.inclusion_tag('table-of-contents.html', takes_context=True) def table_of_contents(context, course): return { 'course': course, } @register.inclusion_tag('display_section.html', takes_context=True) def section_expanded(context, section): # Identify the user from the context request user = context['request'].user return { 'section': section, 'completed': section.has_been_completed_by(user), 'outstanding_modules': section.get_outstanding_modules_for(user) } However, when I run the code above, I get a key error because the context variable is not passed through to the second inclusion tag: KeyError at /courses/pivottables-video-course/table-of-contents/ 'request' How can I ensure that the context variable persists when passed through to multiple nested inclusion tags? -
Atomicity of save() in django
Let's consider a table in database: Book: +--------+ |id|title| ---------- The table is empty. Now, I have a piece of code: from django.db import models class Book(models.Model): title = models.CharField(max_length=100) def f(title): b = Book() b.id = 1 b.title = title b.save() And, I have two processes: Process 1 executes: f('t1') Process 2 executes f('t2') What if the following situation will take place? The save() looks like ( based on what I read from documentation) (1) UPDATE # if primary_key is set (2) INSERT # if UPDATE returns 0 rows or primary_key = None What if the second process executed (1) operation. Now, the first process executed (1) and (2) operation. And now, the second process tries to execute (2). ERROR. So, in fact, the question is: It is safe when it comes to atomicity? Does django ensures atomicity in that situation? If not, how can I do it? -
How to update datetime of a huge mongo dataset using pymongo
I have a dataset of at least 12GB which has data dump of last 30 days. It is actually analytics data. I want to show this dump as demo analytics, like if a user want to see how my app's analytics works they can check the last 30 days of analytics data irrespective of the date. So, I came up with a solution without changing the datetime for all the records, I could change the first date entry to recent date everyday. suppose, the first date of the dataset is 2017-04-01T23:00:00Z now, on 1st May it will become 2017-05-01T23:00:00Z. This way I want to just replace the date but not the time. I want time to remain same. Here is an example of one such entry, { "_id" : { "_ts" : ISODate("2017-04-01T23:00:00.000Z"), "_appId" : NumberLong(50), "_event" : "_searchclick" }, "sum" : 5663, "noresults" : 0, "transactions" : 0 } I am using: MongoDB: 3.2 Pymongo: 3.2.2 Django: 1.8.2 I am very new to MongoDb and Pymongo. So, I am open to any kind of suggestion to accomplish this. Let me know if you need more details before down voting the question. Thank you in advance. -
How can I edit the kwargs of a RedirectView?
I have a project that needs to redirect legacy urls to the new urls (I need to keep them for a while)... I'm using the RedirectView class to do this, but I have to set up the url hard-coded. My code is like this: class LegacyParlamentarDetailRedirectView(RedirectView): permanent = True url = '/parlamentar/%s' def get(self, request, *args, **kwargs): pk = request.GET.get('cod_parlamentar', '') self.url = self.url % (pk) return super(LegacyParlamentarDetailRedirectView, self).get(self, request, *args, **kwargs) What I want to do is to use the pattern_name attribute so I do not have to write the url, but I need to add the variable pk to the kwargs list (something like this): class LegacyParlamentarDetailRedirectView(RedirectView): permanent = True pattern_name = 'parlamentar_detail' def get(self, request, *args, **kwargs): kwargs['pk'] = request.GET.get('cod_parlamentar', '') return super(LegacyParlamentarDetailRedirectView, self).get(self, request, *args, ) can anyone help me? -
How to use validators on FileField content
In my model, I want to use a validator to analyze the content of a file, the thing I can not figure out is how to access the content of the file to parse through it as the file has not yet been saved (which is good) when the validators are running. I'm not understanding how to get the data from the 'value' passed to the validator into a file (I assume I should use tempfile) so I can then open it and evaluate the data. Here's a simplified example, in my real code, I want to open the file and evaluate it with csv. in Models.py class ValidateFile(object): .... def __call__(self, value): # value is the fieldfile object but its not saved # I believe I need to do something like: temp_file - tempfile.TemporaryFile() temp_file.write(value.read()) # Check the data in temp_file .... class MyItems(models.Model): data = models.FileField(upload_to=get_upload_path, validators=[FileExtensionValidator(allowed_extensions=['cv']), ValidateFile()]) Thanks for the help! -
querying foreignkey nested for loop django
I am trying to return a list of categories for a business, and for each category I would like to list all the meals related to the category. I was returning all of my items, not by category, but I have decided I want them sorted by category. This is what I have tried (among other attempts as well) I simply am having trouble getting the meals into there categories. This is my latest attempt In my models.py I have Business(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) logo = models.CharField(max_length=300) ItemCategory(models.Model): name = models.CharField(max_length=50) Item(models.Model): name = models.CharField(max_length=100) business = models.ForeignKey(Business) category = models.ForeignKey(ItemCategory) short_description = models.CharField(max_length=250) in my views.py def business_profile(request, business_id): items = Item.objects.filter(business_id = business_id).select_related('itemcategory') return render(request, 'business_profile.html', {"items": items}) in my template I am trying {% for itemcategory in items.itemcategory_set.all %} {{ itemcategory.name }} {% for item in itemcategory %} {{ item.name }} <br> {{ item.short_description }} {% endfor %} {% endfor %} From my research into other questions and reading the documents, i felt this would be right.. However from my results I can not get the correct output in my template. Would this be the correct practice? Or should I try getting the categories … -
Simple Subquery with OuterRef
I am trying to make a very simple Subquery that uses OuterRef (not for practical purposes, just to get it working), but keep running into same error. posts/models.py from django.db import models class Tag(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=120) tags = models.ManyToManyField(Tag) def __str__(self): return self.title manage.py shell code >>> from django.db.models import OuterRef, Subquery >>> from posts.models import Tag, Post >>> tag1 = Tag.objects.create(name='tag1') >>> post1 = Post.objects.create(title='post1') >>> post1.tags.add(tag1) >>> Tag.objects.filter(post=post1.pk) <QuerySet [<Tag: tag1>]> >>> tags_list = Tag.objects.filter(post=OuterRef('pk')) >>> Post.objects.annotate(count=Subquery(tags_list.count())) And here I keep getting the same error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. -
POST or not? render_to_response() or render()?
sI am very new user of Django. I would like to send an email (for fax) in clicking on a button. So I have created the method send_fax in the view CustomerRequestUpdateView. I am a bit confusing here. Does this method have to use a POST request? How could I render 'send_fax' to my template? class CustomerRequestUpdateView(RequestUpdateView): template_name = 'loanwolf/customers/request.html' url_namespace = 'customers' def send_fax(self): subject = 'The contract of %s' % self.customer.email_user contact_message = 'This is just a test for later on during this project' from_email = settings.EMAIL_HOST_USER to_email = [from_email, ] send_mail( subject, contact_message, from_email, to_email, fail_silently=False, ) return #render(request, template_name, context) render_to_pdf() I thought I could use render_to_response() or just render(), but my method use self, not request. Could anyone be able to help me here? -
Unable to upload file using REST API Django-Rest Framework
I am trying to build a REST API that should read the uploaded file and display the contents of the file. But I am unable to upload the file as the screen show below is what appears. I am relatively new to Django/Python so any help would be appreciated. I have shown the code I have below as well. REST_API_Image views.py from multipart_form_data.serializers import FilesSerializer from rest_framework.views import APIView from rest_framework.response import Response from multipart_form_data.models import Files from rest_framework import status from django.db.utils import OperationalError import csv @api_view(['GET', 'POST']) def upload_form(request): if request.method == 'POST': instance = Files(docfile=request.FILES['docfile'], title=request.DATA['title']) instance.save() return Response('uploaded') elif request.method == 'GET': files = Files.objects.all() print files serializer = FilesSerializer(files,many=True) return Response(serializer.data) @api_view(['POST', 'GET']) def upload_serializers(request): if request.method == 'POST': serializer = FilesSerializer(data=request.DATA, files=request.FILES,many=True) if serializer.is_valid(): serializer.save() return Response(data=request.DATA, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'GET': files = Files.objects.all() serializer = FilesSerializer(files,many=True) return Response(serializer.data) serializers.py from rest_framework import serializers from multipart_form_data.models import Files class FilesSerializer(serializers.ModelSerializer): class Meta: model = Files fields = ('docfile', 'title') allow_null = True many = True models.py from django.db import models class Files(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, default='default_value') docfile = models.FileField(upload_to='/file') urls.py from django.conf.urls import url from django.contrib … -
How to configure Apache to work with Django
I am struggling to configure my Apache so that I can correctly run my django app. I can run the app correctly on the server machine using python manage.py runserver. I can get to all the pages correctly. But when I set up Apache to use reverse proxy to so it can forward requests to django I get some pages that work and some that don't. It's because the reverse proxy has a path like /myapp in the definition. So the pages in the django app break if their URLs don't resolve to /myapp/rest-of-path. I need to use this myapp path because apache is serving other pages. I'm not sure how you put a server like django behind apache such that apache can forward to it where URLs are like example.com/myapp so that apache forwards to the correct place AND so that the django server doesn't have all its URLs messed up because of the presence of the "myapp" necessary in the reverse proxy definition. I've tried stuff from a lot of websites that describe apache/django config but nothing seems to mention this issue or show what the resolution is. THey all describe it so that the new app acts … -
Internal Server error 500 - Ajax and Django
I am trying to post comment from views to the template but I get internal server error 500 when executing this code: views.py: def comment(request, letnik_id, classes_id, subject_id): if request.method == 'POST': exam_id = request.POST.get('exam_id') exam = get_object_or_404(Exam, id=exam_id) comment = request.POST.get('post') comment = comment.strip() if len(comment) > 0: instance = ExamComment( exam=exam, comment=comment, comment_user=request.user) instance.save() user = request.user.username html = '{0}{1}'.format(html, render_to_string( 'exam_partial_comment.html', {'comment': comment})) return HttpResponse(html) else: return HttpResponseBadRequest() ajax: $(".comments input[name='post']").keydown(function (evt) { var keyCode = evt.which?evt.which:evt.keyCode; if (keyCode == 13) { var form = this.closest("form"); var container = form.closest(".comments"); var olist = $(container).find(".clearfix"); var input = this; $.ajax({ url: "{% url 'comment' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}", data: $(form).serialize(), type: 'post', cache: false, beforeSend: function () { $(input).val(""); $(input).blur(); }, success: function (data) { clearfix = $(container).children(".clearfix"); $(clearfix).html(data); } }); } }); Does anybody happen to know what am i doing wrong? -
Translate django variable with html template value
I am trying to translate like this: <div class="col-sm-7 section"> {{ template |safe }} </div> template = <div class="row"> <div class="calc-head">{% trans "Calculations" %}</div> </div> But the {% trans "Calculations" %} is not working for me. Can anyone help me -
Wagtail / Django inbuilt main menu
Started a project working with Wagtail CMS and what I understood of their principal of pages is that it is hierarchical leading me to the conclusion that pages are either parent/child related or siblings. So how I have done it is have my main page landing and all other pages would be children of this page. Here is my structure Home page / | \ News About us Events / | \ / | \ n_item n_item n_item e_item e_item e_item So they are 6 types of pages Home page * (unique) News * (unique) n_item (News Item) About Us * (unique) Events * (unique) e_item (Event Item) I then ticked the "Show in menus:" in the promote tab for the starred pages (*) in the above list. The n_item and e_item will allow the editor (non technical) person to add as many of these pages as they wanted as they will be listed as part of the contents in the "News" and "Events" pages respectively. Ideally the editor should not create siblings to Home Page,News, About us and events. Is it also possible to limit wagtails functionality of where editors can add pages if they are not super users? …