Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Learning Backend Development
I am looking to create a courses website similar to https://brilliant.org/courses/ which allows users to create accounts and register for premade courses. I would like for each student to have their own dashboard which displays various statistics like how much time they spent on a course and what courses they are enrolled in. This is for a nonprofit organization aimed at elementary through early high school students. Currently, I know the very basics of frontend development (HTML, CSS, JS) and some python however I am unsure where to start to learn backend development to actually create user accounts and courses. Since I am learning python on the side I would prefer to use Django, where is a good place to start for someone with absolutely no prior computer science or web dev experience? -
Django __iregex crashing for regular expression ^(\\. \\.)$
When I try to make an __iregex call using the regular expression '^(\\. \\.)$' I get: DataError: invalid regular expression: parentheses () not balanced I am using PSQL backend so the django documentation states that the equivalent SQL command should be SELECT ... WHERE title ~* '^(\\. \\.)$'; When I run this query manually through the PSQL command line it works fine. Is there some bug with Django that I don't know about that is causing this to crash? -
When I am trying to add an object or update any objects, Django gives null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, pbkdf2_sha256$150000$nZ78tMu3I9nQ$auiF+N/RUqIHgVBMUL6kjAX8zjPPyc..., null, f, dude, , , , f, t, 2021-03-31 19:16:57.392614+00). enter image description here -
Exception Value TodoList matching query does not exist
I am using SQLite as backend db for django application. I have one table in the DB called TodoList having around 101 records. When I am triggering delete action from HTML, entries between id 1-9 are getting deleted, however, ids more than 9 having no effect. If i try to delete 101th entry i am getting the following error in the browser. Is there any limit with django or sqlite on number of database table records? DoesNotExist at / TodoList matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:7000/ Django Version: 3.0.13 Exception Type: DoesNotExist Exception Value: TodoList matching query does not exist. Exception Location: C:\My_Data\Rapid\.venv\py3.9.0\lib\site-packages\django\db\models\query.py in get, line 415 Python Executable: C:\My_Data\Rapid\.venv\py3.9.0\Scripts\python.exe Python Version: 3.9.0 Python Path: ['C:\\My_Data\\Rapid\\Experiences\\Coding\\Python\\Hands-On\\00.django_hands_on\\todoapp', 'C:\\My_Data\\Rapid\\.venv\\py3.9.0\\Scripts\\python39.zip', 'c:\\users\\ramesh.petla\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\ramesh.petla\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\ramesh.petla\\appdata\\local\\programs\\python\\python39', 'C:\\My_Data\\Rapid\\.venv\\py3.9.0', 'C:\\My_Data\\Rapid\\.venv\\py3.9.0\\lib\\site-packages', 'C:\\Users\\ramesh.petla\\AppData\\Roaming\\Python\\Python39\\site-packages', 'c:\\users\\ramesh.petla\\appdata\\local\\programs\\python\\python39\\lib\\site-packages'] Server time: Wed, 31 Mar 2021 19:30:22 +0000 Environment: Request Method: POST Request URL: http://127.0.0.1:7000/ Django Version: 3.0.13 Python Version: 3.9.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todolist'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\My_Data\Rapid\.venv\py3.9.0\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\My_Data\Rapid\.venv\py3.9.0\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\My_Data\Rapid\.venv\py3.9.0\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = … -
Create Table in Python-docx with Merge and Split functionality
Currently I am working on the project in which I am taking number of rows and column at frontend and Inserting data into it and sending JSON at backend. Tables have Merge and Split functionality How to create table on python docx enter image description here for example : enter image description here -
Django-Heroku: Data in models not persistent
I have deployed a web app with Heroku and developed using Django. Problem: Every time the app goes to sleep, and when it wakes up, objects in the Django models get reset to their original state (empty model). I am not entirely sure what is the problem I am facing here. What I suspect: db.sqlite3 file does not get updated when I make any changes. App resets to original state after waking up from sleep. Procfile gets run again. What have I tried: Searching Google for any leads on what might be the problem. Updating model locally before redeploying on Heroku. -
cv2.cvtColor mysteriously kills python worker without throwing exception
I'm getting very mysterious behavior when trying to run some basic functions in a python worker (using Django RQ). I am using a function (nested deep 8 to 10 stack frames in from the viewset's route) that results in the following error: "Work-horse was terminated unexpectedly (waitpid returned 11)" The image itself is an ordinary image with 1000 by 700 pixel with 3 channels. I'm not sure why this method is throwing this strange error in the code (cv2.cvtColor() I know this because I stepped through it and it ends at the same spot every time), and not even generating any kind of exception. There is a BaseException clause that attempts to catch this, but it fails, the worker just deems the job as having failed and moves it to the FailedJobRegistry and exits the entire stack frame. I attempted to increase my environment's memory that the worker is running in (PyCharm) to 5GB, but it still results in this error. Then I reinstalled opencv-contrib-python and it failed. My team needs to use the opencv-contrib-python repository because we make use of SIFT. How can I diagnose what this obtuse error message means? I can't see anything in the logs that … -
Concat Nested Dictionary value to string
Would like to convert dictionary_list = { hello_world = { 'Hello': 'World' }, myName = { 'Im': 'Harry' } } to Hello world Im Harry I am looping through the nested dictionary by using the following for loop: for key, value in dictionary_list.items(): Just need to concat value into an empty string. -
Trying to execute django-admin makemessages in windows 10
I´m trying to generate translation file using command django-admin makemessages -l pt-br in Windows 10 but unfortunately the files aren´t generated. Here the steps that I followed: Installed gettext library from mlocati. I also tried several options from django i18n: Make sure you have GNU gettext tools , this process is more manual. As the result when i run django-admin makemessages -l pt-br looks like that Django is executing something but the directory is not generated in the end. Here are some peace of code that I have views.py from django.shortcuts import render from django.utils.translation import gettext as _ def index(request): context = { 'hello': _('Hello!') } return render(request, 'index.html', context) settings.py """ Django settings for translation_example project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3^*d$5b7$r2$t-0cxmef22l5_)t^cn9i-xkq48zen$u*67)tvm' # SECURITY WARNING: don't run with debug turned on in … -
Start Django modelformset with values from instances?
This question asks about initializing a Django model formset with instances. The answer is: use the queryset argument. But what if I want a new formset with a copy? That is, all the values of those instances, but not the instances themselves (i.e., they'll be extra and not yet bound). My current solution is to make the call to formset partial (so I can fill in "extra"), and copy over all the values. I don't love this, because if we add fields to Item, then we have to go and add those fields to the copy. Is there a better way? import functools PartialItemFormset = functools.partial( forms.modelformset_factory, Item, formset=BaseItemFormSet, fields=('name', 'description')) EmptyItemFormset = PartialItemFormset(extra=2) the_items = Items.objects.filter(...) copy_formset = PartialItemFormset(extra=len(the_items))( queryset=Item.objects.none(), # TODO: Is there a better way than copying all the fields? initial=[{'name': item.name, 'description': item.description} for item in the_items]) -
forms in Django does not register the data in the database
I'm stuck I try a lot of things to make it work, but always the same problem the form dose note save the data at all and the any error that I get is the message error (what I writ in the message) all i get is a change in the url like this http://127.0.0.1:8000/appointement/create_appointement_2?patient=patient+12&initial-patient=patient+12&doctor=2&date=2021-04-02&start_time=16%3A30 is there anything that can show me the error or if anyone have this problem be for a few hits will be awesome? this is my models .py class Appointment(models.Model): user_ho_add = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_ho_add_appointment') patient = models.CharField(null=True,max_length = 200, default=defaultTitle) doctor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctor_app') date = models.DateField(null=False, blank=False, default=timezone.now) start_time = models.TimeField(null=True, blank=True, default=timezone.now) end_time = models.TimeField(null=True, blank=True, default=timezone.now) and this is my forms.py class AppointmentForm_2(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) # patient = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.PATIENT)) date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), input_formats=settings.DATE_INPUT_FORMATS) start_time = forms.DateField(widget=forms.DateInput(attrs={'type': 'time'}), input_formats=settings.TIME_INPUT_FORMATS) class Meta: model = Appointment fields = ('patient', 'doctor', 'date', 'start_time') and this is the views.py @login_required def create_appointement_2(request): user = get_user_model() patients = User.objects.filter(type_of_user=TypeOfUser.PATIENT) form_appointment_2 = AppointmentForm_2(request.POST or None) if request.user.is_doctor() or request.user.is_reception(): if request.method=='POST': form_appointment_2 = AppointmentForm_2(request.POST or None) user = get_user_model() if form_appointment_2.is_valid(): form_appointment_2.save(commit=False) form_appointment_2.user_ho_add = request.user # form_appointment.end_time = form_appointment.start_time + timedelta(minutes=30) start_time = form_appointment_2.start_time future_time … -
Django HTML page returns the same id object from database
I have a few objects on my database, and my html page should open a new tab with the respective “id’s” when I click on the objects. But when I click on them It opens a new tab always with the “id:1”, even if I click on the second object, it returns me the “id” of the first item, instead of the second one. How can I make it to display the respective ‘id’ of the item when I click on it? Here is the screenshoot of the page Here is the openned tab after I click on the 2nd object, displaying the 'id' of the first object. Here is the HTML code of the page uploaded: https://github.com/khavro21/my_html/blob/main/index.html I can´t find out what is missing on my code, do you have any idea? Thank you! -
Can't migrate after makemigrations on django
everyone. I newbie in this field. So, After I finished makemigrations. then I migrate this error code occurs. I try to solve it but still stuck. please guide, I attach my error code as below. (venv) C:\Users\hp\Desktop\Taskly_App\src>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, house, oauth2_provider, sessions, social_django, task, users Running migrations: Applying task.0002_auto_20210331_2329...Traceback (most recent call last): File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 411, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: table "task_tasklist" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\hp\Desktop\Taskly_App\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) … -
Django Post Save Signal goes on looping
The below code goes on looping , after processing the value for profile_pic my use case: when the value for profile_pic is passed while saving the model , I need to perform some operations on it and then save it , if the value is null nothing should happen @receiver(post_save,sender=User) def resize_image(sender,instance,created,*args,**kwargs): if instance.profile_pic: ###### doing some operations on profile_pic ###### instance.profile_pic=image_process(image) instance.save() -
Paginate constantly updating feed in django?
The obvious problem is that loading further pages in an updating feed would lead to loading some content more than once. Is there a good built-in way to perform such a task? I think the paginator object wont really work unless used with reversed queryset which however is allegedly very memory inefficient. Another solution I could think of (when ordering by time) is sending a timestamp of the last object on the page, saving it in front-end and for the next request send this time to django do a time__gte for n+1 objects and slice off the first one. Would probably do the trick quite well but its anything but intuitive. Is there a better way to go about it? -
Update a value that is the sum of two range values
I recently started to work on Django and JavaScript, and currently working on Range items. I successfully managed to have two functioning scales and to update their value next to them each time the user is modifying them. <p>You have <span id="demo1"></span> spent dollars on this item.</p> <div class="input-group"> <p class="input-group-text">0<input type="range" id="myRange1" name="myRange" min="0" max = "120" step="5" class="form-range"></p> <p class="input-group-text"> 120</p> </div> var slider1 = document.getElementById("myRange1"); var output1 = document.getElementById("demo1"); output1.innerHTML = slider1.value; slider1.oninput = function() { output1.innerHTML = this.value; } <p>You are spending<span id="demo2"></span> dollars on this item.</p> <div class="input-group"> <p class="input-group-text">0<input type="range" id="myRange2" name="myRange" min="0" max = "120" step="5" class="form-range"></p> <p class="input-group-text"> 120</p> </div> var slider2 = document.getElementById("myRange2"); var output2 = document.getElementById("demo2"); output2.innerHTML = slider2.value; slider2.oninput = function() { output2.innerHTML = this.value; } Now, what I am trying to get is to have a value that is the sum of the two values, and that is updating as soon as the user is modifying one of the two scales. I tried the following: <p>You have spent <span id="demo_total"></span> dollars in total.</p> var value_total = 0 var output_total = document.getElementById("demo_total"); output_total.innerHTML = 120 // Display the default slider value value_total.value = function() { output_total.innerHTML = parseInt(output1.innerHTML) + … -
How do I get the client Remote Port number in a Django?
I know I can use request.META['REMOTE_ADDR'] to get the client's IP in my django view function. However, I have no idea how to get the client remote port number. For example, you can see your own remote port number on the site below: https://www.myip.com/ Remote Port MY VIEW PY: if request.user.is_authenticated: gelenIleti = request.META.get('HTTP_X_FORWARDED_FOR') if gelenIleti: ip = gelenIleti.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') portNumarasi = request.META['SERVER_PORT'] logger.info(' ' + 'LOG KAYDI :' + ' ' + ' KULLANICI : ' + request.user.username + ' ' + ' IP : ' + ip + ' ' + ' SERVER PORT : ' + portNumarasi) -
What do I set date_field to in DayArchiveView for django-recurrence?
I have a model for booking slots and a DayArchiveView in django. I am using django-recurrences to make my events recurrent https://django-recurrence.readthedocs.io/en/latest/index.html views.py class ClubBookingArchiveView(DayArchiveView): queryset = BookingSlot.objects.all() date_field = "recurrences" #what should I put here? allow_future = True allow_empty = True models.py class BookingSlot(models.Model): start_time = models.TimeField("Start Time") end_time = models.TimeField("End Time") recurrences = RecurrenceField() I am wondering what I should set the date_field to in my DayArchiveView. Or if anyone can think of anyway I can get around this, is there like a get_date_field() I can override or something, or will I have to generate a view completely from scratch? -
Can't write to a file with Django in Nginx
I have deployed a Django web app using uWSGI and Nginx, but the app runs into an error when trying to create a file inside a specified folder. Inside my views file, I specify a function which writes to a file using "with open". This function writes the file to a folder named 'output' inside the Django project folder. When I run the Django server, all the functionality works well, but, when I run the Nginx server, it gives me an error exactly where the "with open" is. I have already tried to switch the ownership of the 'output' folder, but it did not work. Also tried to run 'sudo chmod -R www-data:www-data' with my whole project folder as an attribute, but I had no success. I would please like to have more insight on how to fix this issue. The problem is likely about my permissions, but I have tried everything in my knowledge to fix it but it did not work. In attachment, I am sending an image of the output of the 'ls -la' command inside my Django project folder. Also, the guide I have followed can be found here: https://tonyteaches.tech/django-nginx-uwsgi-tutorial/. output of the ls -la command … -
How to use django-select2 in wagtail?
I have a model with many-to-many relation. And for wagtail I used the following: from django_select2.forms import Select2MultipleWidget from wagtail.admin.edit_handlers import FieldPanel panels = [ FieldPanel('field_name', widget=Select2MultipleWidget ] But select2 is not showing up. What can be done? -
Django Models get value from a foreign key
I have the following model: class Check (models.Model): user_id = models.ForeignKey(Client, on_delete=models.CASCADE) client = Client.objects.get(pk=1) #change id according to user_id client_birth = client.birth client_gender = client.gender What I need is to get those birth and gender values from model Client, but according to the value id set on user_id. Is that possible? -
I cannot install Django in my Virtual Environment
I wanted to install Django in my virtual environment (which was completely working), but got this whole lot of errors. Anyone know what to do? I just typed this in PowerShell: pipenv install django And got this: Error: An error occurred while installing django! Error text: Collecting django Using cached Django-3.1.7-py3-none-any.whl (7.8 MB) ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM Pipfile.lock!. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them. django from https://files.pythonhosted.org/packages/b8/6f/9a4415cc4fe9228e26ea53cf2005961799b2abb8da0411e519fdb74754fa/Django-3.1.7-py3-none-any.whl#sha256=baf099db36ad31f970775d0be5587cc58a6256a6771a44eb795b554d45f211b8 (from -r c:\users\vojtěch\appdata\local\temp\pipenv-e9otm_0m-requirements\pipenv-sj4h6g3_-requirement.txt (line 1)): Expected sha256 baf099db36ad31f970775d0be5587cc58a6256a6771a44eb795b554d45f211b8 Got 764ad5e659cd3a7740b314806b39c67501c6136a21d23652515df3bfb4023d76 -
how to add quantity to products in cart django
so I am trying to add a option to set quantity for my products before I add them to the cart and while they are inside the cart something like thisexample my models.py class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) products = models.ManyToManyField(Product, blank=True) total = models. DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': products = instance.products.all() total = 0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal = total instance.save() m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through) def pre_save_cart_receiver(sender, instance, *args, **kwargs): if instance.subtotal > 0: instance.total = Decimal(instance.subtotal) * Decimal(1.08) # 8% tax else: instance.total = 0.00 pre_save.connect(pre_save_cart_receiver, sender=Cart) this is my views.py … -
How to align components in the bootstrap Navbar Properly?
I am developing an e-commerce website, but I cannot align the components in my navbar properly. I just copied the navbar code from the bootstrap site and pasted it inside my main.html file. Here is the navbar code: Ecom <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'store' %}">Store<span class="sr-only"></span></a> </li> </ul> <div class="form-inline my-2 my-lg-0 "> <a href="#"class="btn btn-warning">Login</a> <a href="{% url 'cart' %}"> f <img id="cart-icon" src="{% static 'images/cart.png' %}"> </a> <p id="cart-total">0</p> </div> </div> </nav> Below is the Navbar image (all components are jumbled):- I want to align the login button and cart image symbol to right and also reduce the size of the navbar and login button -
Pylint does not acknowledge a module
I'm new to Django and haven't used much of the Python tooling. The following line of code is being flagged by Pylint, despite working without issue. # main/management/commands/send_policy_notifications.py from main import models No name 'models' in module 'main'pylint(no-name-in-module) The file structure follows: . ├── Pipfile ├── Pipfile.lock ├── .env ├── .pylintrc ├── main │ ├── __init__.py │ ├── access_conditions.py │ ├── admin.py │ ├── apps.py │ ├── authentication.py │ ├── flags.py │ ├── management │ │ └── commands │ │ └── send_policy_notifications.py │ ├── tests.py │ ├── urls.py │ └── views.py └── manage.py How can I configure Pylint to acknowledge that main contains models? I'm using Visual Studio Code.