Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
html file not extending
I extended the base file and the directory is correct and Iam still getting normal style. {% extends "music/base.html" %} {% block body %} {% load staticfiles %} <img src="{% static 'music/image/Robot-PNG-File.png' %}" class="rounded-circle" alt="face" style='max-height:200px'><br> <h2>{{album.album_title}}</h2> <h3>{{album.artist}}</h3> <ul> {% for songs in album.song_set.all%} <li>{{songs.song_title}}- {{songs.file_type}}</li> {% endfor %}<br> </ul> {% endblock %} -
Django Messages working only after manual page refresh when I try display error about existing user
In my Django project I want to use Django Message ( from django.contrib import messages) to display error when user or email exist. Unfortunately my views not working. HTML: {% for message in messages %} <p>{{ message }}</p> {% endfor %} views.py: def account_signup(request): if request.method == 'POST': nick = request.POST['nick'] email = request.POST['email'] password = request.POST['password'] user_model = get_user_model() if user_model.objects.filter(username__iexact=nick).exists(): messages.warning(request, 'Please correct the error below.') return render(request, "account/account_signup.html", context={'is_taken_email': email, 'messages': messages}) if user_model.objects.filter(email__iexact=email).exists(): messages.warning(request, 'Please correct the error below.') return render(request, "account/account_signup.html", context={'is_taken_email': email, 'messages': messages}) user = User.objects.create_user(username=nick, email=email, password=password) user.save() return HttpResponse(status=202) else: """Return template with sign up page.""" return render(request, "account/account_signup.html") I cant find a reason. Thanks in advance! -
Set id for None object
I have model for my comments: class Comment(models.Model): body = models.CharField(max_length=255, verbose_name="comment") message = models.ForeignKey(Message, on_delete=models.CASCADE, related_name="comments", verbose_name="message") author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="author") parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', verbose_name='parent', default=None) posted = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="posted") edited = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name="edited") def __str__(self): return self.body def get_create_url(self): return reverse('wall:add-comment', kwargs={'id': self.message.id, 'pk': self.parent.id}) def get_update_url(self): return reverse('wall:edit-comment', kwargs={'id': self.id}) I understand that my question is probably stupid, but I need to get an id for parent.id if parent is None. Help pls -
ajax + django, form with success url
I'm working on posting django form wrapped in modal using ajax. It seems that i got it working, but I'd like to ask about one thing. When I get my form and then post it I expect getting back to previous view and reloading it in order to display all operations with the newest one included. Below you can see how it looks like under the hood: [16 / Feb / 2018 12:22:52] "GET /expenses/new_operation/ HTTP/1.1" 200 1135 [16 / Feb / 2018 12:23:01] "POST /expenses/new_operation/ HTTP/1.1" 200 21 [16 / Feb / 2018 12:23:01] "GET /expenses/manage_operations/?csrfmiddlewaretoken=0wiGRic6QGlqSyVIv36f02bQ4CeJk81WfN9waSoiVrSaPPnLx1HbS0YapFypTtdk&account=1&type=-1&category=2&date=2001-11-11&amount=111 HTTP/1.1" 200 6313 What I don't get is why in GET /expenses/manage_operations/ request all the data from the previously posted form is being attached. In my view I have set success_url: class OperationCreate(CreateView, OperationMixIn): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def get_form_kwargs(self): ( ... ) return kwargs def form_valid(self, form): ( ... ) if self.request.is_ajax() and self.request.POST: form.save() return JsonResponse({'result': 'success'}) return super(OperationCreate, self).form_valid(form) def form_invalid(self, form): if self.request.is_ajax() and self.request.POST: form.save() return JsonResponse({'result': 'error'}) return super(OperationCreate, self).form_invalid(form) Here is my main javascript code reposible for handling modal and new operation button: <script type="text/javascript"> $(document).ready(function () { $(document).ajaxSuccess(function () { … -
Installing Channels: Python Django version compatibility
The Django app compiles, but when I try to run it: (virtualenv) root@computer:path# python manage.py runserver 0.0.0.0:8000 It gives error: File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/channels/routing.py", line 75, in resolve_routing raise ImproperlyConfigured("Cannot import channel routing %r: %s" % (routing, e)) ImproperlyConfigured: Cannot import channel routing 'codebench.routing.channel_routing': cannot import name ProtocolTypeRouter According to this https://github.com/VincentTide/django-channels-celery-example/issues/1 It maybe related to Python version, so I did: (virtualenv) root@computer:path# alias python=python3 (virtualenv) root@computer:path# python -V Python 3.5.2 (virtualenv) root@computer:path# python manage.py runserver 0.0.0.0:8000 Traceback (most recent call last): File "manage.py", line 3, in <module> import eventlet ImportError: No module named 'eventlet' (virtualenv) root@computer:path# pip install eventlet Requirement already satisfied: eventlet in /root/.virtualenvs/codebench/lib/python2.7/site-packages Requirement already satisfied: greenlet>=0.3 in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from eventlet) Requirement already satisfied: enum-compat in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from eventlet) Requirement already satisfied: enum34 in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from enum-compat->eventlet) Now I stuck at: ImportError: No module named 'eventlet' I have the following packages installed: channels==1.1.6 daphne==1.4.0 Django==1.9 eventlet==0.20.0 -
How to print in template something when queryset build with union() changes?
I have two queryset: q1 and q2. I make a union of them with q1.union(q2) Now, when I print in template the queryset with a for loop, how can I print something between the two querysets? Something like: Featured results (q1 forloop) Other results (q2 forloop) Why I thought to use union instead of separated querysets? Because I want only one pagination for both Thank you -
Unapply the effect of 'makemigrations' in django
Is there anyway I can unapply the effect of command python manage.py makemigrations <app>? What I was trying to do- I have 3 apps, which have models interdependent on each other(app2 depends on app1, app3 depends on app2, app1 depends on app3). So to remove the circular dependency I removed fields from app1(which depend on app3) and use python manage.py makemigrations <app> for each app separately then python manage.py migrate. Then add those dependent fields in app1 and again use the above commands to have full tables. The issue I forgot to remove the dependent fields in app1 and used makemigrations which also worked fine. But when I am using python manage.py migrate it is giving me the CircularDependency error, I want to undo the effect of makemigrations command. The are answers about removing migrations which happens when your tables are created, but in my case I am stuck before that. -
How add varriable from funсtion to modelform
I try to transfer a new variable urls from a function to a ModelForm. In the letter, the variable comes, but in the form - saving an empty string. models.py class Order(models.Model): name = models.CharField(max_length=25, verbose_name="Имя*") phone = models.CharField(max_length= 20, verbose_name="Мобильный телефон*") email = models.EmailField(max_length=25, verbose_name="Электронная почта*") text = models.TextField() urls = models.URLField() views.py def viewperson(request, slug): trainer = Trainer.objects.get(slug = slug) urls = (reverse('trainers:viewperson', args=[slug])) if request.method == 'POST': model_form = ModelOrderForm(request.POST) if model_form.is_valid(): subject = "New order" phone = model_form.cleaned_data['phone'] name = model_form.cleaned_data['name'] text = model_form.cleaned_data['text'] email = model_form.cleaned_data['email'] recipients = [mail@gmail.com'] message = name + " " +" "+ phone + " " + "site.com"+urls +" "+ text if result['success']: try: model_form.cleaned_data['urls']=urls #Here i try to send urls in forms urls-field instance = model_form.save() send_mail(subject, message, email, recipients) return redirect('thanks_for_order') except BadHeaderError: return HttpResponse('Invalid header found') else: messages.error(request, 'Error reCAPTCHA. Tray again.') return redirect('trainers:viewperson' , slug=slug) else: model_form = ModelOrderForm() return render(request, "trainer_person.html", {'trainer':trainer, 'model_form':model_form,}) -
How to make Django migrations on Google Cloud Platform?
I would like to host my app on Google App Engine and have a Google SQL instance for the database. The main part of the app is an API built with Django Rest Framework. I asked Google Cloud Support about the best practices of making migrations in production when I need to modify the database's schema. Since I am new to web development, perhaps any experts here have similar experience and can verify if the suggested process is something what I can really follow? For database migration best practice, you could create a separate development/test/backup instance of your Cloud SQL database. Let's say for example your DB instance for production is DB1, create a dev instance namely DB2 that has all the tables of DB1. After that, configure your app to point DB2 instance temporarily. Please make sure that both instances are in sync and updated. Then, deploy a new version of your app that points to DB2 so you can update DB1 (add new tables, columns) as your official database instance in the production environment. Then you can point it again to DB1 and update DB2. -
Angular 4 with Django as backend
how can we link frontend and backend of an application which will be using Angular 4 and Django. -
Using django CSRF middleware with views returning JsonResponse
I want to use CSRF middleware with API Views in Django. Here is a demo view I want to use CSRF with, I am confused how to integrate CSRF here. def login(request): try: if len(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))==1: print(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password']))) return JsonResponse({'exit':'0','msg':'Success'}) return JsonResponse({'exit':'2','msg':'User Invalid'}) except Exception as e: return JsonResponse({'exit':'10','msg':'Unknown Error Occured'}) Any help or suggestions will be appreciated. Thanks. -
Djongo, put mysql object id into mongodb listfield from admin
We are using Djongo drivers for django and mongodb compatibility. We have to insert into a Mongodb document a ListField that contains multiple Mysql object pk (as integer or string), obviusly from the admin interface. There's a way? Just for info, without that ListField all work properly and the database router is configured. Thanks all EXAMPLE Mongo document: class MongoDocument(models.Model): field1 = models.CharField(unique=True, max_length=100) LISTFIELD = models.SOMETHING() field3 = models.CharField(max_length=40,unique=True,default=uuid.uuid4) fieldN = models.BooleanField(default=True) class Meta: abstract = True Mysql table: class MysqlTable(models.Model): field1 = models.DecimalField() field2 = models.CharField() field3 = models.CharField() fieldN = models.IntegerField() -
Django: TestClient, cookie detection not working, even though they are supplied
I have a view that contains the following code: language = 'nl_BE' language-cookie = self.request.COOKIES.get('PreferredLanguage') if language-cookie and language-cookie != 'nl_BE': language = 'fr-FR' (...) context['iframe_url'] = language_adapted_url_intro + language + language_adapted_url_outro I am writing tests for our program, and this is the test that is supposed to test the code above. class TestStoreListView(TestCase): def setUp(self): self.client = Client() def test_language_cookie_detection_FR(self): self.client.cookies = SimpleCookie({'Name': 'PreferredLanguage', 'Value':'fr_BE'}) response = self.client.get(reverse('store_appointment')) self.assertTrue('fr-FR' in response.context['iframe_url']) yet this test keeps failing with the following error: self.assertTrue('fr-FR' in response.context['iframe_url']) AssertionError: False is not true But how can this be? The cookie is supplied and the if/else in the view is simple enough. Other tests verify that a context['iframe_url'] is indeed returned (but with nl_NL as its 'language'. Does anyone know what I am doing wrong? -
How can I create a personal for each account in django ? Note: not in admin site
I am a beginner and still learning Django. I am wondering how can I build a personal site for each account like Facebook , Instagram, etc.Thank you very much. English is not my first language. -
upgrade Django 1.9 to 2.0
upgrade Django 1.9 to 2.0 getting an error django.core.exceptions.ImproperlyConfigured: WSGI application 'society.wsgi.application' could not be loaded; Error importing module. setting.py WSGI_APPLICATION = 'society.wsgi.application' wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "society.settings") application = get_wsgi_application() Python 3.5, Django 2.0 -
Manager isn't available; 'auth.User' has been swapped for 'polls.User'
I have created a different version of the User model where there is no username field and I am now trying to implement a sign in feature, but I keep getting the error Manager isn't available; 'auth.User' has been swapped for 'polls.User' I have searched the rest of this site and tried to implement the feature beneath to fix the problem but to no avail. from django.contrib.auth import get_user_model User = get_user_model() Here is the rest of my files Views from django.http import HttpResponse from django.shortcuts import get_object_or_404, render, render_to_response, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from polls.forms import SignUpForm from django.contrib.auth import get_user_model User = get_user_model() @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = None raw_password = form.cleaned_data.get('password1') user = authenticate(password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) forms from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') username = None class Meta: model = User fields = … -
Django login not showing errors
I know there are multiple questions like this around, but none of them contain a clear answer. I am using the default authentication from Django, but have trouble displaying something like 'Your username/password combination is incorrect'. Is it possible to fix this without making a custom view function? My urls.py looks like this: url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='mysite_login') Then my login.html has the following code: {% block content %} <section class="content"> <div class="container block"> <div class="row"> <div class="col-md-12"></div> <form action="{% url 'mysite_login' %}" class="form-control" method="post" accept-charset="utf-8"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field|addcss:'form-control' }} {% if field.help_text %} <small style="color: grey">{{ field.help_text|safe }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit" class="btn btn-dark">Login</button> <input class="form-control" type="hidden" name="next" value="{{ next }}"><br> </form> </div> </div> </div> </section> {% endblock %} So this all works, except for displaying the error messages. I've seen answers where you can write a custom view function and form to fix this, but I assume it should be also possible while using the build-in login functionality right? Thanks a lot. -
Can't install Django using pipenv for unknown reason (but can using pip)
I have no idea what is causing this issue, I have tried uninstalling and re-installing everything from scratch, and I still can't solve this after two days of trying. I could really use some expert help. Am I missing something fundamental here? On my desktop I am running Windows 10, on my laptop I am running Windows 7 (Professional, SP1). On desktop, I pipenv to install django==1.11, and pip freeze shows django==1.11 listed. On my laptop, use pipenv to install django==1.10, but pip freeze doesn't list django. When I check pipfile.lock, I see django listed in there. When I try to use django-admin startporject project, The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check th e spelling of the name, or if a path was included, verify that the path is correct and try again. This is the log from my laptop, so that you can see all the commands I've used (in case I've missed one): PS C:\Project> pipenv install django==1.11 Creating a virtualenv for this project. Using C:\Python27\python.exe to create virtualenv. Running virtualenv with interpreter C:\Python27\python.exe New python executable in C:\Project\Scri... xe Installing setuptools, pip, wheel...done. Virtualenv location: … -
ProgrammingError: ForeignKey already exists when running PyTest in Django project
I am running pytest on a Django-cookiecutter project + Stripe (using Dj-stripe), and running into a ProgrammingError. self = <django.db.backends.utils.CursorWrapper object at 0x10e8323c8> sql = 'ALTER TABLE "djstripe_charge" ADD CONSTRAINT "djstripe_charge_account_id_597fef70_fk_djstripe_account_id" FOREIGN KEY ("account_id") REFERENCES "djstripe_account" ("id") DEFERRABLE INITIALLY DEFERRED' params = () ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x10b5fc668>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x10e8323c8>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: > return self.cursor.execute(sql, params) E django.db.utils.ProgrammingError: constraint "djstripe_charge_account_id_597fef70_fk_djstripe_account_id" for relation "djstripe_charge" already exists ../../Envs/tracer/lib/python3.6/site-packages/django/db/backends/utils.py:85: ProgrammingError When pytest is running django_db_setup, it is erring- request = <SubRequest '_django_setup_unittest' for <TestCaseFunction 'test_clean_username_false'>>, django_db_blocker = <pytest_django.plugin._DatabaseBlocker object at 0x1079f3cc0> @pytest.fixture(autouse=True, scope='class') def _django_setup_unittest(request, django_db_blocker): """Setup a django unittest, internal to pytest-django.""" if django_settings_is_configured() and is_django_unittest(request): getfixturevalue(request, 'django_test_environment') > getfixturevalue(request, 'django_db_setup') I've dropped the test db a few times, but the error is the same - referencing that Stripe charge during db setup. My pytest.ini: [pytest] DJANGO_SETTINGS_MODULE=config.settings.test I'm trying to debug why this is getting created twice, however I'm hitting a roadblock on where to look. Any ideas? Thank you in advance for your help! -
HTTPError: HTTP Error 401: Invalid (legacy) Server-key delivered or Sender is not authorized to perform request. - Django push notifications
I can't send notifications to other devices like mobile phones with Django push notifications. I get an error saying : HTTPError: HTTP Error 401: Invalid (legacy) Server-key delivered or Sender is not authorized to perform request. -
python django deploy vs ruby on rails capistrano deploy
i'm learning Ruby on Rails. And i wrote a small app. now i want to deploy it to my domain. i don't want to make it live under heroku. so i bought a host package from digitalOcean. i used a couple deployment tutor, but no luck. it doesn't show my homepage. i like Ruby on Rails so much. especially approaching to database. but deploying is very hard, if you don't want to pay for it a company like heroku. now, i'm thinking another choices. i love osx and i want to code there. because of this, i don't think to learn c# and .net. python is warm to me. so, is the deploying of python django easier than RoR deployment, like html/ccs/js or lamp sites? thank you all! -
Refresh page without reload. Wagtail
Where can i put ajax get data code in Wagtail? I have following page model: class ScreencastPage(Page): content_panels = Page.content_panels + [ InlinePanel( 'groupstage_screencast_relationship', label="Choose Teams", panels=None, max_num=2), ] parent_page_types = ['home.HomePage'] def matches(self): matches = [ n.match for n in self.groupstage_screencast_relationship.all() ] return matches And my template: {% for spiel in page.matches %} {% if forloop.first == forloop.last %} <div id="fullscreen"> <ul class="ulup"> <li class="logo_bg first_team">{% image spiel.team_1.team_logo width-400 class="logo" %}<p>{{spiel.team_1.title}}</p></li> <li class="first_team_score">{{ spiel.team_1_total_score }}</li> <li class="colons">:</li> <li class="second_team_score">{{ spiel.team_2_total_score }}</li> <li class="logo_bg second_team">{% image spiel.team_2.team_logo width-400 class="logo" %}<p>{{spiel.team_2.title}}</p></li> </ul> </div> {% endif %} {% endfor %} I started writing js. Just exaple: $(document).ready(function() { setInterval(function(){ $.ajax({ type: "GET", url: "/presentation", success: function(data) { $(".first_team_score").update(data.team_1_total_score); $(".second_team_score").update(data.team_2_total_score); } }) }, 10000); }); The idea is that the page will automatically update the value of <li class="first_team_score">{{ spiel.team_1_total_score }}</li> and <li class="second_team_score">{{ spiel.team_2_total_score }}</li> without reloading the page. I found here great example, but they using view.py We also need to write a new view.py or have wagtail some method for that? -
Override in the widget attributes the max_length set on the Model
In the Model I set the maxlength of the field: short_description = models.CharField(max_length=405) In the ModelForm in the widget attributes I set minlength an maxlength: widgets={ 'short_description': TextareaWidget(attrs={'minlength': 200, 'maxlength': 400}), .... } The issue in the HTML the minlegth is from the widget, but maxlength is still taken from the model(405 instead of 400). I want the widget attribute to overwrite the model attribute. -
Owner of the data and superuser should only be able to update the data using CBV
This is my UpdateView. As i have just started django. I am a newbie views.py @method_decorator(login_required, name='dispatch') class ProductUpdateView(UpdateView): fields = ('product_name', 'product_cost') model = Product I have created a superuser and a user. Superuser should be able to update all the product of both his and everyone else's but user should be only be able to update his product only. urls.py urlpatterns = [ url(r'^product/(?P<pk>\d+)/update/$', login_required(ProductUpdateView.as_view()), name='product_update'), ] I have a created a product using superuser, which has pk = 1. When i login with some user (Which not superuser) and visit the above url. This user is able to update superuser's product. models.py class Product(models.Model): product_name product_cost # This two fields and created_by created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name="Product", null=True) Is there any way that own of the data can update that data and if user tries to access someone else's data it should Http404. -
When using ajax with django views, when should I use a method of GET and when should it be POST?
I'm able to accomplish the same task with either--I only need to make sure that if the ajax method is get, then my view needs to handle the get and if a POST, that the view handles a post. Given this, when do I use a GET and when do I use a POST? $.ajax({ method: "????", url: $endpoint, data: $buttonData, success: handleSuccess, error: handleError, }) class MyAjaxView(View): def ???(self, request, *args, **kwargs):