Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"NoReverseMatch" issue in Django
NoReverseMatch at /en-us/schools/1/classroom/1/update/ Reverse for 'index' with arguments '('',)' not found. 1 pattern(s) tried: ['en-us/schools/(?P\d+)/index/$'] urls.py url(r'^(?P\d+)/classroom/(?P\d+)/update/$', views.ClassroomUpdateView.as_view(), name='classroom_update') -
Unable to migrate with django_mssql_backend to outside host
I'm trying to migrate my django project and use SQL Server 2012 as database backend. For connection, i'm using django-mssql-backend. But, something wrong happen when trying to migrate. File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\ProgramData\Anaconda3\lib\site-packages\django_mssql_backend-2.2.0-py3.7.egg\sql_server\pyodbc\base.py", line 536, in execute django.db.utils.Error: ('21000', '[21000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. (512) (SQLExecDirectW); [21000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The statement has been terminated. (3621)') And here my code for define database in settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'djangodb', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '172.30.55.7', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } As info, database host to another server and I ain't use model. But, if I change database host into 'localhost' (of course, I created same database in my local computer), migration process success. Thanks for help. -
How can I create objects in a for-loop in python?
I'm trying to create some objects in database through a for loop in python, but when I try, it only inserts last one. This is the code I have, where 'langssplit' is a list, the result of spliting a string like '2-3' (the pks of the Language rows in the table). I need to create and insert an object into the database for each element on the list, but it only saves the last one. The newprofile is an object I have already created. langsparam = request.GET.get('langs', '') langssplit = langsparam.split('-') for lan in langssplit: lang = Languages.objects.filter(pk=lan).first() newprofilelan = ProfilesLanguages(profile=newprofile, language=lang) newprofilelan.save() What am I doing wrong? Thanks for any help! -
Validation of custom widgets
How should validation errors be propagated for custom widgets where the widget input itself may be incoherent? Case in point, I'm creating a custom date input widget for a Date field that allows the user to select the date according to the Japanese Imperial calendar. This requires an era dropdown and a year input, and it's perfectly possible to select an era–year combination that is in itself invalid. The widget converts this input to/from a Python date object using the MultiWidget.value_from_datadict/MultiWidget.decompress methods: def value_from_datadict(self, data, files, name): era, imperial_year, month, day = [widget.value_from_datadict(data, files, f'{name}_{i}') for i, widget in enumerate(self.widgets)] try: return date(self._j2w.convert(f'{era}{imperial_year}年'), int(month), int(day)) except ValueError: # selected era/year combination was invalid return '' All I can do in this method is catch any ValueError and return an empty value instead, which means the field's validator complains about missing data, not about an incorrect value. If I simply raise the ValueError or a ValidationError, it's causing an uncaught exception error. Where and how should this kind of validation happen? I'd like the keep the abstraction of the Japanese picker purely inside the UI layer, and keep the backing field a simple Date field. -
django celery not executing tasks.py in digitalocean server
I used Celery in my django project for schedule tasks, it was kinda perfect in local server, I upload this update to my digitalocean server, and after 3 days of searching and fixing issues I couldn't understand that pinch of mistakes I did ! , here is my project structure ├── app │ ├── __init__.py │ ├── admin.py │ ├── urls.py │ ├── models.py │ ├── apps.py │ └── views.py ├── manage.py ├── corsa │ ├── __init__.py │ ├── celery.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── requirements.txt └── templates ├── base.html ├── other tasks.py : @shared_task def just_testing(): print(' test log ') @shared_task def tasks_to_do_daily(): # some stuff to do daily @shared_task def tasks_to_do_weekly(): # some stuff to do weekly celery.py : os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'corsa.settings') app = Celery('corsa') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'add-contrab1': { 'task': 'app.tasks.just_testing', 'schedule': 6.0, }, 'add-contrab2': { 'task': 'app.tasks.tasks_to_do_daily', 'schedule': crontab(minute='26', hour='09'), }, 'add-contrab3': { 'task': 'app.tasks.tasks_to_do_weekly', 'schedule': crontab(minute='00', hour='00', day_of_week='sat,tue'), }, } app.conf.CELERY_TIMEZONE = 'Asia/Hong_Kong' settings.py : CELERY_BROKER_URL = 'amqp://localhost' Ok, now issues part .. For local I tried these commends celery -A corsa worker -l info , celery -A corsa beat -l info , celery worker -A corsa --loglevel=INFO … -
Style guide: how to not ot get int o a mess in a big project
Django==2.2.5 In the examples below two custom filters and two auxiliary functions. It is a fake example, not a real code. Two problems with this code: 1. When a project becomes big I forget what aux functions I have already written. Not to mention team programming. What is the solution here? To organize a separate module for functions that can be imported? And sort them alphabetically? 2. Some functions from here may be reused outside this package, and some may not. Say, the combine function seems to be reusable, while "get_salted_str" is definitely for this module only. I think that it is better to distinguish between functions that may be imported and those that may not. Is it better to use underline symbol to mark unimported functions? Like this: _get_salted_str. This may ease the first problem a bit. 3. Does Django style guide or any other pythonic style guide mention solutions to the two above mentioned problems? def combine(str1, str2): return "{}_{}".format(str1, str2) def get_salted_str(str): SALT = "slkdjghslkdjfghsldfghaaasd" return combine(str, SALT) @register.filter def get_salted_string(str): return combine(str, get_salted_str(str)) @register.filter def get_salted_peppered_string(str): salted_str = get_salted_str(str) PEPPER = "1234128712908369735619346" return "{}_{}".format(PEPPER, salted_str) -
Filter data based on current date + 365 days in Django Rest framework
I am trying to build a web app. Part of the requirement is when the user clicks on a time interval like "1 year", he can view all the upcoming movies in one year. When the user clicks on "1 year" it should trigger a filter which displays movies from today till next year. How is it possible in django ? I want to make a filter similar to this logic - class sales_plot(APIView): def post(self, request, *args, **kwargs): interval = json.loads(request.body).get('interval') queryset = model_name.objects.filter(date_of_relase= current_date + interval) serialize = serializer_name(queryset, many=True) return Response(serialize.data, status=status.HTTP_200_OK) How can I do that ? -
How to deal with standard Error object on frontend?
I have a frontend app with many API requests, but it's a pain to work with error responses. Sometimes I need to go through many objects like: error.response.data.email and sometimes it is error.response.data.address.province[0]. I can't predict all of the errors, and writing manual "parsers" looks like a dirty extra solution to me: const errorsObject = err.response.data let errors = '' Object.keys(errorsObject).map(key => { if (key === 'address') { Object.keys(errorsObject.address).map( key => (errors += `${key} : ${errorsObject.address[key]}\n`) ) } else { errors += `${key} : ${errorsObject[key]}\n` } return undefined }) yield toast.error(errors) Also it still doesn't cover everything. Is there any frontend parsers for that? If not, our backend is Python(Django), maybe there is a package for backend side? Ideally I'd want to see a flat array of objects {title, message}. -
How to setup vue template with django project
I have downloaded vuejs template,I want to setup with django project(my django side is already up and running) I don't want to spend much time reading the structure of vuejs and its components by now. Am wondering is there any easy way to setup like vue CLI or any. Please help me any easy way to integrate!! -
How to save files via django serializers after processing them in my views?
I have a excel/csv file that I read using pandas once the user uploads the file. I process the file in my views.py and save them directly using the command df.to_excel("filename.xlsx") or df.to_csv("filename.csv") Is there a way to save the files through django serializer? I've tried df.to_excel("filename.xlsx") directly on the serializer data as shown on the code, but the file ends up writing to my disk directly instead of being saved via the serializer. data = { 'file': df_template.to_excel(output_file_name, index=False), 'created_for': project.id, } outputrecord_serializer = OutputRecordSerializer(data=data) if outputrecord_serializer.is_valid(): #print('Check if serializer is valid') outputrecord_serializer.save() #print('saved') else: print(outputrecord_serializer.errors) -
KeyError for 'id' field when ModelForm CheckboxSelectMultiple choices are 'id'
I am new to Django. I have a form where I want to have list of 'id's of model items as choices of CheckboxSelectMultiple field. Here is my example Models.py class TryDjango(models.Model): name = models.CharField(max_length=120) Views.py class trydjango_view(View): template_name = 'trydjango.html' failed_template = 'generic_error.html' viewContext = { "title" : "Page title ", "columnNames" : ["Name"], "url" : 'trydjango', 'loginInfo' : 'logout', } def get(self, request): self.viewContext['deleteTryDjangoForm'] = \ deleteTryDjangoForm(prefix='delete') login_result = getLogin(request) self.viewContext.update({'loginInfo' : login_result['loginInfo']}) return render(request, self.template_name, self.viewContext) ModelForms.py class deleteTryDjangoForm(forms.ModelForm): myPrefix ='delete-' class Meta: model = TryDjango fields = ['id'] def __init__(self, *args, **kwargs): super(deleteTryDjangoForm,self).__init__(*args, **kwargs) sportSeriesList = listOfSportSeries() print(sportSeriesList) self.fields['id'].widget = \ forms.CheckboxSelectMultiple(choices=[(1,1)]) #<<-- Line 399 in the error Finally the error I am getting KeyError at /trydjango/ 'id' Request Method: GET Request URL: http://127.0.0.1:8000/trydjango/ Django Version: 2.0.7 Exception Type: KeyError Exception Value: 'id' Exception Location: /Users/sbt/dev/trydjango/src/myPrjApp/modelforms.py in __init__, line 399 Where line 399 is the line "forms.CheckboxSelectMultiple(choices=[(1,1)])" from my form. The form doesn't give this error if I change the field from 'id' to 'name'. I have few other models whose primary keys are not the 'id' fields. I can delete those model items using the corresponding primary keys. However, the form fails only if the … -
is there a way to fix a database isssue on django?
I'm not sure if removed some pycache files and it messed my website up or if me pulling some files from git has changed my folders about but I'm getting database connect issues. I have tried makemigrations, migrate and runserver and I'm getting the same error each time. I can't uninstall wagtail or django as it comes up failed to create process. I'm getting the horrible feeling it might be time to scratch the project and start again. Here is the error self.connection = self.get_new_connection(conn_params) File "..\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 194, in get_new_connection conn = Database.connect(**conn_params) sqlite3.OperationalError: unable to open database file The above exception was the direct cause of the following exception: Traceback (most recent call last): File "..\threading.py", line 926, in _bootstrap_inner self.run() File "..\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "..\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "..\runserver.py", line 120, in inner_run self.check_migrations() File "..\base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "..\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "..\loader.py", line 49, in __init__ self.build_graph() File "..\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "..\recorder.py", line 73, in applied_migrations if self.has_table(): File "..\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "..\base.py", … -
How to store a table to database in Django 2.1?
I use Django 2, that is why I post similar questions and I am a beginner in Django. Question: I have a table inside html, and I need to save it into database using view and model and form. Here are some part of the code: template.html <form method="post" action="/images/save/" enctype="multipart/form-data"> {% csrf_token %} <table class="table" border="1" id="tbl_posts"> <tbody id="tbl_posts_body"> {% for name, age in lines %} {% with i=forloop.counter0 %} {% with i|add:1|stringformat:"s" as i_id %} {% with id="rec-"|add:i_id %} <tr id={{id}}> <td><span class="sn">{{ i|add:1 }}</span>.</td> <td><INPUT type="text" name="txt1" value=""\></td> <td><INPUT type="text" name="txt2" value=""\></td> </tr> {% endwith %} {% endwith %} {% endwith %} {% endfor %} </tbody> </table> <input type="submit" value="Submit"> </form> model.py: class Names(models.Model): name= models.CharField(max_length=255) age= models.IntegerField() view.py: def save_form(request): template = "template.html" context = {'txt1': "Name", 'txt2': 0} if request.method == 'POST': dname= request.POST.get("txt1") dage= request.POST.get("txt2") names1= Names(name=dname, age=dage) names1.save() return render(request, template, context) Question: So, it works perfectly, but the issue is that It saves only the last row. I think there is a way to enter the whole data. I need to enter all data in the table not only the last row. Can someone help me? Update: lines is a zip a … -
Migrations issue in Cpanel postgresql
I have a query regarding Cpanel, Please help me out. I had created python application with using Django Framework and Postgresql as Database and I am facing issue while migrating the Database, Below is the mentioned error please do the needful. Thanks in Advance -
No phone number record in django admin site
Currently on my own django project at the admin site, I can only see username, email , first name, last name and staff status. The UserCreationForm I am using provided by django has a phone number text field that I included to let users key in their phone number, however, I cant seem to get the admin site to store the phone number record. Please tell me if there are any changes that should be made to my current code so that I can see the phone records. Wondering if there is anything that I should be including to my admin.py or forms.py. /* forms.py */ from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from validate_email import validate_email class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', 'email'] def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, verify=True): raise forms.ValidationError("Invalid email") return email /* views.py */ from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() phone_number = form.cleaned_data['phone'] # do something with phone number?? username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') … -
Chained form fill in django form
I have a django model Models.py class ReceiveDocket(models.Model): sender_parent_client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='sender_parent_client') client_location = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_location') received_at_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name='warehouse_list') class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_company = models.CharField(max_length=255, default=0) client_name = models.CharField(max_length=255, default=0) client_shipping_address = models.CharField(max_length=255, default=0) and a form of receive docket: Views.py @method_decorator([login_required, employee_required], name='dispatch') class ReceiveDocketFormView(CreateView): model = ReceiveDocket fields = "__all__" template_name = 'packsapp/employee/docketRecievedForm.html' def form_valid(self, form): product = form.save(commit=False) product.save() messages.success(self.request, 'The Docket was created with success!') return redirect('employee:docket_table') How can I change my views such that when I select the sender parent client it automatically fills the client address in client location or at least show the client address in the drop-down ? -
django: Where to put readonly_fields?
I defined my model as following: from django.db import models class Books(models.Model): name = models.CharField(max_length=100) author = models.CharField(max_length=100) def __str__(self): return str(self.name) The problem is that when I want to make the author field readonly in admin.py as following: from django.contrib import admin from core.models import Books class Books(admin.ModelAdmin): readonly_fields=('author',) admin.site.register(Books) I get the following error upon running server: -
raise MultiPartParserError in Django2.2
I'm trying post the form data using 'XMLHttprequest' to the django views and i'm getting 'A server error occurred. Please contact the administrator.' in the browser console, and i'm getting following error raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary.decode()) AttributeError: 'NoneType' object has no attribute 'decode' in my terminal. The following is my code snippet. <html><head><tile></title> <body> <form> {% csrf_token %} <input type="text" id="in" name=""> <input type="button" id='' value="submit" onclick="myfunction()"> </form> <script type="text/javascript"> function myfunction() { var emailId = document.getElementById('in').value; var csrfToken = getCookie("csrftoken"); var myform = new FormData(); myform.append("email", emailId); var xhttp = new XMLHttpRequest(); xhttp.open("POST", '{% url "log" %}', true); xhttp.setRequestHeader('X-CSRFToken', csrfToken ); xhttp.setRequestHeader("Content-Type", "multipart/form-data;charset=utf-8"); xhttp.send(myform); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) } }; } </script> <body> </html> -
Django template convertion error when a number with thousand separator
I have some decimal values with thousand separator passed into a Django template as a list. It should be interpreted as a float value to do some JavaScript calculations. However due to the thousand separator it causing problems in the list iterations. See the code below as interpreted in the template. I have highlighted the values that have problems. Also note that I want thousand separator for other places, so it can not be turned off globally. I used the floatformat filter but no luck. data: [0.00, 0.00, 35,200.23, 2,910.36, 1,677.00, 0.00,], -
"'Template' object has no attribute 'strip'"
I am using python 3.6 on my local and jinja2 template code is working fine ,But on sever python version is 3.7 so while i am trying to update a resource then getting error "'Template' object has no attribute 'strip'" -
How to make Unlike with django-likes package?
I'm using django-secretballot and django-likes to make a simple like button. My problem with django-likes package that there is no example show how to make unvote / unlike after you liked an object.. I found this function 'remove_vote' in 'django-secretballot' but really I don't know how to use it with django-likes I will be glade if there is any example of how to use it. thanks -
File in PostgreSQL composite type in Django
I want to save file, which is in PostgreSQL user defined composite field. When saving file which is not in custom field, in save_form_data() setted attribute becomes FieldFile and that's probably what I want to happen with composite field too. When saving composite field however, I get the error "can't adapt type 'TemporaryUploadedFile'", since tuple element representing file, stays TemporaryUploadedFile. How do I save file in composite field? This is my composite field (models.py): class MyType(models.Field): name_in_field = models.CharField(max_length=100) file_in_field = models.FileField( upload_to=file_path, storage=OverwriteStorage() ) def db_type(self, connection): return "custom_field" def save_form_data(self, instance, data): # I want attribute to become tuple (CharField, FieldFile) # just like it happens with the file outside of MyType # but attribute becomes (CharField, TemporaryUploadedFile) # what is identical to data and throws error when saving # Default behavior: setattr(instance, self.name, data) # I suppose I should write something like below, but what exactly? # setattr(getattr(instance, self.name), "name_in_field", data[0]) # setattr(getattr(instance, self.name), "file_in_field", data[1]) I've prepared repo for testing. -
How to match specific word in url.py in django?
I am new to dJango. I got the following url address http://127.0.0.1:8000/polls/%7B%25%20url%20'main'%20%25 but my app didn't find the address when looked up my urls.py as below. from django.urls import path from . import views urlpatterns = [ path('main', views.main, name='main'), path('pageA',views.pageA,name='pageA') ] I know that it can be resolved by applying the regular expression but I failed to get the right solution. -
Django Default value for a custom user field is not added into the db tables
I'm working on a project using Python93.7) & Django(2.2) in which I have extended the user model to add a custom filed for the user. I have defined a default value for that field in the model but when I leave it empty on the form sibmission the default is not added into the DB. Here's my model: From models.py: class CustomUser(User): team = models.CharField(max_length=255, default='NotInGroup', blank=True) Here's my view: From views.py: if form.is_valid(): print('form is valid') print(form.cleaned_data['team']) if not form.cleaned_data['team'] == '': form.team = form.cleaned_data['team'] else: form.team = 'Default' print(form.team) user = form.save() If I leave it empty for form.team it prints out the Default' but not saved in DB. Here's my form: **Fromforms.py`:** class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('first_name', 'last_name', 'email', 'username', 'team', 'password1', 'password2') -
Google font not displaying
I am trying to get a Google font to load from css to my html template for my application. Can't get the "Upload schtuff" to assume the Bangers font. Here's the base.html: {% load static %} <!doctype html> <html> <title>{% block title %}Upload Schtuff{% endblock %}</title> <head> <link href="//fonts.googleapis.com/css?family=Bangers&display=swap" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> </head> <body> <div> <h1><a href="/">Upload schtuff </a></h1> </div> </body> </html> Here's the static/uploader/style.css: ''' h1 a, h2 a { color: #714D91; font-family: 'Bangers', cursive; } ''' I've also tried importing the font to the style sheet with @import url('https://fonts.googleapis.com/css?family=Bangers&display=swap'); Also tried importing it to the .html file <style> @import url('https://fonts.googleapis.com/css?family=Bangers&display=swap'); </style> It's got to be my link href lines, right? Thanks in advance!