Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create form calendar view in django?
Value 1.01.2019 2.01.2019 .. .01.2019 14.01.2019 I Insert data Insert data Insert data Insert data II Insert data Insert data Insert data Insert data III Insert data Insert data Insert data Insert data IV Insert data Insert data Insert data Insert data Hi, How to create the above form in django template? -
Deleting a MongoDB document via id in an Angular-Django app
I have written the following code to delete specific customer documents via their id from a MongoDB collection: Angular service: deletepost(id: number): Observable<Post> { const url = `${this.baseApiUrl}` + `/handle_post/` + id; return this.httpClient.delete<Post>(url) .pipe( retry(3), catchError(this.handleError) ); } Django view: @csrf_exempt @api_view(['GET', 'DELETE', 'PUT']) def handle_post_by_id(request, id): try: post = PostModel.objects.get(pk=id) except PostModel.DoesNotExist: exceptionError = { 'message': "Post with id = %s" %id, 'posts': "[]", 'error': "" } return JsonResponse(exceptionError, status=status.HTTP_404_NOT_FOUND) if request.method == 'DELETE': post.delete() posts_serializer = PostModelSerializer(post) response = { 'message': "Successfully deleted a post with id = %s" %id, 'posts': [posts_serializer.data], 'error': "" } return JsonResponse(response) My URLs are as follows: urlpatterns = [ path('handle_post/<int:id>', handle_post_by_id) ] What am I doing wrong that a customer with id does not get deleted from the database? -
getting the error "The QuerySet value for an exact lookup must be limited to one result using slicing. "
I am trying to create a lms with django. So I have a separate model for the teachers who can upload the courses, and another model for courses. The code is below: models.py class teacher(models.Model): name=models.ForeignKey(User, on_delete= models.CASCADE) area=models.ManyToManyField(subject) description=RichTextField() class course(models.Model): title=models.CharField(max_length=500) areas=models.ManyToManyField(subject) description=RichTextField() instructor=models.ForeignKey(teacher, on_delete= models.CASCADE) material=models.CharField(max_length=1000) def __str__(self): return self.title In my views.py file: instr=teacher.objects.filter(name=request.user) data2=models.course.objects.filter(instructor__name__username=instr) return render(request, "course/profile.html", {'datas':a, 'courses': data, 'creations':data2}) in the templete: <div class="col-md-12"><label class="labels">Created Courses</label> {% for data in creations %} <form action="/course/" method="GET"> <div class="w3-display-container w3-col s12 m4 l4 w3-section"> <div class="card" style="width: 30rem; height: 30rem;"> <div class="card-body hover_trans_grey"> <h5 class="card-title">{{data.title}}</h5> <h6 class='card-title'>Uploaded by {{data.instructor.name}}</h6> <button type="submit" class="btn btn-primary w3-button" name="s" value="{{data.pk}}">Go to Course</button> </div> </div> </div> </form> {% endfor %} </div> I get the error: What is the way to remove this issue? -
search fields django admin with uppercase/lowercase
In my Django admin app i have this code in admin.py: search_fields = ["app_product_mapping", "id", "app__app_name", "product__product_name"] I noticed that the search field is sensitive to Uppercase and Lowercase and I want to make it sensitive to all over. How can I do that? TNX! -
Deploy a Django application on Azure VM using Github Actions
I have built a Django application and dockerized it with Nginx, I also created a GitHub workflow to build the docker image and push it to ghcr.io. Now I want to deploy the docker image (from ghcr.io) to the Azure virtual machine (ubuntu). but I couldn't find, how to connect azure VM to GitHub workflow and execute some commands from it. name: CI and CD on: [push] env: DOMAIN_NAME: ${{ secrets.DOMAIN_NAME }} jobs: build: name: Build Docker Images runs-on: ubuntu-latest steps: - name: Checkout master uses: actions/checkout@v1 - name: Add environment variables to .env run: | echo DJANGO_SECRET_KEY=${{ secrets.DJANGO_SECRET_KEY }} >> .env echo DJANGO_ALLOWED_HOSTS=${{ secrets.DJANGO_ALLOWED_HOSTS }} >> .env echo DATABASE=postgres >> .env echo DB_NAME=${{ secrets.DB_NAME }} >> .env echo DB_USER=${{ secrets.DB_USER }} >> .env echo DB_PASS='${{ secrets.DB_PASS }}' >> .env echo DB_HOST=${{ secrets.DB_HOST }} >> .env echo DB_PORT=${{ secrets.DB_PORT }} >> .env echo VIRTUAL_HOST=$DOMAIN_NAME >> .env echo VIRTUAL_PORT=8000 >> .env echo LETSENCRYPT_HOST=$DOMAIN_NAME >> .env echo EMAIL_HOST_USER=${{ secrets.EMAIL_HOST_USER }} >> .env echo EMAIL_HOST_PASSWORD=${{ secrets.EMAIL_HOST_PASSWORD }} >> .env echo DEFAULT_EMAIL=${{ secrets.DEFAULT_EMAIL }} >> .env echo NGINX_PROXY_CONTAINER=nginx-proxy >> .env - name: Set environment variables run: | echo WEB_IMAGE=ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/web >> $GITHUB_ENV echo NGINX_IMAGE=ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/nginx >> … -
Heroku Is giving me 'error h14 for my django project
When I go to my heroku project it says to run heroku logs --tail, and when I do that I get: 2022-01-16T04:52:26.342707+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=riseupontario.herokuapp.com request_id=584f14b8-99da-4cfc-bfad-1811755db6fb fwd="49.149.136.159" dyno= connect= service= status=503 bytes= protocol=https 2022-01-16T04:52:27.375325+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=riseupontario.herokuapp.com request_id=63993a67-e160-4762-a520-9164646b74f7 fwd="49.149.136.159" dyno= connect= service= status=503 bytes= protocol=https I've tried heroku ps:scale web=1 but I get: Scaling web processes... failed ! No such type as web This is my procfile: web: gunicorn riseupontario.wsgi --log-file - How do I get my site working? -
How to prepopulate the django ckeditor page in html
I am creating a blogging site with django, and want to create an editing post page using the same form as the one I used for post creation. This is the forms.py class PostForm(forms.Form): title = forms.CharField(max_length=100, label='Post Title') short_description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100})) content = forms.CharField(widget=CKEditorWidget()) And this is the html so far: <div class="form-group"> <label class="col-form-label mt-4" for="inputDefault">Title</label> {% render_field form.title class="form-control" value=post.title %} </div> <div class="form-group"> <label class="form-label mt-4" for="exampleTextarea" >Short Description</label > <!-- {% render_field form.short_description class="form-control" initial=post.short_description %} --> <textarea class="form-control" cols="100" name="description" rows="3">{{ post.short_description }}</textarea> </div> <div class="form-group"> <label class="col-form-label mt-4" for="inputDefault">Content</label> {{ form.content }} </div> I want to be able to prepopulate the ckeditor widget with prexisting data from the model: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts') short_description = models.TextField() Any advice on how to do so? updated_on = models.DateTimeField(auto_now=True) content = RichTextField() -
Compare data from two different models in Django
I created two models from statistics import mode from django.db import models # Create your models here. class Image(models.Model): photo = models.ImageField(upload_to="myimage") date = models.DateTimeField(auto_now_add=True) shape = models.CharField(max_length=20, default='') color = models.CharField(max_length=20, default='') class final(models.Model): fshape = models.CharField(max_length=20, default='') fcolor = models.CharField(max_length=20, default='') fnmae = models.CharField(max_length=20, default='') fdescr = models.TextField(max_length=50, default='') I want to compare shape from Image model with final model fshape if shape and fshape are equal then display fshape -
Django: set-cookie causes cookies to be stored in the backend instead of the frontend
example.com is frontend (Next.js) api.example.com is backend (Django) For some reason, the cookie is stored on the backend domain. This does not allow the front-end to access the stored cookies. I have implemented an authentication API using the following, but as far as I can tell, there is no setting to change the domain where cookies are stored. django-cors-headers dj-rest-auth djangorestframework-simplejwt CORS_ALLOWED_ORIGINS = ['https://example.com'] CORS_ALLOW_CREDENTIALS = True How can I store cookies on the front-end domain? -
CSS and Bootstrap only working on one html page and not the other
I launched my app on Heroku and everything seems to be working as usual except that the design (css) is only fully working on my home.html page but not my results.html page. On the results.html page it seems that only some css components are working while others are not. I've attached pictures of the design differences as well as the header code where I link my css and bootstrap. I would appreciate any help in knowing why my results.html page is not fully loading the css file. home.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <!-- Drag and drop script --> <script src="{% static 'PRIIIME_Travel/js/drag_drop.js' %}"></script> <!-- Get value of ranking boxes script --> <script src="{% static 'PRIIIME_Travel/js/get_value.js' %}"></script> <!-- Meta tags --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="noindex, nofollow"> <link rel="icon" type="image/png" href="{% static 'logo/PRIIIME_Logo.png' %}" /> <!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!--- Include CSS --> <link rel="stylesheet" href="{% static 'PRIIIME_Travel/css/home.css' %}" type="text/css" /> <title>Travel</title> </head> results.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <!-- Drag and drop script --> <script src="{% … -
AttributeError: Got AttributeError when attempting to get a value for field `password2` on serializer `RegisterSerializer`
Original exception text was: 'CustomUser' object has no attribute 'password2'. I am trying to create a serializer for creating users but this error comes up when I try to create the model. Am I not allowed to have serializer fields that the Model doesn't have? class RegisterSerializer(serializers.Serializer): email = serializers.EmailField() username = serializers.CharField(max_length=150) password = serializers.CharField(max_length=128) password2 = serializers.CharField(max_length=128) profile_img = serializers.ImageField() def create(self, validated_data): email = validated_data.get('email') username = validated_data.get('username') password = validated_data.get('password') profile_img = validated_data.get('profile_img') return CustomUser(email=email, username=username, password=password, profile_picture=profile_img) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.username = validated_data.get('username', instance.username) instance.password = validated_data.get('password', instance.password) instance.profile_img = validated_data.get('profile_img', instance.profile_img) return instance -
NameError When Running Python script through Bash
I am trying to run some python (Django) files via Bash (for some cronjobs); however I am coming across some odd errors. Setup is basically a .sh script I run with bash that loads some source files & then runs a python file via Django Shell. For demonstration purposes I have commented out some parts of the bash script, that I was using during testing. Bash Script #!/bin/bash source /home/grlaer/Desktop/mensam_games/bin/activate source /home/grlaer/Desktop/mensam_games/vars.env cd /home/grlaer/Desktop/mensam_games/cards_refactor #python3 manage.py shell < tcg_sku/test_bash.py ./manage.py shell < tcg_sku/test_bash.py #cat tcg_sku/test_bash.py | ./manage.py shell exit 0 Python Script from datetime import datetime print(datetime.now()) def do_this(): print("Its printing datetime") print(datetime.now()) return None do_this() Error/Traceback 2022-01-16 00:11:02.698550 Its printing datetime 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 "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/commands/shell.py", line 93, in handle exec(sys.stdin.read()) File "<string>", line 12, in <module> File "<string>", line 9, in do_this NameError: name 'datetime' is not defined I run bash test_bash.sh from the command line, and I get the … -
I Have a problem deploying my Django app on heroku [closed]
I am trying to deploy my django app on heroku, but it seems not to work because of the below error. ERROR: Could not find a version that satisfies the requirement kivy-deps.angle==0.3.0 (from versions:none) ERROR: No matching distribution found for kivy-deps.angle==0.3.0 ! Push rejected, failed to complete python app. ! Push failed The above is the error during my deployment process. I am using Python version 3.9.3 Django version 3.2.9 It will be of much help for me to hear a solution from you. -
Django change password using custom inputs with PasswordChangeView
Currently working on a change password method, not sure how to do the html inputs for it. I am using PasswordChangeView in my urls.py from django.urls import path from .views import update_profile from django.contrib.auth.views import PasswordChangeView urlpatterns = [ path('profiles/settings/', update_profile, name='update_profile'), path('profiles/change_password/', PasswordChangeView.as_view( template_name='profiles/settings.html'), name='password_change'), ] The template it is pointing too is the user update profile. I want to use own inputs on the template, but not sure how to hook it up with PasswordChangeView html <!-- Password Change --> <div class="tab-pane fade" role="tabpanel" id="password"> <form action="{% url 'password_change' %}" method="post"> {% csrf_token %} <div class="form-group row align-items-center"> <label class="col-3">Current Password</label> <div class="col"> <input type="password" placeholder="Enter your current password" name="password-current" class="form-control" /> </div> </div> <div class="form-group row align-items-center"> <label class="col-3">New Password</label> <div class="col"> <input type="password" placeholder="Enter a new password" name="password-new" class="form-control" /> <small>Password must be at least 8 characters long</small> </div> </div> <div class="form-group row align-items-center"> <label class="col-3">Confirm Password</label> <div class="col"> <input type="password" placeholder="Confirm your new password" name="password-new-confirm" class="form-control" /> </div> </div> <div class="d-flex justify-content-end"> <button type="submit" class="btn btn-primary">Change Password</button> </div> </form> </div> Question I want each of those 3 inputs used to change password, but i dont know what label id and name label to use to … -
geodjango filter polygon intersections for every point
I was trying to get locations(polygon) with shops(point). I don't want to add foreign key reference for location into shop model, rather want to get them by checking their intersections. class Shop(models.Model): name = models.CharField(max_length=40) location = PointField() @property def point(self): return self.location.wkt class Location(models.Model): name = models.CharField(max_length=200) area = PolygonField() I get my desired querysets using for loop however I was looking for a database related approach. for i in Location.objects.all(): print(Shop.objects.filter(location__intersects = i.area)) ## output: <QuerySet [<Shop: Shop object (1)>, <Shop: Shop object (2)>, <Shop: Shop object (4)>]> <QuerySet [<Shop: Shop object (3)>]> so I tried using subquery but iterating over full Location queryset returns error more than one row returned. so I set the limit to 1. loc=Location.objects.all() shp=Shop.objects.filter(location__intersects=Subquery(loc.values('area')[:1])) However, I need to filter Shop for all the Location. What might be the best way of doing that? -
expected string or bytes-like object while sending a Post request to a view
i have this view Where im making a post request from my frontend, iam sending a list of objects as a body to this endpoint. I have recieved the list in the files variable. now im trying to create an objects with the data i get from my files list, but im getting this error @api_view(("POST",)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def get_import(request): files = json.loads(request.body) print(files) # im able to see the list in the console. user = UserAccount.objects.filter(email=request.user).first() for i in range(len(files)): trans, created = Transaction.objects.update_or_create( chp_reference=files[i]["transaction_chp_reference"], defaults={ "user": user, "income_period": files[i]["transaction_income_period"], "property_market_rent": files[i]["transaction_property_market_rent"], }, ) trans.save() return Response(status=status.HTTP_201_CREATED) I tried to delete all migrations and db, and re created . but still same problem. Traceback (most recent call last): File "G:\cra-react\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\cra-react\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\cra-react\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\cra-react\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "G:\cra-react\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "G:\cra-react\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "G:\cra-react\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "G:\cra-react\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "G:\cra-react\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = … -
Deploying Django Apps on Heroku
I'm at my wit's end. I have followed two tutorials about deploying a Django app onto Heroku. I created two apps with the first tutorial (MDN), and one app with the second tutorial (Corey Schafer's YouTube video). All three times I've created these Django apps and they work. But when it comes time to try to deploy these apps to Heroku, something I download through pip into these apps doesn't work. This time around, with Corey Schafer's tutorial, when I download "django-heroku" through pip, the download works but when I add import django_heroku django_heroku.settings(locals()) into my "settings.py" file, I get an error message saying Import "django_heroku" could not be resolved Pylance(reportMissingImports) I've searched high and low across the Internet for the answer for this and found nothing. And I'm taking a real chance putting up this question here and hoping for an answer. Is Django incompatible with Heroku? I'd like to be able to deploy my Django apps to Heroku since Heroku is free, but perhaps Heroku no longer allows Django apps to be deployed? Please help! I'm tearing my hair out. -
Getting an attribute error in django.how do i resolve this?
Getting an attribute error at a model in django. When I tried to call the model.get_absolute_url at my model_list templates.it says model has no attributen "id" while in the model,i ve also written both the url mapper and the view function correctly,including the detals templates the exception was pointing the this reverse line This is the function under the model in models.py file ''' def get_absolute_url(self): return reverse('my_midel_detail_template_name',args=[str(self.id)]) ''' -
Django dynamic url routing not working properly
I'm trying some dynamic url routing for my website. I got to the point but is not working properly when I want to redirect to other pages. Let me explain: I have the same navbar for each page. I have a "news" page with url /news from which I can dynamically route to each article with url /article/pk, where pk is the index of the article in postgresql database. The article page has the same navbar of each other page but when I click to redirect to another page (for example /news) it doesn't work since it looks for /article/news which obviously does not exists instead of /news. I don't know how to solve this and I would be glad if you could help me. Please don't roast me, it's my first project. Feel free to ask for code if needed. -
Django_tables2 : using bootstrap in django-tables2
If I want to use Bootstrap in django-tables2 what should I do? Where I should write DJANGO_TABLES2_TEMPLATE = 'django_tables2/bootstrap4.html' If I want to use bootstrap5 what should I do? -
The `.update()` method does not support writable dotted-source fields by default
i'm trying to update some data and got this error what is wrong here? Exception Value: The `.update()` method does not support writable dotted-source fields by default. Write an explicit `.update()` method for serializer `users.serializers.TransporteurSerializer`, or set `read_only=True` on dotted-source serializer fields. i'm trying to build a multi types user so the user (CustomUser) is the parent class class TransporteurSerializer(serializers.ModelSerializer): # user = CustomUserSerializer() first_name = serializers.CharField(source = 'user.first_name') last_name = serializers.CharField(source = 'user.last_name') email = serializers.CharField(source = 'user.email') phone_number = serializers.CharField(source = 'user.phone_number') address = serializers.CharField(source = 'user.address') class Meta: model = Trasporteur fields = [ 'id', 'first_name', 'last_name', 'email', 'phone_number', 'address', 'matricule','car_type','current_location','is_on_travail','bio', ] def update(self, instance, validated_data): user_data = validated_data.pop('user') user = instance.user instance.matricule = validated_data.get('matricule', instance.matricule) instance.car_type = validated_data.get('email', instance.car_type) instance.current_location = validated_data.get('email', instance.current_location) instance.is_on_travail = validated_data.get('email', instance.is_on_travail) instance.bio = validated_data.get('email', instance.bio) user.first_name = user_data.get('first_name',user.first_name) user.last_name = user_data.get('first_name',user.last_name) user.email = user_data.get('email',user.email) user.phone_number = user_data.get('first_name',user.phone_number) user.address = user_data.get('address',user.address) user.save() instance.save() return instance -
How to call posts comments from an api
Currently I have the following Models: class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200, blank=False, null=False) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False) text = models.TextField(max_length=1000) and these ModelViewSets: class PostViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer class CommentViewSet(ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer my question is how can I call comments from a post like this: GET /posts/{id}/comments currently I get the comments this way: GET /comments/{id} #comment Id, not post id. -
apply css class to ckeditor uploaded images
I have a feature that allows users to write blog posts using with ckeditor. The issue is if a image is uploaded it is way to large. I need to be able to apply a css class so I can properly size these images. I found this stack post saying to put this code in my config.js file and run collectstatic it should apply a class. However it does not do anything. Any suggestions? this is my config.js file /** * @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved. * For licensing, see https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; }; CKEDITOR.on('instanceReady', function (ev) { ev.editor.dataProcessor.htmlFilter.addRules( { elements: { $: function (element) { // check for the tag name if (element.name == 'img') { element.attributes.class = "img-fluid" // Put your class name here } // return element with class attribute return element; } } }); }); -
OSError: /opt/homebrew/opt/gdal/lib/libgdal.dylib: cannot open shared object file: No such file or directory
I am trying to deploy a webapp that utilises GDAL libraries. I have followed the heroku documentation pertaining to GDAL and Heroku here and here. My buildpacks are: === vygrapp Buildpack URLs 1. https://github.com/heroku/heroku-geo-buildpack.git 2. heroku-community/apt 3. heroku/python When I deploy my app through heroku I get this traceback: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/tmp/build_4575d756/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_4575d756/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate remote: app_config.import_models() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 300, in import_models remote: self.models_module = import_module(models_module_name) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 850, in exec_module remote: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> remote: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager … -
Django form not able to upload image
Trying to upload user avatar on profile page, but it wont do anything when pressing the button, I have set that there is not required to upload profile pic, so rest of form works. forms.py class UpdateProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'location', 'bio', 'avatar'] def __init__(self, *args, **kwargs): super(UpdateProfileForm, self).__init__(*args, **kwargs) self.fields['avatar'].required = False views.py @login_required def update_profile(request): context = {} user = request.user instance = Profile.objects.filter(user=user).first() if request.method == 'POST': form = UpdateProfileForm(request.POST, request.FILES, instance=instance) if form.is_valid(): print('\n\n form is valid') form.instance.user = user form.save() return redirect('/') else: form = UpdateProfileForm(instance=user) print(errors) context.update({ 'form': form, 'title': 'update_profile' }) return render(request, 'profiles/settings.html', context) From html <form method="POST" action="." enctype="multipart/form-data"> {% csrf_token %} <div class="media mb-4"> <img alt="Image" src="{{ user.profile.avatar.url }}" class="avatar avatar-lg" /> <div class="media-body ml-3"> <div class="custom-file custom-file-naked d-block mb-1"> <input type="file" class="custom-file-input d-none" id="{{ form.avatar.id_for_label }}"> <-- This is my label for the button <label class="custom-file-label position-relative" for="{{ form.avatar.id_for_label }}"> <-- Input field.. nothing happens when press <span class="btn btn-primary"> Upload avatar </span> </label> </div> <small>Use an image at least 256px by 256px in either .jpg or .png format</small> </div> </div> <!--end of avatar--> <div class="form-group row align-items-center"> <label class="col-3">First Name</label> <div class="col"> …