Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I Migrate Django App on Heroku from git deploy to container deploy?
Now that Heroku supports deploying an app straight from you docker image. I would like to migrate my existing Django app to a Container based app, but without loosing all the configuration already done (postgreSQL, mainly) Is there a easy way to migrate to a container? I have searched a lot and couldn't find any tutorial that did not assume that you where creating a new app from scratch. Can it be done? -
Django - collectstatic inside CI pipeline
I’m using the library django-storages to upload my statics into S3. In local when collectstatic I notice that only modified files are uploaded but inside my CI pipeline it always upload every single file even if there’s no change in it. I have more than 2000 files which means 2000 writes to S3 per pipeline. Could it be related to md5? Any help very appreciated -
TypeError: expected string or buffer when trying to migrate database
models.py from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.db import models from django.utils.text import slugify class Post(models.Model): title = models.CharField(max_length = 120) image = models.ImageField(null=True,blank=True) draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) Updated = models.DateTimeField(auto_now=True,auto_now_add=False) Timestamp = models.DateTimeField(auto_now=False,auto_now_add=True) def __unicodde__(self): return self.Title def __str__(self): return self.title def get_absolute_url(self): #return 'posts/%s/' %(self.id) return reverse('posts:detail', kwargs={'id':self.id}) class Meta: ordering = ["-Timestamp","Updated"] and terminal : jayu@broadwell-gt2:~/Desktop/trydjango19$ python manage.py migrate Operations to perform: Apply all migrations: admin, contenttypes, posts, auth, sessions Running migrations: Rendering model states... DONE Applying posts.0002_auto_20180526_0745...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) /migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 221, in add_field self._remake_table(model, create_fields=[field]) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 103, in _remake_table self.effective_default(field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 210, in effective_default default = field.get_db_prep_save(default, self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/init.py", line 728, in get_db_prep_save prepared=False) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/init.py", line 1301, in get_db_prep_value value = self.get_prep_value(value) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/init.py", line 1296, in get_prep_value return self.to_python(value) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/init.py", line 1260, in … -
Django React axios post request: how to get csrftoken cookie?
I am using Django rest framework as my backend (api), and React for frontend. Now I want to POST form data to the backend. I want to use csrf protection, because of safety. So I am trying to manually set the csrf header for my axios request using the 'csrftoken' cookie send by Django. For this I am using the method as recommended in the Django documentation: Link The problem that I am walking into is that I need the cookie on my machine before I can add it to the header, and I don't know how to get the cookie to be returned by Django. Main question: how do I get the 'csrftoken' cookie to my machine? (While React is rendering the form without (initially) needing any communication with the Django backend) Also, if you see any problems with my code, I'd like to know that. My code Here is my current code, and I'll describe the things I have tried: django views.py: from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def contact(request): if request.method == "POST": print(request.data) if request.method == "GET": return request Initially I only had the POST part of the above function. But since I seem to have no … -
How to auto increment a model date field Django
I want to auto increment a date field in my model on a particular day. My model id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular client across the website") client = models.ForeignKey('Client', on_delete=models.CASCADE, null=True, help_text="The client") last_pay = models.DateField(null=True, blank=True, help_text="The last time the client paid") due_pay = models.DateField(null=True, blank=True, help_text="The time for the next pay") amount = models.IntegerField(null=True, blank=True) Proposed function def increment_month(self): if self.last_pay == date.today(): self.last_pay = self.last_pay + datetime.timedelta(weeks=4) self.save() -
print statement inside celery task not working
I need to debug celery task to see whether it is working properly or not, So I put some print statements inside tasks.py. While running the project I have observed that task successfully runs but doesn't print anything on the console. How can I debug the celery task. -
Django filter ModelMultipleChoiceFilter: __init__() takes at least 2 arguments (3 given)
I have this code: class MyFilter(FilterSet): transcribe_by = django_filters.ModelMultipleChoiceFilter( name='transcribe_by', label='Transcribed By' ) and I am getting this error when opening the page: __init__() takes at least 2 arguments (3 given) What am I doing wrong? -
Stop/Start celery task over UI django
Is there a possibility to utilize a button in django template so I can stop/start a celery task? I realize that I can use the Abortable task, for aborting function, and I can do some boolean to make it run again, but I'm not sure how to connect it with a button, any ideas, thanks. -
How to cache views with Redis separately for mobile and desktop?
I want to cache the view using cache_page function. I'm using two different HTML template for mobile and desktop. The problem is, if I visit the URL firstly from desktop the page is caching and when visit from mobile, django shows me the desktop HTML template not the one for mobile. How I can cache these two templates separately for mobile and desktop? This is how I cache the view: from django.views.decorators.cache import cache_page urlpatterns = [ url(r'/', cache_page(60 * 60)(HomeView.as_view())), ] My View: class HomeView(TemplateView): template_name = 'desktop/blog/homepage.html' def get(self, request, *args, **kwargs): # Use mobile template for mobile devices. if request.device['is_mobile']: self.template_name = 'mobile/blog/homepage.html' return super(HomeView, self).get(request, *args, **kwargs) I want to cache entire page, not the querysets only. -
Slow serialization in django rest framework
I'm trying to figure out why django rest framework's ModelSerializer is so slow. I'm aware of the problem with N+1 queries, it's not the case. I have a super simple model that has only numbers and strings. Profiling shows that my code spends most of the time inside Serializer::to_representation() method which does not make any database queries. The weird thing is that time spent inside to_representation method is sometimes 0.00001s (which is around what I would expect), sometimes 0.001s and sometimes (very rarely) 0.05s. The time does not correlate with the size of the object being serialized (they are all around the same size in my case). Serialization of 300 objects takes around 1s. My hand-written serializer which simply writes an obj to json string getting all fields manually instead of MySerializer(obj).data does the job in 0.05s which is comparable to what I would expect given 0.00001s spent inside to_representation. What may cause to_representation method work so slowly sometimes and how can I make my serializer faster? -
django-filer: Cannot add foreign key constraint when applying migrations
I asked this question on the django-filer Google Group but didn't get any answers so now I am trying here: I am trying to install django-filer v. 1.3.2. I have installed dependencies and applied their migrations: Django 1.8.4 django-mptt 0.7 easy_thumbnails 2.3 django-polymorphic 1.3.1 Pillow 2.9.0 When I apply the migrations for django-filer I get this error for the 0001_initial migration: django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') Looking at the migration, I found that the problem occurs when creating foreign keys to my user model, fx. for the FolderPermission model: ('user', models.ForeignKey(related_name='filer_folder_permissions', verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True)) If I remove lines that try to create foreign keys to the user model, the migration is applied correctly. I use a custom user model called email_username and the users are found in the email_username_user table. I have verified (by printing the variable when applying the migration) that setting.AUTH_USER_MODEL is correct when the migration is applied. I don't get why the migration cannot create foreign keys to this table. Any ideas? -
is there any two way binding support in django code with html?
i search and worked the most of the answer all around the web to make the data refresh in the html(with django) without page refresh for example when click button in django html it refresh the page so how to make the data refresh without calling the page refresh(using href url), is django support two way binding like angular4 or etc ? Thanks -
Receive a Post form and return the query result (db is read-only)
I'm new in django, I'd like your help to receive a post from the html form and process it on the view to return only the selected option. HTML monitoring.htmlenter image description here <form action="{ %url 'show_list' %}" method="post"> <div class="form-row align-items-center"> <div class="col-auto my-1"> <select class="custom-select mr-sm-2" id="inlineFormCustomSelect" name="shift"> <option selected>Shift 1</option> <option value="1">Shift 1</option> <option value="2">Shift 2</option> <option value="3">Shift 3</option> <option value="ALL">ALL</option> </select> </div> <button type="submit" value="Submit" class="btn btn-info">Search</button> </div> </form> Then.. If I selected the Field Shift = 1, return it on the views.py views.py def show_list(request): query = my_custom_sql(self='my_custom_sql') query2 = my_custom_sql2(self='my_custom_sql2') myDate = datetime.now() return render(request, 'monitoring.html', {'query': query, 'query2': query2, 'date': myDate}) Here's the models.py def my_custom_sql(self): with connection.cursor()as cursor: cursor.execute(""" select A.WORK_YMD, A.SHIFT_CODE, --A.LINE_CODE, B.LINE_NM, A.MODEL_NM, A.SMD_INSP_QTY, A.SMD_RETEST_DEFT_QTY, (A.SMD_RETEST_DEFT_QTY / A.SMD_INSP_QTY * 1000000) AS DEF_INDEX_PPM from TBS_QM_TOTAL_PROC_DEFT A, TBM_MD_LINE B where --WORK_YMD = '20180410' A.WORK_YMD = TO_CHAR (SYSDATE,'yyyymmdd') AND A.LINE_CODE = B.LINE_CODE AND A.SMD_INSP_QTY > 0 AND A.SHIFT_CODE = '1' ORDER BY DEF_INDEX_PPM DESC, B.LINE_NM ASC """) row = dictfetchall(cursor) return row -
Django-ReactJS WebApp - development and prod
I'm trying to development a new web app with Django and reactJS. I used create-react-app of Facebook API during development reactJS side. Now the issue occur in development env, Django app run on port 8000, for example, and reactJS run on port 3000. In Prod situation, the Django server should contain the templates and the static files as well. The question is simple - There is a way to run, on dev env of course, the react code from the Django app, like to always build the new html and js minified into the Django project and than I can use only the Django project server and than I don't need to change the path of the api calls and use only relative path for this, I don't really need the On Fly reload and those features of create-react-app not that important for me, I just try to create simple dev env which can work as prod without different configuration issue when deploying app, exactly like of AngularJS works, you just use relative path and than you run the html files from your backend side and no need angular development server as well. I read about people who always build … -
Django annotate distinct
I have Unit and Slot related models: class Slot(models.Model): unit = models.ForeignKey( 'storage.Unit', on_delete=models.CASCADE, verbose_name=_('unit'), related_name='slots', ) start_date = models.DateField( _('start date'), null=True, blank=True, ) This works fine: models.Unit.objects.annotate( available_from=Min('slots__start_date') ).order_by('id') But this: models.Unit.objects.annotate( available_from=Min('slots__start_date') ).order_by('id').distinct('id') ends up with Unable to get repr for <class 'modeltranslation.manager.MultilingualQuerySet'> Does anybody have an idea what is wrong here? Any hints how to debug? -
Cannot select Image File using djangocms-filer
I hope someone can help out with this one. I have been using djangocms to build a simple frontend centric website for a client so they can maintain their own content. There is nothing fancy in this setup. Just a few template.html files, a little css and djangocms to pull it all together. There are no other forms, models, views or anything at this stage. Just pure djangocms. Originally I was working with django 1.8.6 and the image picker seemed to work fine. I could upload my files and next to each one there is a selector icon which works and all was great. See below image. This was using cmsplugin-filer. Then I tried to upgrade the website to Django version 1.11.13 and I started to run into this problem. The file select that you see above is no longer available to the user. I have spent days working on this and in my travels I found that apparently cmsplugin-filer is now deprecated. So I removed it and switched to the recommended djangocms-filer install thinking that might solve my problem...but no. After many many hours of head scratching I figured it must be something in my project throwing things out, … -
List not filling properly
So, i have this bit of code that is supposed to go through a list of products, link them up with their price and then display the product with the price as a 'display item' to the user on a webpage for product in product_list: p = PricedProduct.objects.filter(proid=product) p.order_by('date') dp = DisplayProduct dp.proid = product.id dp.proname = product.productname print(product.productname) dp.proprice = p[0].value displaylist.insert(0,dp) this is where i link up the item to the price the 'print' method is currently showing: Apple Banana However when i run: for dp in displaylist: print(dp.proname) it shows: Banana Banana Can anyone tell me why this is happening, as its causing my web page to just show 2 bananas instead of an apple and a banana -
Django Forms adding unlimited additional formsets while filling out form
I've got a form for two models, my Offer model, which is my main model and my Item model which has a one-to-many relationship with the Offer. Now I have a TemplateView which I use to create new Offers, the form for these Offers is build by my Offer-Form and my Item-Offer. The user has always one Offer Form and underneath that form he should have always 1 Item-Form BUT also be able to simply add another Item-Form underneath the existing, so that he can unlimited items to the offer. But I just don't seem to find out how to do this? My Item-Form is a django formset_factory() and right now I'm only able to show one form. I know you can add the parameter extra=X, but I want it to be dynamically. Does someone know how to do that? Is it even possible with django? Or do I have to use Javascript for that? My Code looks like this: views.py class OfferCreateView(TemplateView): model = Offer template_name = 'offers/offer_create.html' form_class = OfferCreateForm def get(self, request, *args, **kwargs): form = OfferCreateForm(request=request) itemformset = formset_factory(ItemCreateForm, extra=3, can_delete=True) item_form = itemformset() return self.render_to_response({ "form": form, "item_form": item_form }) Forms.py class OfferCreateForm(forms.ModelForm): class Meta: … -
python - Django built in login view not redirecting to next
I am using django auth views for authentication but after successful login it should try to redirect the user to the next GET param but it is redirecting to LOGIN_REDIRECT_URL only! here is my url url(r'^login/$', auth_views.login, {'template_name': 'accounts/registered/login.html',}, name='login'), in my setting.py LOGIN_REDIRECT_URL = '/' when a unauthenticated user wants to visit dashboard it automatically redirected to login page with next param http://127.0.0.1:8000/accounts/login/?next=/accounts/dashboard/ but after successful login it redirects it to http://127.0.0.1:8000/ it should redirect it according to next param. -
Django 2 - pagination does not propperly work
first of all, thank for reading my question :) I'm currently working on a small Blog platform and i want to implement pagination for all my Post elemets. therefor i modified my view.py and the actual .html template. The problem now is that each time i visit the post_list.html page and i click on next nothing happends.. What the matter here: post_list.html {% extends 'quickblog/base.html' %} {% block content %} {% for post in posts %} <br> <div class="post"> <h1><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h1> <p>{{ post.text|linebreaksbr }}</p> <div class="date"> <a>published by: {{ post.author }}</a><br> <a>published at: {{ post.published_date }}</a><br> <a>tags: {{ post.tag }}</a> </div> </div> {% endfor %} <div class="pagination"> <span class="step-left"> {% if posts.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ posts.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ posts.number }} of {{ posts.paginator.num_pages }}. </span> {% if posts.has_next %} <a href="?page={{ posts.next_page_number }}">Next</a> <a href="?page={{ posts.paginator.num_pages }}">Last &raquo;</a> {% endif %} </span> </div> {% endblock %} views.py ... def post_list(request): list = Post.objects.all() paginator = Paginator(list, 15) # Show 15 Posts per page page = request.GET.get('posts') posts = paginator.get_page(page) return render(request, 'quickblog/post_list.html', {'posts': posts}) ... -
Two Facebook App Authentications in Django
I am creating a delivery app and created two facebook apps one for the driver and the other for the customers. Now I'm trying to authenticate to my server but, only one app seems to work when I add both Facebook Auth Keys and Secrets to my Settings.py file, only one works. Is it possible to have both the driver and customer authenticate via different the different apps? -
Dictionary as choices in choicefield inside forms.py
Im giving the choices for a choicefield in forms.py as a dictionary. I've imported my dictionaries page as dicto. da=[dicto.country_array] country = forms.ChoiceField(choices=da,widget=forms.Select(attrs={'class':'form-control m-b', 'id':'country_sel'})) In the template, I'm getting ValueError: too many values to unpack (expected 2). How do i get the choices correctly? -
VSCode Django import warning
trying out the VSCode editor, but immediately ran into a problem. I have a django 2.0.5 installation in a virtual environment, however, the out of the box linter yells at me. This is one of the errors (better said, warnings, because the server is running fine, and everything gets displayed properly) E0611:No name 'path' in module 'django.urls'enter image description here I'm sure it's easy to solve, but it's beyond me at this point -
django-user-accounts don't redirect after successful login
I use django-user-accounts app in my project. I can't understand strange behavior. When user try to login nothing happens. After successful login I want to redirect user. Why ACCOUNT_LOGIN_REDIRECT_URL setting don't work? settings.py: ACCOUNT_LOGIN_REDIRECT_URL = reverse_lazy('dashboard') Also I tried to use LOGIN_REDIRECT_URL = reverse_lazy('dashboard') but result was the same. urls.py: url(r"^account/", include("account.urls")), templates/account/login.html: <form method="post" action=""> {% csrf_token %} {% render_field form.username|add_class:"form-control" placeholder="Username" %} {% render_field form.password|add_class:"form-control" placeholder="Password" %} <input type="hidden" name="next" value="{{ next }}"/> </form> In console I see next: [26/May/2018 14:31:38] "GET /account/login/ HTTP/1.1" 200 4018 -
Bootstrap Grid Doesn't work as expected
I want my main content and Sidewidget in the same row. With my knowledge of bootstrap grid, I tried to make this work but the sidewidget is stacking below the content and not in the sides. Here is the required snippets. body.html <!-- Navigation --> {% include 'nav.html' %} <!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-8 "> {% block content %} {% endblock %} </div> <div class="col-lg-4"> {% block sidewidget %} {% endblock %} </div> </div> </div> <!-- Bootstrap core JavaScript --> <script src="{% static 'js/jquery.min.js' %}"></script> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'js/tinymce/tinymce.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/tinymce/custom.js' %}" ></script> nav.html <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="#">Start Bootstrap</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'add' %}">Add Article</a> </li> {% endif %} </ul> </div> </div> My {% block content %} {% for post in posts %} <h2 class="mt-4">{{post.title}}</h2> <!-- Author --> <p class="lead"> by …