Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check if image exists in Django template
I currently have a template that loops through a list of URLS, like so. {% for i in images %} <div class="col"> <p><a href="{{i}}"><img height="200" src="{{i}}"/></a></p> <p><a href="{{i}}">{{i|cut:"/uploads/"|truncatechars:20}}</a></p> </div> {% endfor %} The issue is at the time of rendering some of the images are not done processing. So how would I check if the image is available via the url? -
How to resend a cognito invite when credentials expire
here i need to resend the cognito invite to a user whose credentials expire before he signs up @staticmethod def get_set_cognito(sender, instance, *args, **kwargs): self = instance if self.pk is None: client = boto3.client('cognito-idp', region_name=settings.AWS_DEFAULT_REGION) # try: # # Check if the user exists in Cognito # existing_user = client.admin_get_user(Username=self.user.email, # UserPoolId=settings.COGNITO_USER_POOL_ID) # except client.exceptions.UserNotFoundException: # pass try: # if not existing_user: response = client.admin_create_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email, DesiredDeliveryMediums=['EMAIL'], UserAttributes=[ { 'Name': 'custom:backend_url', 'Value': settings.BACKEND_API_URL }, { 'Name': 'custom:backend_id', 'Value': settings.BACKEND_ID }, { 'Name': 'email_verified', 'Value': 'true' }, { 'Name': 'email', 'Value': self.user.email }, { 'Name': 'family_name', 'Value': self.last_name if self.last_name else ' ' }, { 'Name': 'given_name', 'Value': self.first_name if self.first_name else ' ' }, { 'Name': 'phone_number', 'Value': self.phone if self.phone else ' ' } ], ) self.user.username = response['User']['Username'] if(len(response['User']['Username']) < 3): logger.error("empty response from cognito for email - " + self.user.email) logger.error(response) self.user.delete() else: self.user.save() # else: # self.user.username = existing_user['Username'] # self.user.save() except client.exceptions.UsernameExistsException: # existing_user = client.admin_get_user(Username=self.user.email,UserPoolId=settings.COGNITO_USER_POOL_ID) existing_user = client.admin_get_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email ) self.user.username = existing_user['Username'] self.user.save() except Exception as e: logger.error( "there was an error trying to create cognito user", e) self.user.delete() Set MessageAction to "RESEND" to resend the invitation message to a user … -
How can i populate the user_id using Django Rest
I'm working on a small project using Django Rest, I would like to populate the user_id field each time a user submit a form. This is my code class ContactView(ListModelMixin, viewsets.GenericViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer def create(self, request): serializeObject = ContactSerializer(data = request.data, many=True) if serializeObject.is_valid(): contactObject = Contact.objects.all() contactSerializer = ContactSerializer(contactObject, many=True) return Response(contactSerializer.data, status = status.HTTP_201_CREATED) return Response(serializeObject.errors, status.HTTP_400_BAD_REQUEST) My Serializer : class ContactSerializer(serializers.ModelSerializer): #list_name = serializers.CharField(source="list.name", read_only=True) class Meta: model = Contact fields = '__all__' -
Form filled out but still invalid
I am trying to get data from a form and redirect if the form is valid. I am, however, seemingly not grabbing any data. In a test, I fill out each form with "test". I would expect these forms to be valid and redirect to a success page, and am unable to figure out where I am going wrong with my logic. Error: form.errors = <ul class="errorlist"><li>category<ul class="errorlist"><li>This field is required.</li></ul></li><li>comment<ul class="errorlist"><li>This field is required.</li></ul></li></ul> forms.py from django import forms class CandidateReportForm(forms.Form): category = forms.CharField(label='Category', max_length=10) comment = forms.CharField(label='Comment', max_length=1000) views.py from django.shortcuts import render from django.views import View from .forms import CandidateReportForm class CandidateReportView(View): form_class = CandidateReportForm form_template = 'Reports/candidate_report.html' form_submit_template = 'Reports/report_submitted.html' form_submit_error = 'Reports/report_error.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.form_template, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): return render(request, self.form_submit_template) else: print(f"form.errors = {form.errors}") return render(request, self.form_submit_error) html <div class="container"> <div class="card"> <h2 class="card-title">Report</h2> {{ form.as_p }} <form action="submit_candidate_report" method="post">{% csrf_token %} <input class="btn btn-primary" id="report" name="report" type="submit" value="Submit"> </form> </div> </div> -
Delete uploaded files when calling transaction.set_rollback() on the View
I have a simple file upload function as shown below: Model: class ImageUpload(models.Model): image = models.ImageField() Serializer: class ImageUploadSerializer(serializers.ModelSerializer): class Meta: model = ImageUpload fields = ['id', 'image'] View: class TestView(APIView): @transaction.atomic def post(self, request): # some logic code serializer = ImageUploadSerializer(data={ 'image': request.FILES['file'] }) if serializer.is_valid(): serializer.save() if something_bad_happen: transaction.set_rollback(True) return Response(status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_200_OK) Ok, if everything is normal, I will have an image file saved to the hard disk on the server and a record stored in the database. When I called transaction.set_rollback(True) in View, Django did the rollback perfectly and no records were added to the database. But after I recheck, Django didn't delete the image file on my hard disk even though there is no record in the DB associated with that image file. I also searched and got a solution like post_delete: @receiver(models.signals.post_delete, sender=ImageUpload) def auto_delete_file_on_delete(sender, instance, **kwargs): if instance.image: if os.path.isfile(instance.image.path): os.remove(instance.image.path) This seems to work only when I call delete() method but with not with transactions. How can I delete unnecessary files during upload file when my View raising exception or transaction.set_rollback(True) function is called? -
How to prevent a page from refreshing when I want to submit a form?
I am trying to build my first website and I encountered a problem that I couldn't resolve by now. So, when an user wants to add an item to the cart, or to increment the quantity, I want to prevent the page from refreshing when hitting the submit button. I've looked for many answers, I tried to apply Ajax/JQuery, but unsuccessful. Here is my code: html <form action="{% url 'cart-add' %}" method="GET" id="myform"> {% csrf_token %} <label> <input type="hidden" name="{{ product.pk }}"> <input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1"> <button type="submit" value="">Add to chart</button> </label> </form> Ajax/JQuery script <script type="text/javascript"> $(document).ready(function () { $('myform').on('submit', function(e) { e.preventDefault(); $.ajax({ url : $(this).attr('action') || window.location.pathname, type: "GET", data: $(this).serialize(), success: function (data) { $("myForm").html(data); }, error: function (jXHR, textStatus, errorThrown) { alert(errorThrown); } }); }); }); </script> When I hit add-to-cart submit button, it throw me to the "cart.html". I do not want to do that, instead I want to prevent that and throw a message to the user saying that his/her item has been successfully added. Can somebody help me? Thank you very much for your time. I much appreciate it! -
how to customize django forms and success message without bootstrap?
I'm currently making a registration page. I'm using django's registration form and message alert. However, i do not use Bootstrap and would not like to use Bootstrap. How am i able to customize my registration form and message alerts with pure CSS? Here I provide the code to my message alerts: base.html <div class="alert"> {% if messages %} {% for message in messages %} {{message}} {% endfor %} {% endif %} </div> views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Thank you for registering, {username}.') return redirect('conference:index') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) I've tried adding the "alert" class into the CSS, however it does not work at all. Is there something I'm missing out in order to make the CSS styling work? -
Issue in adding sub-apps in settings.py file
I am unable to add my sub apps like category, user in settings.py. It was working fine but don't know what mistake I have done. Please help. I'm not able to progress from here. Please create a model and get that model to admin panel. Link to github -
how to remove absolute disk path in django urls
I use Django 3.1, and i get a trouble. who can tell me how to do. thanks. My problem is my site path in linux Hard disk appeared in the admin url, like this: http://127.0.0.1/data/pysites/mysite.com/mysite/admin/ '/data/pysites/mysite.com/mysite/' is my linux disk path, it appeared in the admin url, I hope it is only ‘http://127.0.0.1/admin/’, how can i remove it? in vews.py, i print request.path is: /data/pysites/xxx.com/mysite/play/ed160af7-5c98-4868-a679-2e86803e67d2/ i think the right path shuold be /play/ed160af7-5c98-4868-a679-2e86803e67d2/ -
Django: My object's list attribute not saving inside of 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() values = [1, 2, 3, 4, 5, 4, 3, 2, 1] def myFunction(): for value in values: my_object.class_list.append(value) return something_unrelated So in my_object, I want new values saved in its class_list attribute. I don't want the function to return the class_list. I want Django to save the attributes in its database. If I insert print statements before and after the for loop (see below), I get exactly what I would expect. def myFunction(): print(my_object.class_list) for value in values: my_object.class_list.append(value) print(my_object.class_list) return something_unrelated In the consul I will see [] [1, 2, 3, 4, 5, 4, 3, 2, 1] But if I print(my_object.class_list) afterward, it will print [] So how do I get Django to save my object info? What … -
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?