Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django Template to get attributes of html tags
So I have a webpage with a radio button on it. So when the default option is selected, Django displays English units. When the other option is selected, Django displays Metric units. index.html <form> <label class="radio-inline"> <input id="English" type="radio" name="optradio" checked="checked"> <p>English</p> </label> <label class="radio-inline"> <input id="Metric" type="radio" name="optradio"><p>Metric</p> </label> </form> {% if getByID("English").checked="checked" %} {% for length, width in english %} <p>{{ length }} Miles X {{ width }} Miles</p> {% endfor %} {% else %} {% for length, width in metric %} <p>{{ length }} Kilometers X {{ width }} Kilometers</p> {% endfor %} {% endif %} I've been searching for hours, but haven't found anyone using template language to base conditions off of other elements. Would anyone know how to properly do this? -
Django throwing error django.db.utils.IntegrityError: UNIQUE constraint failed: mediaSort_userdata.user_id
I'm testing my models on my django app and whenever i try to save my extended User model (using a OneToOne relationship) it throws that error models.py class UserData(models.Model): lastSeason = models.IntegerField(default=0) lastChapter = models.IntegerField(default=0) user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.user.username This is what i do on the manage.py shell: >>> from django.contrib.auth.models import User >>> from mediaSort.models import Show, UserData >>> import datetime >>> usL = User.objects.get(username='luciano') >>> newUs = UserData(lastSeason=1,lastChapter=2,user=usL) >>> newUs.save() And this is the error: Traceback (most recent call last): File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: mediaSort_userdata.user_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 842, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 880, in _do_insert using=using, raw=raw) File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1125, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\Luciano\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1280, in execute_sql cursor.execute(sql, params) … -
Django Ignoring Asynch Tests Completely (Django Channels)
I'm working on a web server running Python3.6, Django 2.0 and Channels 2.0.2. I'd like to build some tests to make sure my websocket consumers are behaving themselves, unfortunately, whenever I run the tests they are all ignored completely. I've been following the official Channels documentation on testing, and I copied the code Channels uses to test its generic consumers as is but whenever I run the tests, the test runner simply reports that it ran no tests: Creating test database for alias 'default'... System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Destroying test database for alias 'default'... I get no errors or other warnings. I've double checked that I've installed pytest-asyncio and pytest-django, and I'm 100% sure the file itself is being loaded by placing a print statement at the top. All my other tests run normally. Any help is greatly appreciated. -
How do I use `password_reset_confirm.html` with AngularJS?
I want to integrate AngularJS in my custom password_reset_confirm.html template. But when I fill out a new password and hit "submit," nothing happens. I have this in my custom password_reset_confirm.html template: {% block main %} <div class="elems-wrapper card bg-light elem-with-margin-top membership-detail-elem" ng-app="app" ng-controller="Ctrl"> <div class="card-body"> <h2 class="card-title">{% trans "Reset password" %}</h2> {% if validlink %} <form id="reset-pw-confirm-form" name="newPWForm" method="post"> {% csrf_token %} <div class="input-group"> <input id="id_new_password1" class="form-control" type="[[[ newPW.showPW ? 'text' : 'password' ]]]" name="new_password1" aria-label="Enter new password" placeholder="Enter new password" ng-model="newPW.pw" ng-minlength="8" ng-maxlength="32" required> <div class="input-group-append"> <div class="input-group-text"> <input aria-label="Checkbox for showing password" type="checkbox" ng-model="newPW.showPW" ng-checked="false" > <small class="text-muted">[[[ newPW.showPW ? 'Hide' : 'Show' ]]]</small> </div> <button class="btn btn-primary" type="submit" ng-disabled="!newPW.pw">Submit</button> </div> </div> <input id="id_new_password2" type="hidden" value="[[[ newPW ]]]" name="new_password2" aria-label="Automatically enters password a second time for confirmation" placeholder="Enter again" ng-model="newPW" ng-minlength="8" ng-maxlength="32" required> </form> {% else %} <p>{% trans "The password reset link was invalid, possibly because it has already been used. Please request a new password reset." %}</p> {% endif %} </div> </div> {% endblock main %} And this in my JS file: var app= angular.module("app",[]); app.config(function($interpolateProvider, $httpProvider){ $interpolateProvider.startSymbol("[[["); $interpolateProvider.endSymbol("]]]"); $httpProvider.defaults.xsrfCookieName= "csrftoken"; $httpProvider.defaults.xsrfHeaderName= "X-CSRFToken"; }); app.controller("Ctrl", function($scope, $http){ }); How do I make the form submit to … -
(django) I've updated my static files. Why doesn't gunicorn see that?
Even on my (production) server, I go into /home/me/myproj/myproj/static/js/main.js and see that it is updated, but at mysite.com/static/js/main.js it is not updated. Here are my django static settings: DIRNAME = os.path.abspath(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) if not IS_PRODUCTION: BROKER_URL = "django://" STATIC_ROOT = os.path.join(BASE_DIR, '/static') SITE_ID = 5 #SSLIFY_DISABLE = True STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) DEBUG = True else: BROKER_URL = 'amqp://' STATIC_ROOT = os.path.join(DIRNAME, 'static') #PREPEND_WWW = True SITE_ID = 3 STATICFILES_DIRS = ( os.path.join(DIRNAME, 'staticfiles/'), ) DEBUG = False Can anyone help? Thanks in advance -
django celery 4 - ValueError: invalid literal for int() with base 10
I have django 1.11.5 and celery 4. I want to pass user in view to task (because I can't do this in tasks.py, right?) def form_valid(self, form): form.instance.user = self.request.user dict_obj = model_to_dict(self.request.user) # serialized = json.dumps(dict_obj) # print(serialized) task_number_one.delay(dict_obj['username']) return super().form_valid(form) In celery I got an error: ValueError: invalid literal for int() with base 10: 'my_username' -
Chatbot - Django channels with websockets or Django-Rest-Framework?
I am going to create dialog system which will allow to upload all types of files and which will have online chat with server. I wonder what should I choose Django channels with websockets or Django-Rest-Framework? Or maybe I should use both - Django-Rest-Framework for registration and sending files and Django channels with websockets for chat? What do you think about it? Maybe I should choose something else? -
Django add message to path
Is it possible to pass a flash message along with a path in urls.py? Since I did not write the auth_views into my core views.py file I figured there might be an easy way to pass it along with the request. I'd prefer to use the auth_views out of the box so that it's easy to update my version of Django. If this is not possible, then I am not trying to force it. Checked the documentation but did not find anything about messages. path('logout/', auth_views.logout, {'next_page': auth_views.login}, name='logout'), I'd like to pass something like the message below so that it doesn't feel like they clicked login by accident or something. 'messages.success(request, 'You have securely logged out of {{request.user.email}}. Thank you for visiting.') -
How to overide django_filter forms deafult behviour for MultipleChoiceFilter and BooleanFilter?
Hello I am working with django_filters and am having some issues figuring out how to override it's default forms, the form works fine if I just do {{ filter.form.as_p }} however it is not user-friendly For MultipleChoiceFilter how would I make each choice a selectable button that only sends data when the form submit button is used? I attempted the following {% for choice in filter.form.size %} <button type="button">{{ choice.choice_label }}</button> {% endfor %} While that does list all the choices it does not send any data. For BooleanFilter how would I only display the true option to the user instead of a drop-down that lists all the possible values? Thanks -
Django and RabbitMQ setup
I have a django app deployed on multiple VMs behind a load balancer. On each django. I want to setup celery and RabbitMQ for the app. Each django app would be running a celery worker, and some of the VMs should be running RabbitMQ in a cluster setup and if a celery worker executes a task others shouldn't execute the same task. Is this approach for setting up celery and RabbitMQ good. Can anyone guide me to how this can be setup (Configurations, tutorial, etc.)? -
Which Server is suitable for django project which written in windows Machine
these days i will finish my django project . im developing the project in Pycharm IDE And i am using windows . python version : 3.6.4 django version : 2.0.2 i am going to publish my project into internet BUT I dont have much information about servers and their OS . I think Linux Servers are more secure and better for python language . but there is a question : im using pycharm in windows OS , so i SHOULD use a windows server for production which pycharm installed on it ?! Can anyone explain all steps in " pycharm django project " production ? Thanks. -
Django Social Auth - Not Enough Values To Unpack When Trying To Send Email
I'm using the Django-Python Social Auth app and i'm trying to extend my pipeline so that when a user signs up using Facebook, they are simultaneously signed up to my Mailchimp mailing list (and sent an email to verify). This works fine if a user signs up using traditional input methods--but not via Social auth.and is returning this error: ValueError at /oauth/complete/facebook/ not enough values to unpack (expected 2, got 1) My pipeline looks like so: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'sendsub', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) you can see that I've added a sendsub function which is based on this function---and somewhat modeled off this page here def sendsub(backend, user, response, *args, **kwargs): profile = user.get_profile() email = profile.email thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() def run(self): API_KEY = settings.MAILCHIMP_API_KEY LIST_ID = settings.MAILCHIMP_SUBSCRIBE_LIST_ID api = mailchimp.Mailchimp(API_KEY) try: api.lists.subscribe(LIST_ID, {'email': self.email}) except: return False again this sendsub function is working correctly when applied to my regular registration page an user model..here is the function (slight difference). class SendSubscribeMail(object): def __init__(self, email): self.email = email thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() def run(self): API_KEY = settings.MAILCHIMP_API_KEY LIST_ID = … -
what is robots.txt warning in django and advise to handle this?
I am running Django on localhost (development machine), and I came across this in my debug console: Not Found: /robots.txt 2018-03-20 22:58:03,173 WARNING Not Found: /robots.txt [20/Mar/2018 22:58:03] "GET /robots.txt HTTP/1.1" 404 18566 What is the meaning of this and if there is any recommendation to handle this right. Also on production server. -
How can I authenticate user both in websockets and REST using Django and Angular 5?
I would like to authenticate user both in websockets and REST using Django and Angular 5. I have created registration based on REST API. User after creating an account and log in can send messages to backend using websockets. My question is how can I find out that the authenticated user by REST API (I use Tokens) is the same user who sends messages? I don't think that sending Token in every websocket message would be a good solution. -
Can I filter a parent model by occurences in a child model in django?
I have two models: class User(models.Model): # stuff class Task(models.Model): # stuff When assigning new tasks to users, I want to avoid assigning tasks the worker has gotten before. The approach I'm trying to take is to add a third model, Assignment that tracks tasks assigned to a given user: class Assignment(models.Model): worker = models.ForeignKey(User) task = models.ForeignKey(Task) How, though, do I go about forming a query based on this? My thought was to start by filtering Assignments by the user being assigned to, but I'm getting stuck after that point. def get_tasks(worker): previous_assignments = Assignment.objects.filter(worker=worker) assignable_tasks = Task.objects.filter(pk__in=previous_assignments???) Is there a way to access the task ids inside the previous_assignments queryset? Not sure if this isn't the best approach, or if I am just missing how to move past this step. -
Django website toggling between latest and previous state on reload
today, I have recognized a strange behaviour of my Apache served Django 2.0.2 (Webfaction) website. After I have made a change and restarted the Apache server, the reloaded website shows the latest change. But when I hit F5 (reload) again, the view of the previous state is displayed again. Another reload and the latest state is displayed. That continues back and forth. For example, see the smallcaps and line-break changes: Before, the same happened to the background opacity, too, so it's not limited to the font. It happens on Firefax (PC) as well as on Opera and Chrome browsers (on mobile dev). So, I assume the issue lies in Apache - or Django. I've never seen such a behaviour, before. Does anyone have an idea what causes this effect? Not sure whether it is of help (because the site will soon change), but for reproduction of the error, this is the site: http://campfire.skylet.de/ Thank you Michael -
Generalizing deletion of placeholderfield django-cms with signals
I'm currently working in django-cms and utilizing a PlaceholderField in several of my models. as such, I'd like to generalize this process to avoid having to override every model's delete, and add a specialized manager for each type of object just to handle deletions. a little back story: after working up the design of my application a little bit and using the (honestly impressive) 'PlaceholderFields' i noticed that if I deleted a model that contained one of these fields, it would leave behind it's plugins/placeholder after deletion of the model instance that spawned it. This surprised me, so I contacted them and according to django-cms's development team: By design, the django CMS PlaceholderField does not handle deletion of the plugins for you. If you would like to clear the placeholder content and remove the placeholder itself when the object that references it is deleted, you can do so by calling the clear() method on the placeholder instance and then the delete() method so being that this is expected to happen prior to deletion of the model, my first thought was use the pre_delete signal provided by django. so i set up the following: my problem models.py class SimplifiedCase(models.Model): #... fields/methods … -
Django Email Backend Setting Not Working
I have a unit test with a test-specific settings file, which includes: EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = '/my/file/path' This wasn't working, so I dropped into the debugger to check the settings in the middle of running my test: ipdb> from django.conf import settings ipdb> settings.EMAIL_BACKEND 'django.core.mail.backends.locmem.EmailBackend' ipdb> settings.EMAIL_FILE_PATH '/my/file/path' The file path setting worked, but the backend setting didn't! Does anyone know why? What else could I check/configure? Is this something for a bug report? Django 1.11 -
Cannot assign "'Album object (6)'": "Music.album_id" must be a "Album" instance
I spend a lot of time in google and find a few solutions for my problem but none of them works :(( models : class Album(models.Model): name = models.CharField(max_length=100) author = models.CharField(max_length=100) picture_address = models.TextField(max_length=1000) creation_year = models.IntegerField(default=-1) rate = models.IntegerField(default=0) class Music(models.Model): name = models.CharField(max_length=100) cover = models.ImageField(upload_to=upload_destination) album_id = models.ForeignKey(Album, on_delete=models.CASCADE) and here is form : class music_create_form(forms.ModelForm): album_options = [('', '')] for album in models.Album.objects.all(): album_options.append((album,album.name)) name = forms.CharField(required=True , widget=forms.TextInput(attrs={'class': "normal_padding form-control"})) cover = forms.FileField(required=True , widget=forms.FileInput(attrs={'class': "normal_padding", 'accept': "image/jpeg"})) album_id = forms.Field(required=True , widget=forms.Select(attrs={'class': "normal_padding form-control"}, choices=album_options)) class Meta: model = models.Music fields = [ 'name', 'cover', 'album_id' ] and here is view : def create_music(request): form = forms.music_create_form(request.POST or None, request.FILES or None) context = {'form': form} if request.method == "POST": if form.is_valid(): print(form) data = form.save(commit=False) data.save() context['action_done'] = True return render(request, 'music/create_music.html', context) when i try to add new model with that form , i got the error at this line : " if form.is_valid() " Cannot assign “'Album object (6)'”: “Music.album_id” must be a “Album” instance -
django-oscar home page not displaying content
I have a django-oscar application which works fine but the problem I am facing is that I can not get the index page http://127.0.0.1:8000/ to display anything. I tried adding some content block and working from the dashbord by adding the url as / but still would not work. any help would be greatly appreciate. -
Generating large openpyxl file django
I am using django and openpyxl to export reports on button click. However, one of my reports is very large (about 3.5MB and 150k rows of data with 30+ columns) and when I try and run the openpyxl file generation I get 504 Gateway Time-out The server didn't respond in time. Is there anyway I can prevent the django view from timing out? Perhaps something I can add to the python in the view to allow for extra processing time? It doesn't matter if it takes a minute or two. I have tried openpyxl Write-only mode and it still times out. I think it is also worth noting that I am using apache Here is my code: wb = Workbook(write_only=True) ws = wb.create_sheet() # Adds headers ws.append(data['headers'][1:]) # Add data to 'RawData' for row in data['data']: ws.append(row[1:]) file_name = str(report_name).replace(' ', '_') + "_export.xlsx" response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename= "{0}"'.format(file_name) return response -
Django does not regulate what the user can choose
I am very new to Django so don't judge me :). I am making a blog project and everything works well except one thing. When creating a post, the user can choose any other author that has previously logged in. Is there any way to set the author namespace as the currently logged in user? Here is my code: Models.py from django.db import models from django.utils import timezone from django.core.urlresolvers import reverse from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User def validate_even(value): if value == 'auth.User': raise ValidationError( _('%(value)s is not an even number'), params={'value': value}, ) class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('post_detail', args=(), kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.post',related_name='comments') author = models.ForeignKey('auth.User') text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse('post_list') def __str__(self): return self.text class UserProfileInfo(models.Model): user = models.OneToOneField(User) def __str__(self): return self.user.username My forms.py from django import forms from blog.models import Comment,Post from django.contrib.auth.models import User from blog.models import UserProfileInfo class PostForm(forms.ModelForm): … -
Encoding error when saving excel file to Django FielField
Have a good day, everyone. While building a django app I have come to a problem I hope I can get help with. I'm generating manually an excel file using an empty pandas dataframe where the headers are the contents of another model field, this file will serve as a template for the user to import data. The file is generated sucessfully but when I try to save it to a model (so I dont have to create again the same file in the future) it gives me the folowwing error: 'charmap' codec can't decode byte 0x8d in position 54: character maps to < undefined> I'm currently using Django 2.0.3, windows 10 and my system language is Spanish (latin america) Here is the view The view receives the values 'periodo' (period) and 'programa' ('program') from a form def generar_archivo_importacion(request): if request.method == 'GET': periodo_plantilla = Periodo.objects.get(id=request.GET['periodo']) programa_plantilla = Programa.objects.get(id=request.GET['programa']) # HERE I TRY TO GET THE DATA FOR THE DATAFRAME HEADERS try: modulos_generales = ModulosGeneralesPeriodo.objects.get(periodo__id=periodo_plantilla.id). \ modulos_generales.all() except ModulosGeneralesPeriodo.DoesNotExist: return HttpResponse('Error: No hay Módulos generales inscritos en este periodo, corrija este error') datos = { 'Numero Documento': [], 'Tipo Documento': [], 'Nombre': [], 'Apellido': [], } for modulo in modulos_generales: … -
ImportError trying to run the Django shell
I'm getting an intractable ImportError when trying to run python manage.py shell on my Django project. Here is a partial directory structure (generated using tree -D 3 -P '*py'): . ├── dashboard │ ├── __init__.py │ ├── apps.py │ ├── context_processors.py │ ├── exporters.py │ ├── forms │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── check_in.py │ │ ├── check_in_types.py │ │ ├── companies.py │ │ ├── experts.py │ │ ├── families.py │ │ ├── fields.py │ │ ├── packages.py │ │ ├── pre_activation_families.py │ │ ├── search.py │ │ ├── session_categories.py │ │ ├── session_types.py │ │ ├── sessions.py │ │ └── widgets.py ├── lucy_web │ ├── __init__.py │ ├── models │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── base_family.py │ │ ├── check_in.py │ │ ├── check_in_type.py │ │ ├── company.py │ │ ├── country.py │ │ ├── expert.py │ │ ├── expert_session_type.py │ │ ├── expressions.py │ │ ├── family.py │ │ ├── lucy_guide.py │ │ ├── notification.py │ │ ├── package.py │ │ ├── package_session_type.py │ │ ├── pre_activation_family.py │ │ ├── question │ │ ├── session.py │ │ ├── session_category.py │ │ ├── session_type.py │ │ ├── timestamped_model.py │ … -
django-dbbackup wrong backup command?
I try to use django-dbbackup module in my project. From the docs I need to run it with python manage.py dbbackup. If I do so - I see there goes a command: pg_dump last_cosmetics --host=localhost --username=postgres --no-password --clean And then it fails with dbbackup.db.exceptions.CommandConnectorError error. I figured out that default PostgreSQL db backup command must be in a format: pg_dump [connection-option...] [option...] [dbname] But as I see that traceback differs: django-dbbackup sends the first argument - database name. And in the PostgreSQL docs - this name must be the last argument. What am I missing or doing wrong? How to make django-dbbackup work correctly?