Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent form from resetting automatically in django
I created a dropdown in Django app but after selecting an option it resets back to its default value. Here are my attempts for preventing this. What am I doing wrong here ? Any help is appreciated - Attempt1 - <form method=post id='test' name="test" onChange="javascript: document.forms['test'].submit()">{% csrf_token %} <select name="mydropdown" id="mydropdown"> <option value = "option1" {% if selected_option == option1 %}selected{% endif %}>option1</option> <option value = "option2" {% if selected_option == option2 %}selected{% endif %}>option2</option> <option value = "option3" {% if selected_option == option3 %}selected{% endif %}>option3</option> <option value = "option4" {% if selected_option == option4 %}selected{% endif %}>option4</option> </select> </form> I get the selected_option fields from the views file - selected_option=request.POST.get("test") Attempt 2 - <form method=post id='test' name="test" onChange="javascript: document.forms['test'].submit()">{% csrf_token %} <select name="mydropdown" id="mydropdown"> <option value = "option1" {% if mydropdown == option1 %}selected{% endif %}>option1</option> <option value = "option2" {% if mydropdown == option2 %}selected{% endif %}>option2</option> <option value = "option3" {% if mydropdown == option3 %}selected{% endif %}>option3</option> <option value = "option4" {% if mydropdown == option4 %}selected{% endif %}>option4</option> </select> </form> -
is it possible to return a single value from Q in Django?
I am using the Django ORM and I would like to do something like: self.queryset.annotate(cupcake_name=Q(baked_goods__frosted_goods__cupcakes__cupcake_id='xxx')) but return the cupcake name somehow so I can serve it as a data attribute. -
Populating Field in Form with Images in Django
I'm trying to populate a field with images from a model in Django. The idea is that the user will enter the name of their product, then ultimately an API with google images will look that up and populate a field on the next page with a couple images to select. At this stage, I'm just trying to get a field on the form to show multiple images for the user to select and I'm having a hard time. Here's some of my code, any input is helpful. I know there is a lot out there around this topic and I've looked through a lot but I'm still stuck. My most recent attempt was to create a custom Widget, I'm really open to any solution that will work. I'm really not a Django/Python wizard so bear with me :) Thank you! Models.py class ProductImage(models.Model): imageId = models.AutoField(auto_created=True, primary_key=True) image = models.ImageField(upload_to='images',null=True,blank=True) def __str__(self): return str(self.image) class Item(models.Model): itemId = models.AutoField(auto_created=True, primary_key=True) itemName = models.CharField( "Name", max_length=1024, ) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category' ) itemImage = models.ForeignKey(ProductImage, on_delete=models.CASCADE, related_name='photo', default="", ) itemOwner = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='my_items' ) itemAvaialable = models.BooleanField() costPerItem = models.IntegerField(verbose_name='Cost per Item (USD)') itemDescription = models.TextField(null=True, blank=True) itemAddedDate … -
How to query reverse many to many in django
I have a model Profile (user's profile) and it has many to many relation to self named followings. This manages followers / followings system like one in twitter. class Profile(models.Model): followings = models.ManyToManyField('self', blank = True, related_name = 'followers') I can get followings just get followings of an User but how to query followers of a user using django model query? -
Edit the values from a row in the HTML table
I have a table that looks like that: {% for item in records %} <tr> <td> <form action="{% url 'update_record'%}" method="post">{% csrf_token %} <input type="text" class="title" value="{{ item.title }}" size="20" maxlength="30" /> <input type="hidden" value={{ item.id }} name="new_title" /> <input type="submit" value="edit" /> </form> </td> <td> <input type="text" class="result" value="{{ item.results }}" size="10" maxlength="20" readonly /> </td> </tr> {% endfor %} Both fields (title, result) have values already but I am trying to edit their value and then send the new title value to my Django view : @csrf_exempt def update_record(request): # do things with the new title value sleep(3) return redirect('profile') and here is my urls.py , in case it is helpful in any way: urlpatterns = [url(r'^update_record/', views.update_record, name='update_record'),] I tried switching between post and get methods , using AJAX, and almost anything related I could find but nothing seems to work . The current code doesn't produce any errors but I don't see the fields at the "request.POST" dictionary. Any method would be highly appreciated because I don't know what to try at this point except analytical Ajax classes! -
Django | JS variable inside dynamic URL
I'm trying to pass a javascript variable inside a dynamic url using Django. I have the following path path('task-update/<str:pk>/', updateTask, name='task-update'), I'm able to retrieve the "Task" fields I created (id, title, description, ...) depending on what task I select inside the HTML (this is done using AJAX and the Django-REST Framework). However, I'm having some trouble on rendering javascript values inside dynamic urls var url = `{% url 'task-update' pk=${activeItem.id} %}` The ${activeItem.id} is where I'm having some trouble, I tried assigning it to a variable and passing that into the URL but it doesn't work -
Django: Setting for testing with multiiple schemas
We are working on a project which uses a legacy database. First, we ran django manage.py inspectdb to create the models.py file. Then we tried many different ways and it seems like setting database like this works: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'anrakutei', 'OPTIONS' : { 'options': '-c search_path=anrakutei,smart_assist' }, 'USER': 'postgres', 'PASSWORD': '*****', 'HOST': '****', 'PORT': '****', }, 'master': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'anrakutei', 'OPTIONS' : { 'options': '-c search_path=anrakutei,master' }, 'USER': 'postgres', 'PASSWORD': '*****', 'HOST': '*****', 'PORT': '****' }, } We also set the db_table in class Meta to point to the search path like this '"master\".\"m_kengen"'. But then the problem happened when Django trying to create Test database. The error is Unable to create django_migrations table (No schema has been created to select in ) We then set it like this and the test can run. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'anrakutei', 'OPTIONS' : { 'options': '-c search_path=anrakutei,smart_assist' }, 'USER': 'postgres', 'PASSWORD': '******', 'HOST': '*****', 'PORT': '****', 'TEST': { 'MIRROR': 'default', } }, 'master': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'anrakutei', 'OPTIONS' : { 'options': '-c search_path=anrakutei,master' }, 'USER': 'postgres', 'PASSWORD': '*****', 'HOST': '******', 'PORT': '****' }, } But now the problem is … -
syntax error at or near "ON" django postgress
I am doing a Many to Many relationship. But when adding values to that field I get an error. class pA(models.Model): hu = models.CharField(max_length=120, default="") class pB(models.Model): jo = models.ManyToManyField(pA) This is the error I get when adding a value to pB: error de sintaxis en o cerca de «ON» LINE 1: ...dule_main_pb_jo" ("pb_id", "pa_id") VALUES (2, 1) ON CONFLIC... ^ This error appears only when I use a postgres DB, but not SQLite. -
GeoDjango: Unable to access feature from Layer object using feature ID (IndexError)
I am working through the GeoDjango tutorial using the world borders data found here: (https://docs.djangoproject.com/en/3.1/ref/contrib/gis/tutorial/). The problem I am having is with accessing individual features from a Layer object. I have tried using list slices and accessing an object by is feature id without success. I have also tried adding "from django.contrib.gis.gdal import *" just in case something was missing, but that didn't help either. I would be very appreciative if someone could please share any thoughts on what might be going wrong or if I have made a mistake along the way. Please see my code below for further explanation, thank you. $ python manage.py shell # Following the GeoDjango tutorial step by step >>> from pathlib import Path >>> import my_app >>> world_shp = Path(my_app.__file__).resolve().parent/'data'/'world.shp' >>> from django.contrib.gis.gdal import DataSource >>> ds = DataSource(str(world_shp)) >>> print(ds) C:\path\to\my_app\data\world.shp (ESRI Shapefile) >>> print(len(ds)) 1 >>> lyr = ds[0] >>> print(len(lyr)) 246 # The Layer object's features exist >>> for feature in lyr: ... print(feature.fid) ... 0 1 2 3 ... 245 # Attempt to access Feature object at index[0] >>> lyr[0] Traceback (most recent call last): File "<console>", line 1, in <module> File "...\src\venv\lib\site-packages\django\contrib\gis\gdal\layer.py", line 47, in __getitem__ return self._make_feature(index) … -
What is the best way to structure files to implement a front end (React.js) to an already established backend (Django)?
This may seem subjective, but the reason I am asking on this platform is because I feel like beginner programmers will run into this problem again in the future, and being a beginner programmer, I would like some insight to best practices in full stack file structure. Thanks in advance! So I started out on my project by building it with Django to understand how databases work. I built a decent database system, and so in preparing to move onto iteration 2, I want to now use React.js to build a better frontend. But, I have a lot of relevant Django code that iteration 2 will use again. What is the best way to structure my files to begin building the frontend with React.js after I've already established my backend? I will attach the iteration 1 file structure: C:. ├───.idea │ ├───inspectionProfiles │ └───shelf │ └───Uncommitted_changes_before_Merge_at_13-Mar-21_15_59_[Default_Changelist] ├───AIAD │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───comments │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───departments │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───directMessage │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───friends │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───main │ ├───migrations │ │ └───__pycache__ │ ├───Templates │ │ └───main │ └───__pycache__ ├───media … -
Django @api_view decorator runs before main function?
I have a silly problem, I don't know why but @api_view decorator get called after main function execution. I am using Django rest framework with simple JWT, and set some prints in simple JWT package and also in my function and compared to another view function with same structure and some how results were different. in the working view function JWT prints appears first but in below view function the prints order were vice versa. @api_view(['GET']) def fetch_groups(request): print('fetch_group user is {}'.format(request.user)) user = request.user groups = Group.objects.filter(company__exact=user.company,visible_to__exact=user) data = FetchGroupsSerializer(data=groups) return JsonResponse(data=data) I don't know what I had possibly done wrong -
Django 3 keeps using the admin templates for email reset
I tried following the other posts around this topic, but so far nothing worked. Often other post are about Django 1. For some reason Django keeps ignoring the password_reset_email.html file. I have a login.html in the same folder (./myapp/templates/registration/password_reset_email.html) which is used, but password_reset file is ignored. I tried different location of the template folder. Tried providing the path in the URL's patterns: path('accounts/password_reset/', auth_views.PasswordResetView.as_view(html_email_template_name='registration/password_reset.html')), or just path('accounts/', include('django.contrib.auth.urls')), Tried setting the settings accordingly: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'omics_server', 'templates'), os.path.join(BASE_DIR, 'pipelines', 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] But nothing worked. The templates looks like this: {% extends 'base.html' %} {% block title %}Forgot Your Password?{% endblock %} {% block content %} <h1>Forgot your password?</h1> <p>Enter your email address below, and we'll email instructions for setting a new one.</p> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Send me instructions!"> </form> {% endblock %} I don't understand why templates/registration/login.html works but not the other file. -
How can i use join?
I have this MYSQL statement SELECT IF(NOT op_tariff_id=0, (SELECT tariffs.name FROM tariffs WHERE id = op_tariff_id), (SELECT tariffs.name FROM tariffs WHERE id = tp_tariff_id) ) FROM devices WHERE (id = calls.src_device_id AND user_id = calls.user_id) OR (id = calls.dst_device_id AND user_id = calls.user_id) AND id > 0 I try to use join, but it doesn't work, any suggestions? postscript is a django RawSQL statement SELECT IF(NOT devices.op_tariff_id=0, (SELECT tariffs.name FROM tariffs INNER JOIN devices WHERE tariffs.id = devices.op_tariff_id), (SELECT tariffs.name FROM tariffs INNER JOIN devices WHERE tariffs.id = devices.tp_tariff_id) ) FROM devices INNER JOIN calls ON (devices.id = calls.src_device_id AND devices.user_id = calls.user_id) OR (devices.id = calls.dst_device_id AND devices.user_id = calls.user_id) AND devices.id > 0; -
.gitlab-ci mysql service in Django
I'm learning to use Gitlab CI and I'm trying to configure .gitlab-ci file to run CI into my Django project. I have the following .gitlab-ci file: stages: - test variables: MYSQL_DATABASE: $DB_NAME MYSQL_USER: $DB_USER MYSQL_PASSWORD: $DB_PASSWORD services: - mysql:8.0 test: image: alpine:3.13 stage: test script: - ...(up the app)... I have configured the environment variables in the gitlab (Settings -> CI/CD -> Variables) And I have the following DB configuration in my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': getenv('DB_NAME'), 'USER': getenv('DB_USER'), 'PASSWORD': getenv('DB_PASSWORD'), 'HOST': getenv('DB_HOST'), 'PORT': getenv('DB_PORT'), 'TEST' : { 'NAME' : f"test_{getenv('DB_NAME')}", } } } When I run this, all the installation is successfully but at moment to run test I have the following error: django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'mysql' (-2)") Why it happens if in Gitlab Documentation said that if I use the mysql services it's the host that I need to configure. -
How can I fix Django SQLite3 error on AWS?
I am trying to run a django project on an EC2 server, however, when I run python3 manage.py runserver, it returns this error, django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17).. I then check to see what version of SQLite3 is running on my python installation on my EC2 server by running sqlite3.sqlite_version, and it returns 3.7.17. So I then try to update SQLite3 using the default AWS EC2 Amazon Linux package manager, yum, by running yum install sqlite. It then returns this, Package sqlite-3.7.17-8.amzn2.1.1.x86_64 already installed and latest version, even though it is not the latest version. How can I install the latest version of SQLite3 to fix this? -
ImportError: cannot import name 'User'
I created custom save method for my class User. Because I have to create DriverRegistration object when I create User object. When I added only method save i received an error the code works fine without this method ImportError: cannot import name 'User' from 'backend.apps.users.models' (/app/backend/apps/users/models/__init__.py) How can I fix the error? Init file looks fine: from .user import User from .driver_registration import DriverRegistration users.py class User(AbstractBaseUser, PermissionsMixin, TimeStampMixin): objects = UserManager() first_name = models.CharField( "first name", max_length=30, blank=True, null=True ) ... def save(self, *args, **kwargs): super().save(*args, **kwargs) # Create User object driver_registration = DriverRegistration.objects.create(user=self.pk) driver_registration.save() class UserManager(BaseUserManager): def create_user( self, phone_number, password, device_id=None, first_name=None, last_name=None, ): if not phone_number: raise ValueError("Users must have an phone number") user = self.model( phone_number=phone_number, device_id=device_id, first_name=first_name, last_name=last_name, ) user.is_staff = True user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, password): user = self.create_user(phone_number, password=password) user.is_superuser = True user.user_type = UserType.USER_TYPE_MANAGER user.device_id = hashlib.md5( str(random.getrandbits(32)).encode("utf-8") ).hexdigest() user.save(using=self._db) return user driver_registration.py class DriverRegistration(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, ) -
Python Django performing independent interval tasks
It became necessary, in certain situations, to create a periodic task that will check the state of the user every minute. For this I am using django_celery_beat + PeriodicTask + IntervalSchedule When this task is 1, everything is fine. But when a new one is created for another user, the task execution shifts: for example, the first user was checked every minute starting from 10:14:40, the next check should have been at 10:15:40, but a new task was created at 10:15:35 and both users end up being verified at 10:16:35 How can I solve my problem? each user should be checked every minute within its own interval. -
Django deploy Pythonanywhere
The site work fine on my localhost, but I have problems deploying It. wsgi log -
Adding a parent class between models.Model and my Model classes
I have different apps that pertain to different functionalities, but typically they all follow more or less the same patterns. In order to have easy (and flexible) access to the data I need in my templates, I need to implement some methods in my Models. For instance, these methods would be needed in a few different apps in order to populate a list view that contains only a small subset of all the fields of the model: class Produit(models.Model): # fields to present the summary summary_table_headers = ["id","no_prod","descfr","descang", ...] @classmethod def get_list_summary_headers(cls): """ returns the table headers so the template can easily populate <th>""" # return [h for h in cls.summary_table_headers] return [(h, cls._meta.get_field(h).verbose_name) for h in cls.summary_table_headers] def get_fields_values(self): return [field.value_to_string(self) for field in Produit._meta.get_fields()] @classmethod def get_fields(cls): fields = [field.name for field in Produit._meta.get_fields()] return fields Then I have bunch of different apps, but all needs to present a summary list view of sorts. Things are still very much in development, so I wanted to be able change what is to be part of the summary in ONE place (e.g. the models). Then the template just iterates and renders everything that's handed to it. If I need to … -
Connecting Django User model with custom models error using one_to_one_field
models.py This is the models.py file of my django project. I am getting this error in 5 line of the code below.I wanted to connect django default User model to my model by OneToOneField to provide multiple account functionality to my project. but I am stuck at this error that I don't understand. plz, help. from django.contrib.auth.models import User # Create your models here. class DailyTrack(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, related_name = 'Profile', default='') income = models.IntegerField() expense = models.IntegerField() added = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Income {self.amount} Income {self.amount}' error is in the 4th line at the default field, I tried removing default or adding it but I am unable to understand this. There is an error for Operations to perform: Apply all migrations: admin, auth, contenttypes, dailytrackapp, sessions Running migrations: Applying dailytrackapp.0003_dailytrack_user...Traceback (most recent call last): File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'null' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\NIitin\Desktop\MultiProj\DailyTrack\manage.py", line 22, in <module> main() File "C:\Users\NIitin\Desktop\MultiProj\DailyTrack\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 395, in execute … -
how to fix "'coroutine' object has no attribute 'get' and UploadFileForm() takes no arguments
im trying to write a Asynchronous File Uploads with Django Forms. form.py: from django import forms class UploadFileForm(forms.Form): file_name = forms.CharField(max_length=30, min_length=3) file = forms.FileField() views.py: import aiofiles from django.shortcuts import render from .forms import UploadFileForm async def handle_uploaded_file(file): """awaitable function to upload a file and put it in media folder""" async with aiofiles.open(f"media/{file.name}", "wb+") as destination: for chunk in file.chunks(): await destination.write(chunk) async def upload(request): if request.method == 'GET': form = UploadFileForm() context = {'form': form} return render(request, 'upload.html', context) if request.method == 'POST': form = UploadFileForm(data=request.POST, files=request.FILES) if form.is_valid(): await handle_uploaded_file(request.FILES['file']) return render(request, 'upload.html') i got these errors: TypeError: UploadFileForm() takes no arguments "'coroutine' object has no attribute 'get'" hope you guys can help me to fix this:) -
username and password in Qrcode with django
I have a simple qr scanner and qrcode in python. This opens a website after scanning. What i want: the django username and password in a qrcode. So the user scans the qr and logs in. I dont know how to convert the password of the user because of the hash. Here is the code for creating the qrcode (from model). def create_Qrcodes(sender, instance, created, **kwargs): if created: url = the url to go to after scanning the qrcode new_qrcode = Qrcodes.objects.create(vacature=instance) qrcode_img = qrcode.make(url + str(instance.id) + "/") new_qrcode.url_vacature = url + str(instance.id) + "/" new_qrcode.save() canvas = Image.new('RGB', (600,600), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) random_nummer = random.randint(10000000, 90000000) fname = f"{new_qrcode.id}{random_nummer}.png" buffer = BytesIO() canvas.save(buffer, 'PNG') new_qrcode.image.save(fname, File(buffer)) canvas.close() So what i want is an qrcode of the username and password. -
Why is my object's new data not saving inside a function
newbie to Django here. So I made a model with an attribute being a list. Then I made an instance of it. Then I have a function that has a for loop that appends to the "class list" attribute of the object. This is not permanently saving the list data to the attribute of the object (isn't that the whole point of model objects?). I am very confused on how to do that. class Mymodel: class_list = [] my_object = Mymodel() def myFunction(): for loop: my_object.class_list.append(some_value_that_I_want) return something_unrelated -
Should I use select_for_update in my django application with postgresql database?
I am currently building a booking tool (django and postgresql) where people book spaces in a location. The location has limited capacity and therefore might run out of space while a user is trying to book a space. I imagine that this could happen when another user books a place slightly before the current user is booking, e.g. if only 1 space is left, the other user might book too and the database cannot handle it. So my question is would you strongly advise using select_for_update or is there something else that might help me overcome this issue? -
how can I delete all non-matching query results in django?
Say I have a list of values list =['value1',value2'value3'...'...'] Is there a way I can run a query against a whole Db and delete any entries that don't match? The opposite of the below almost: models.objects.filter(value__in=list).delete()