Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to disable cache for authenticated users?
My home page is the same for everyone except the navbar which displays the user's username. I recently applied caching to my entire site using the following : MIDDLEWARE += [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] # CACHING CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': 'C:/Site/_cache', } } CACHE_MIDDLEWARE_SECONDS = 21600 # 6 hours Unfortunately, the site will now sometimes cache a version of the page including the username, meaning the site will display for some users with other people's usernames. Not ideal. What is the best way to deal with this ? Can I exclude this part of the template from my cache ? Or can I just say that caches aren't used for authenticated users ? -
Django formsets: Assign values before form/data is saved
I created a formset, which will be saved in the database afterwards. The formset has two fields 'ticket' & 'quantity'. In my model, there two additional fields 'order_reference' and 'ticket_name', which should be assigned before saving the form. Can you help me to achieve that? models.py class ReservedItem(models.Model): order_reference = models.CharField( max_length=10 #unique=True ) ticket = models.ForeignKey( Ticket, on_delete=models.PROTECT, related_name='reserved_tickets' ) ticket_name = models.CharField(max_length=100) quantity = models.IntegerField(default=0) views.py def event_detail(request, event, organiser): queryset = Event.objects.filter(organiser__slug=organiser) event = get_object_or_404(queryset, slug=event) tickets = [] for ticket in Ticket.objects.all(): tickets.append({'ticket': ticket}) ReserveFormSet = formset_factory(ReserveForm, extra = 0) formset = ReserveFormSet( initial=tickets # Example with qty how tickets above looks [{'quantity': 1}, {'quantity': 4}, {'quantity': 2},] ) if request.method == 'POST': formset = ReserveFormSet(request.POST, initial=tickets) if formset.is_valid(): for form in formset: if form.cleaned_data['quantity'] > 0: # QUESTION: How do I assign the values 'order_reference' & 'ticket_name' before saving the form in the database form.save() print("SAVED.") return render(request, 'events/event_detail.html', {'event': event, 'formset': formset}) forms.py class ReserveForm(forms.ModelForm): class Meta: model = ReservedItem fields = ['ticket', 'quantity'] -
Python27 Django application deployment on Elastic beanstalk "ImportError: Import by filename is not supported"
this question has been raised partially couple of times but every provided solution doesn't seem to fix my problem. Can anyone please help, I've spent many hours trying to figure out the problem. Let me share the directory structure and wsgi.py, manage.py code if anyone can please help? [Only showing necessary files below to explain directory structure ] app_pro .ebextensions 01_packages.config django.config setup_packages.sh .elasticbeanstalk config.yml myapp apps logs templates myapp __init__.py settings production.py local.py eb_settings.py base.py url.py wsgi.py manage.py manage.py import os import sys settings = "myapp.settings.eb_settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) wsgi.py import os import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.eb_settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() django.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "/opt/python/current/app/app_pro/myapp/myapp/settings/eb_settings" PYTHONPATH: "/opt/python/current/app/app_pro/myapp:$PYTHONPATH" "ALLOWED_HOSTS": "*" "aws:elasticbeanstalk:container:python": WSGIPath: myapp/myapp/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "/opt/python/current/app/app_pro/myapp/collectstatic/" And this is the error I've been keep getting. Please help! Application update failed at 2018-06-01T08:46:59Z with exit status 1 and error: container_command 03_migrate in app_pro/.ebextensions/01_packages.config failed. myapp.settings.eb_settings Traceback (most recent call last): File "/opt/python/ondeck/app/app_pro/myapp/manage.py", line 21, in execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/init.py", line 350, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/init.py", line 302, in execute settings.INSTALLED_APPS File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/conf/init.py", line 55, in getattr self._setup(name) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/conf/init.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/conf/init.py", line 99, … -
Duplicated queries with formsets
I'm getting too many duplicated queries in a UpdateView, one from each Formset instances and I don't know how to use prefetch_related with this case. I have one model, Entry, with multiple instances of Boxes (another model). Every box has a Material (third model). So, when the user wants to edit an Entry, if it has 10 boxes, Django will create 10 Duplicated queries to get each material of every box. I've usted prefetch_related before but not with multiple Formsets so I don't know what to do. This is the relevant code: models.py class Entry(models.Model): # No Foreign keys here class Box(models.Model): .... material = models.ForeignKey('Material', on_delete=models.CASCADE) class Material(models.Model: # No Foreign keys here views.py class EntryUpdateView(UpdateView): model = Entry form_class = EntryForm def get_context_data(self, **kwargs): data = super(EntryUpdateView, self).get_context_data(**kwargs) data['materials'] = Material.objects.all() return data def get(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) box_form = BoxUpdateFormSet(instance=self.object) return self.render_to_response(self.get_context_data(form=form, box_form=box_form)) models.py class EntryForm(ModelForm): class Meta: model = Entry fields = ... class BoxForm(ModelForm): class Meta: model = Box fields = .... BoxUpdateFormSet = inlineformset_factory(Entry, Box, form=BoxForm, can_delete=True, extra=0) -
Why should I use Forms.py while using custom user model
Here I am giving my github link for the login using custom user model.Here I've used forms.py.But it works perfectly even I removed forms.py.So why should we use it. https://github.com/NajmathUmmer/customusermodel -
Django: "Object of type 'QuerySet' is not JSON serializable"
I have the following data which I want to pass to JsonResponse. coin_amount = [Portfolio.objects.filter(user = request.user, coin = key['coin']).values('amount') for key in coin_sell_options] print(list(coin_amount)) However this returns a ValuesQuerySet, which is not Json serializable: [<QuerySet [{'amount': Decimal('3.0000000')}]>, <QuerySet [{'amount': Decimal('0.1000000')}]>, <QuerySet [{'amount': Decimal('9.0000000')}]>] That's problematic because I need a list that is JSON serializable. So I need to get a list like this from my ValuesQuerySet somehow: ['3.0000000', '0.1000000', '9.0000000'] -
Django database authentication plugin error
I had a Django project that I had worked on in the past for quite a while. Recently, I tried to reopen it and add some minor changes. What happened is that recently I also reinstalled MySQL(8.0) and of course, recreated my old database. But now when I tried to run the server or any other operation, I get the following error: 2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found. I tried the solution from other post, but it did not work for me. Here is also a full traceback of the error: https://pastebin.com/JqexqTtC -
Django rest framework Reactjs sessions not working
So I have set up Django rest framework as a backend API for an e-commerce website. The website is displayed through a React frontend, which is not served by the django backend. I am currently running both the Django backend and the React frontend from their local development servers (http://127.0.0.1:8000 and http://127.0.0.1:3000 respectively). In the future they will be on separate domains, probably. When I set a session in a view, and read the content in another, this works if I just type in the urls for creating and reading directly into my browser (just for testing purposes). But when I access the backend through my frontend, sessions can not be accessed anymore, or don't seem stored. What will happen is that I get a KeyError when trying to access the data that I set in a previous view. I guess this has to do with something I have read about some time ago, but I find it hard to find the correct information on how to work with this. Does this have to do with the cookie with the session id not being available to the frontend, but only to the backend itself? Main question: I would like to … -
django footer is in middle of page
I'm doing a django project that I gave out of school, but I'm just a beginner. im making a web page, my page footer is in middle of page its my base.html {% block content %} {% endblock %} <footer>...</footer> its my code, I left out the rest. and my home.html {% extends "base.html" %} {% block title %}home.html{% endblock %} {% load staticfiles %} {% block extrastyle %}{% static "css/home.css" %}{% endblock %} {% block content %} {% endblock content %} and i run this page, enter image description here i've tried {% block footer %} <div id="footer">...</div> {% endblock %} in base.html but is doesn't work. same... -
Django - queryset.union return broken queryset : filter() and get() return everything
I use queryset.union to concatenate two querysets of same nature, but using .get() or .filter() on the result doesn't work as espected: >>>foo = obj1.father.all() >>>foo <QuerySet [<Link: l1>, <Link: l2>]> >>>foo.get(pk=0) <Link: l1> >>>bar = foo.union(obj2.father.all()) >>>bar <QuerySet [<Link: l1>, <Link: l2>], <Link: l3>], <Link: l4>]> >>>bar.filter(pk=0) <QuerySet [<Link: l1>, <Link: l2>], <Link: l3>], <Link: l4>]> >>>[l.pk for l in bar] [0, 1, 2, 3] Should I use something else than .union() to concatenate the querysets ? How should I do it ? -
expected str, bytes or os.PathLike object, not InMemoryUploadedFile
I have a method to read a Newick file and return a String in Django framework which is the following: def handle_uploaded_file(f): output = " " for chunk in f.chunks(): output += chunk.decode('ascii') return output.replace("\n", "").replace("\r", "") def post(self, request): form = HomeForm(request.POST, request.FILES) if form.is_valid(): input = handle_uploaded_file(request.FILES['file']) treeGelezen = Tree(input, format=1) script, div = mainmain(treeGelezen) form = HomeForm() args = {'form': form, 'script': script, 'div': div} return render(request, self.template_name, args) Which works fine for normal Newick files but i also have some files which have a string at the beginning of the file. I'm trying to make another method which checks if the file has the following String before it (which is the case in some files): "newick;" and removes the string if found. It works locally but i can't seem to merge them. This is how it locally looks like: def removeNewick(tree_with_newick): for x in tree_with_newick: if x.startswith('newick;'): print('') return x filepath = "C:\\Users\\msi00\\Desktop\\ncbi-taxanomy.tre" tree_with_newick = open(filepath) tree = Tree(newick=removeNewick(tree_with_newick), format=1) which works perfectly when i specify the path just in python so i tried combining them in Django like this: def handle_uploaded_file(f): tree_with_newick = open(f) for x in tree_with_newick: if x.startswith('newick;'): print('') return cutFile(x) def cutFile(f): … -
Django Rest Framework Serializer or any other serializer for neomodel
I am new to neomodel but have been working with drf for a long time. Is there a way to use the drf serializer in neomodel or is there any other way around. How can i serialize the neomodel objects. -
Django REST Framework Serializer validation error
I have the following serializer: class SearchSerializer(serializers.Serializer): category_id = serializers.IntegerField() search_term = serializers.CharField(required=False) I need to validate whether the category with the id exists in the database and retrieve it's value in the view. In order to avoid fetching Category twice, I have added the following validate() to the serializer. def validate(self, data): try: category = Category.objects.get(pk=data['category_id']) except Category.DoesNotExist: raise serializers.ValidationError('Invalid category_id') self.data['category'] = category return data But it leads to an error. When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation. You should either call `.is_valid()` first, or access `.initial_data` instead. Is there a way to do this? -
Integrate Scrapy with Django : How to
I'm still very new in Django I am following this tutorial on how to integrate scrapy and django. the problem is when i am trying to use my own spider it's just wont work. I have tried the spider outside django and it's work just fine, some help will be very helpful. This is my spider.py file import scrapy from scrapy_splash import SplashRequest class NewsSpider(scrapy.Spider): name = 'detik' allowed_domains = ['news.detik.com'] start_urls = ['https://news.detik.com/indeks/all/?date=02/28/2018'] def parse(self, response): urls = response.xpath("//div/article/a/@href").extract() for url in urls: url = response.urljoin(url) yield scrapy.Request(url=url, callback=self.parse_detail) # follow pagination link page_next = response.xpath("//a[@class = 'last']/@href").extract_first() if page_next: page_next = response.urljoin(page_next) yield scrapy.Request(url=page_next, callback=self.parse) def parse_detail(self,response): x = {} x['breadcrumbs'] = response.xpath("//div[@class='breadcrumb']/a/text()").extract(), x['tanggal'] = response.xpath("//div[@class='date']/text()").extract_first(), x['penulis'] = response.xpath("//div[@class='author']/text()").extract_first(), x['judul'] = response.xpath("//h1/text()").extract_first(), x['berita'] = response.xpath("normalize-space(//div[@class='detail_text'])").extract_first(), x['tag'] = response.xpath("//div[@class='detail_tag']/a/text()").extract(), x['url'] = response.request.url, return x this is my pipeline file class DetikAppPipeline(object): def process_item(self, item, spider): item = detikNewsItem() self.items.append(item['breadcrumbs']) self.items.append(item['tanggal']) self.items.append(item['penulis']) self.items.append(item['judul']) self.items.append(item['berita']) self.items.append(item['tag']) self.items.append(item['url']) item.save() And this is the models file in django class detikNewsItem(models.Model): breadcrumbs = models.TextField() tanggal = models.TextField() penulis = models.TextField() judul = models.TextField() berita = models.TextField() tag = models.TextField() url = models.TextField() @property def to_dict(self): data = { 'url': json.loads(self.url), 'tanggal': self.tanggal } return … -
Template language is not being rendered with html
I am new to Django and learning for the first time. I am following a tutorial from youtube. While working with one example given by instructor in video when I tried to imitate that on my system then it isn't working as expected. Following is the html file which I want to render. {% extends "base.html" %} {% block content %} <!DOCTYPE html> <html lang = "en"> <head> </head> <body> <h1>Hellow World!</h1> <p> This is <code> { % verbatim % } {{ html_var }} { % endverbatim % } </code> html coming through </p> <p> { % if num is not None %} Random number is: {{ num }} { % endif % } </p> <p> { % for some_item in some_list % } { % if some_item | divisibleby = "2" % } Even number {{some_item }} <br> { % % } { % endfor % }</p> <p>Some item is {{ some_item }}</p> </body> </html> {% endblock content %} and output is the following: MuyPicky.com Home About Contact Hellow World! This is { % verbatim % } { % endverbatim % } html coming through { % if num is not None %} Random number is: { % endif … -
How do we get multiple values from a single django orm query?
id created_at team 1 2018-02-14 10:33:46.307214+05:30 1 2 2018-02-24 10:41:40.307681+05:30 1 3 2018-03-14 12:00:02.748088+05:30 1 4 2018-03-12 18:05:33.598297+05:30 3 5 2018-03-12 18:04:00.694774+05:30 3 6 2018-04-14 11:24:48.554993+05:30 3 7 2018-04-14 11:42:27.442441+05:30 3 8 2018-05-11 15:53:21.528813+05:30 3 9 2018-05-08 15:49:58.684201+05:30 3 How can we get from a single query current month & team = 3 count, last month & team = 3 count? -
How do i unstage/revert unapplied migrations?
I would like to unstage (analogus to git) all the unapplied migrations. showmigrations gives : blog [X] 0001_initial [X] 0002_auto_20180509_1033 [ ] 0003_auto_20180531_1951 [ ] 0004_auto_20180531_2039 [ ] 0005_post_tags I have 3 unapplied migrations. I assume they don't have any effect on my database tables right now? (because they are not applied, please correct me if i am wrong). I have read other answers and didn't find an easy way to just unstage all the unapplied migrations (for example : git reset command ). Docs talk about makemigrations being analogous to git add and migrate being analogous to git commit. ( I also didn't get how i have 3 unapplied migrations, isn't all unapplied migrations should be in a single file? Like till you don't commit, you are just staging the changes, so everything should be in a single file? In such scenario, when i use migrate command, will all the migrations be applied? ) -
Is there a way to link input fields from HTML to the ACTUAL form fields used in DJANGO
Right now I'm stuck between two things: Either I have a login form that works but isn't exactly what you call visually appealing and one that looks flawless but doesn't do anything. (I know quite the situation) As shown the one up top is clearly quite the looker (sarcasm*), but I want the hideous one at the bottom to work. For the for up top, I just used {{ form }} tag and have at one point my code looked like this: <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} {{ form.username.label_tag }} {{ form.username }} {{ form.password.label_tag }} {{ form.password }} <input type='submit' class='btn btn-primary btn-block' value='{{ title }}' /> </form> But again this doesn't give me the look I want. As of right now, to get the non-functional (but pretty) form look at the bottom I'm using the code for the bootstrap template signin (signin.css included in my base template). This is what my form.html looks like right now: {% extends 'accounts/base.html' %} {% block main_content %} <div class="container"> <div class='col-sm-6 col-sm-offset-3'> <form method='POST' action='' enctype='multipart/form-data' class="form-signin">{% csrf_token %} {{ form}} <h2 class="h3 mb-3 font-weight-normal">Please Sign In</h2> <input type="username" id="inputUsername" class="form-control" placeholder="Username" required autofocus> <input type="password" id="inputPassword" class="form-control" placeholder="Password" required> … -
django drf return zipfile convert asp to django
asp code public dynamic Gz(string id) { string dir = emoPath + "/Emo/EmoFiles/z/"; var path = Path.Combine(dir, id + ".zip"); if (!FileExist(path)) { return "not found."; } ActionResult result = base.File(path, "application/x-zip-compressed"); return result; } django code view.py class Gz(viewsets.ModelViewSet): queryset = "" serializer_class = BaseSerializer def list(self, request, *args, **kwargs): path = os.path.join( settings.MEDIA_ROOT, "Emo", "EmoFiles", "z") file = open(os.path.join( path, kwargs.get("id") + ".zip")) resp = HttpResponse(file, content_type="application/x-zip-compressed") return resp settings.py MEDIA_URL = '/Media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'Media') urls.py urlpatterns = [ url(r'^', include(router.urls)), url(r'^do/gz/(?P<id>.*)$', Do.Gz.as_view({"get":'list'}) ,name="GroupZip") ] raise error FileNotFoundError: [Errno 2] No such file or directory: 'D:\\WebSite\\Mysite\\Media\\Emo\\EmoFiles\\z\\test.zip' that file is exist why not found and i can return zipfile to HttpResponse is right? -
404 error when setting up views in django 1.11 polls app
I am using MacOS HighSierra, django 1.11, and python 2.7.14. Whenever I set up the views and run the server, polls/1 returns a 404 error. I am following the official django course. The page says this - Page not found (404) Request Method: GET Request URL: http://localhost:8000/polls/1 Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^$ [name='index'] ^polls/ ^(?P<question_id>[0-9]+)/$, [name='detail'] ^polls/ ^(?P<question_id>[0-9]+)/results/$, [name='results'] ^polls/ ^(?P<question_id>[0-9]+)/vote/$, [name='vote'] ^admin/ The current path, polls/1, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Django translations not getting translated on dictionary values
I'm using a ordered dict like this from django.utils.translation import ugettext as _ 'alumni': OrderedDict([ ('profession', { 'name': _('Occupation'), 'field': 'profession', 'key': 'profession', 'type': 'text' })]) And I've the translation on the file like msgid "Occupation" msgstr "Meslek" But the transaltion is not working. I'd tried it like this on shell and it seems to be working. In [1]: from django.utils import translation In [2]: translation.activate('tr') In [3]: translation.gettext('Occupation') Out[3]: 'Meslek' All other translations are working fine, Issue is only with the ones defined on dict. Help please. -
Django Form Field Placeholder text using custom template tag
I've looked everywhere for a simple way to add a placeholder text element to a Django Form input field. There are several examples that look to modify the model forms or use add-ins. I've pieced together several disparate examples to come up with the following... This is my first custom template tag and before I add a lot of template changes I'd like to verify that this is correct: templatetags/placeholder.py from django.template import Library import re register = Library() def placeholder(value, token): value.field.widget.attrs["placeholder"] = token return value register.filter(placeholder) templates/my_app/customer_form.html (implementing Bootstrap) <div class="container"> <h5>Add a New Customer</h5> <form method="post">{% csrf_token %} <table class="table table-borderless table-sm table-half"> <tr><td>{{ form.customer | placeholder:'Customer Name' }}</td></tr> <tr><td>{{ form.address1 | placeholder:'Address' }}</td></tr> <tr><td>{{ form.address2 | placeholder:'Address' }}</td></tr> <tr><td>{{ form.city | placeholder:'City' }}</td></tr> <tr><td>{{ form.state | placeholder:'State' }}</td></tr> <tr><td>{{ form.zip | placeholder:'Zip' }}</td></tr> </table> <input type="submit" class="btn btn-outline-primary" value="Add" /> </form> </div> Firefox A couple of things I noted: a) It looks like I can (i) use field tags in the custom tag and (ii) I can use plain text. b) No space between the custom tag name and the value. If there is a space it throws TemplateSyntaxError that placeholder requires 2 arguments, 1 provided. … -
Django Class Based Listview with two filtered individual lists
Hi I am trying to create a page that uses model Item that has a model field called data_type with an integer choice selection of either 1 or 2. I currently have a Listview page and I am trying to create two lists, one that shows Items with data_type=1 and the other that shows data_type=2. 1 represents models and 2 represents scripts, if that helps? Here is my views.py class ItemListView(generic.ListView): context_object_name = 'model_list' queryset = Item.objects.filter(data_type='1') context_object_name = 'script_list' queryset = Item.objects.filter(data_type='2') template_name = 'item_list.html', Item_list.html <h3 class="text-muted text-center mt-4">Models</h3> <hr> <div class="container"> <div class="row mt-4"> {% if model_list %} {% for item in model_list %} <div class="col-md-3"> <div class="card card-primary card-effects p-2 mb-3 mt-4"> <a href="{% url 'portal:item_detail' item.pk %}" class="card-full-link"> <img class="card-img" src="{{ item.image.url }}" alt="Generic placeholder image" width="225" height="185"> <div class="card-body"> <p class="text-muted"> {{ item.get_data_type_display }}</p> <h4 class="text-left"> {{ item.name }}<span class="text-blue">Ξ{{ item.price }}</span></h4> </div> </a> <!-- <p><a class="btn btn-success" href="#" role="button">Learn more &raquo;</a></p> !--> </div> </div> {% endfor %} {% else %} <p>There are no items in the database.</p> {% endif %} </div> </div> <h3 class="text-muted text-center mt-4">Scripts </h3> <hr> <div class="container"> <div class="row mt-4"> {% if script_list %} {% for item in script_list %} … -
Django and TinyMCE: NameError: name 'url' is not defined
I am trying to get TinyMCE working in Django. Here is what I did: Using this package as a reference: django-tinymce4-lite Successfully ran pip install django-tinymce4-lite; package installs fine Added tinymce to INSTALLED_APPS in settings.py Then here it gets tricky: Add tinymce.urls to urls.py for your project: urlpatterns = [ ... url(r'^tinymce/', include('tinymce.urls')), ... ] When I do this, I get this error: url(r'^tinymce/', include('tinymce.urls')), NameError: name 'url' is not defined I have tried the following: Restarting django Instead of placing this in my project's urls.py I have tried my app's urls.py I have tried to convert this to "path('tinymce/', include('tinymce.urls'))," because all other entries use 'path' and not 'url', but that didn't work either (ModuleNotFoundError: No module named 'tinymce.urls) I have tried another tinymce plugin None of this helped. Any suggestions? -
Django booking Car on avialaible time
I want to book a car with available time and available time vary day by day . How do i change available times and having multiple time to choose and accept booking . Dont know how to do