Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django change password
Trying to change password using PasswordChangeView, but cannot get it working. urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('profiles/settings/', update_profile, name='update_profile'), path('profiles/settings/', auth_views.PasswordChangeView.as_view(template_name='accounts/settings.html'), name='password_change'), ] And i am trying to get the input fields correct in my html <div class="tab-pane fade" role="tabpanel" id="password"> <form id="id_password_change_form" method="POST" class="form-signin">{% 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="old_password" class="form-control" id="id_old_password" required="true" /> </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="new_password1" class="form-control" id="id_new_password1" required="true" /> <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="new_password2" class="form-control" id="id_new_password2" required="true" /> </div> </div> {% for field in form %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} {% endfor %} <div class="d-flex justify-content-end"> <button type="submit" class="btn btn-primary">Change Password</button> </div> </form> There is no error, and it do not update the password as supposed to. according to PasswordChangeView, I should not need to alter anything. -
error while hosting django project on heroku
I am new in web development. I create E-Commerse website and now want to host this website on Heroku but there is some problem I don't know what is it. My project is working perfectly. Successfully installed Django-3.1.5 Flask-1.1.2 Jinja2-2.11.3 MarkupSafe-1.1.1 Pillow-8.1.0 Werkzeug-1.0.1 asgiref-3.3.1 click-7.1.2 django-autoslug-1.9.8 django-crispy-forms-1.10.0 gunicorn-20.1.0 itsdangerous-1.1.0 pycryptodome-3.9.9 pygame-2.1.0 pytz-2020.5 sqlparse-0.4.1 whitenoise-5.3.0 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_fd56140f/manage.py", line 22, in <module> main() File "/tmp/build_fd56140f/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 109, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_fd56140f/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable … -
Django ManyToMany | TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use course_tags.set() instead
My model: class Course(models.Model): ... course_tags = models.ManyToManyField(CourseTag, related_name='course_tags', blank=True) ... My Serializer: class CourseSerializer(serializers.ModelSerializer): ... course_tags = CourseTagsSerializer(many=True, required=False) ... class Meta: model = Course fields = [...'course_tags'...] def create(self, validated_data): ... tags_data = validated_data.pop('tags', None) ... course, _ = Course.objects.create( author=author, **validated_data) if tags_data: for tag in tags_data: new_tag, _ = CourseTag.get_or_create(title=tag.get('title')) course.course_tags.add(new_tag.id) course.save() I'm sending POST request to this serializer. Response: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use course_tags.set() instead. I tried working method but, my code is not working. -
How to mitigate the slow function in Django view
My Django website is in shared server ( nginx with uwsgi & Sqlite). The database is huge, when users search for certain model instances, it slows down the server as it wait for the query to finish. VIEW.PY def Newssearch(request): if request.method == "POST": searchdata = request.POST.get('searchdata') result = News.objects.filter(titleEnglish__icontains=searchdata)[0:8] return render(request, 'newsfront/searchresult.html',{'news':result}) The server (Pythonanywhere.com) seems to not support async functions. Any idea how to reduce the priority of the above function , so that if multiple types frequent requests come, it gives less priority to the search function. -
REST API endpoiint call of a signle id gives mutliple results with similar begining alphabtes
I am learning REST API Django and would appreciate your help in understaing the below case. in myproject/abcapp/forms.py from django import forms from .models import * class ProfileForm(forms.ModelForm): class Meta: model=Profile fields = "__all__" class Zoo_data_2020Form(forms.ModelForm): class Meta: model=Zoo_data_2020 fields = "__all__" in myproject/abcapp/models.py from django.conf import settings from django.db import models class ProfileQuerySet(models.QuerySet): pass class ProfileManager(models.Manager): def get_queryset(self): return ProfileQuerySet(self.model,using=self._db) class Profile(models.Model): name=models.CharField(settings.AUTH_USER_MODEL,max_length=200) subtype=models.CharField(max_length=500) type=models.CharField(max_length=500) gender=models.CharField(max_length=500) objects = ProfileManager() class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' managed = False db_table ='profiles' def __str__(self): return '{}'.format(self.name) class Zoo_data_2020QuerySet(models.QuerySet): pass class Zoo_data_2020Manager(models.Manager): def get_queryset(self): return Zoo_data_2020QuerySet(self.model,using=self._db) class Zoo_data_2020(models.Model): name=models.CharField(max_length=200) size=models.DecimalField(decimal_places=3,max_digits=100000000) weight=models.DecimalField(decimal_places=3,max_digits=100000000) age=models.DecimalField(decimal_places=3,max_digits=100000000) objects = Zoo_data_2020Manager() class Meta: verbose_name = 'zoo_data_2020' verbose_name_plural = 'zoo_data_2020s' managed = False db_table ='zoo_data_2020' def __str__(self): return '{}'.format(self.name) in myproject/abcapp/api/views.py: from rest_framework import generics, mixins, permissions from rest_framework.views import APIView from rest_framework.response import Response import json from django.shortcuts import get_object_or_404 from abcapp.models import * from .serializers import * def is_json(json_data): try: real_json = json.loads(json_data) is_valid = True except ValueError: is_valid = False return is_valid class ProfileDetailAPIView(generics.RetrieveAPIView): permission_classes = [] authentication_classes = [] queryset= Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'id' class ProfileAPIView(generics.ListAPIView): permission_classes = [] authentication_classes= [] serializer_class = ProfileSerializer passed_id = None search_fields = ('id','name','animal') … -
preserve data while making changes to fields of model in django
I have two models which are Contact and UpdateInfo. Update model is a foreignkey relationship with Contact like below: class Contacts(models.Model): full_name = models.CharField(max_length=100, blank=True) notes = RichTextField(blank=True) /............./ class UpdateInfo(models.Model): contacts = models.ForeignKey(Contacts,on_delete=models.CASCADE, related_name='update_info') updated_at = models.DateTimeField(auto_now=True) modified_by = models.CharField(max_length=100, blank=True) Now what I need is to put the notes field into UpdateInfo model and remove from Contacts model. Because now the businees requirement has changed and what they need is they need to add notes in the existing notes and want to see them who added the notes and when they added it with the notes appended. But the problem is if I remove the notes field from Contacts and add it to Updateinfo model , there are many data into the production and the notes field data will be lost. Now how can we run migrate in such a way that I add notes field into the Updatinfo model and also migrating the data at the same time.?? Is this what is done by dev ops or we should do it?? Because usually dev ops are migrating the data to the production server from staging area. I need expert opinion on this. -
render() got an unexpected keyword argument 'board_id'
I have this function to get items from DB according to the PK: def new_topic(request, board_id): board = get_object_or_404(Board, pk = board_id) user = User.objects.first() if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): topic = form.save(commit=False) topic.board = board topic.created_by = user topic.save() post = Posts.objects.create( message = form.cleaned_data.get('message'), created_by = user, topic = topic ) return render('board_topics', board_id = board.pk) else: form = NewTopicForm() return render(request,'new_topic.html', {'board':board, 'form':form}) But it gives this error: render() got an unexpected keyword argument 'board_id' -
How to save image file to django obj
I am trying to set an image file from local path to the model GameFilm but the issue is print(File(open(path, 'rb'))) returns None so when i do obj.thumbnail = File(open(path, 'rb')) it will just set obj.thumbnail to None. My Model class GameFilm(models.Model): thumbnail = models.ImageField(null=True, blank=True, upload_to='images/') created_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey('users.User', on_delete=models.PROTECT, null=True, blank=True, related_name='game_films') title = models.CharField(max_length=150) description = models.TextField() film = models.FileField(upload_to='films/') My My problem function Here I am extracting an image at the millisecond 200 from the video in the path video_path. Then, I try to open the file and set it to obj.thumbnail. Then django supposed to upload it to aws s3. Finally, I will delete the local image that is just created. vidcap = cv2.VideoCapture(video_path) millisecond = 200 vidcap.set(cv2.CAP_PROP_POS_MSEC, millisecond) success, image = vidcap.read() if success: cv2.imwrite("framed.jpg", image) # save frame as JPEG file path = f'{settings.BASE_DIR}/framed.jpg' obj = GameFilm.objects.get(id=1) obj.thumbnail = File(open(path, 'rb')) obj.save() os.remove(f'{settings.BASE_DIR}/framed.jpg') -
DRF Viewset problem with using MultiPartParser/FormParser
django version = 2.2.16 drf version = 3.11.0 I would like to know what is the root cause of this problem. I have implemented similar code on previous project with similar settings without this problem. It works fine with JSONParser and FileUploadParser only. My modelviewset class OutletViewset(viewsets.ModelViewSet, mixins.ListModelMixin): permission_classes = [IsAuthenticated] parser_classes = [JSONParser, MultiPartParser] queryset = Outlet.objects.all() serializer_class = serializers.OutletSerializer def get_queryset(self): if "user_id" in self.request.query_params: user_id = self.request.query_params.get("user_id", None) queryset = Outlet.objects.filter(user=user_id) else: queryset = Outlet.objects.all() return queryset My serializer class OutletSerializer(serializers.ModelSerializer): class Meta: model = models.Outlet fields = "__all__" def update(self, instance, validated_data): [setattr(instance, k, v) for k, v in validated_data.items()] instance.save() return instance The error I met: Environment: Request Method: GET Request URL: http://localhost:8000/commons_kl/api/v1/outlets/ Django Version: 2.2.16 Python Version: 3.7.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'drfpasswordless', 'rest_framework_api_key', 'rest_auth', 'django_extensions', 'commons_kl'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', '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'] Template error: In template D:\Work\commonsKL\lib\site-packages\rest_framework\templates\rest_framework\horizontal\select.html, error at line 15 __str__ returned non-string (type NoneType) 5 : <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}"> 6 : {{ field.label }} 7 : </label> 8 : {% endif %} 9 : 10 : <div class="col-sm-10"> 11 : <select class="form-control" name="{{ field.name … -
how to redirect return to same page after POST in this case. django
I am creating this project in django. I am working on recording Add the number of products by BARCOD , where I go to a product -detail view, then hit the product link. Add the number of product in form Everything works fine, but there is one thing. After add number of products by BARCOD I get sent back to a random(?) ....but I would like to stay on the same page Add the number of product in form . But how??? views def returnitm_PK(request,item_PK_id): clientR=ClientPK.objects.get(place=request.POST.get("clientR")) item_PK=StockPK.objects.get(pk=item_PK_id) quan_BARCOD=request.POST.get("quan_BARCOD") Ear_number=request.POST.get("Ear_number") transaction=TransactionPK(item_PK=item_PK,clientR=clientR,quan_BARCOD=quan_BARCOD,Ear_number=Ear_number) transaction.save() if quan_BARCOD== '0009478908' : item_PK.R1=item_PK.R1+int(1) if quan_BARCOD== '0005663140' : item_PK.R2=item_PK.R2+int(1) item_PK.save() context = {'transaction':transaction,'item_PK':item_PK,'clientR':clientR, 'quan_BARCOD':quan_BARCOD,'Ear_number':Ear_number, } return render(request, "details_PK", context) urls path('F_add_items/',views.F_add_items,name='F_add_items.html'), path('F_list_history/', views.F_list_history, name='F_list_history.html'), path('F_list_item/', views.F_list_item, name='F_list_item'), path('<int:item_PK_id>/details',views.details_PK,name='details_PK'), path('<int:item_id>/',views.details,name='details'), path('<int:item_id>/transfer',views.transferitm,name='transferitm'), path('<int:item_id>/returnitm',views.returnitm,name='returnitm'), ############################################################################### path('F_add_PK/',views.F_add_PK,name='F_add_PK.html'), path('F_list_history_PK/', views.F_list_history_PK, name='F_list_history_PK.html'), path('F_list_item_PK/', views.F_list_item_PK, name='F_list_item_PK'), path('<int:item_PK_id>/returnitm_PK',views.returnitm_PK,name='returnitm_PK'), details_PK {% extends 'base.html' %} {% block content %} <center> <div class="card" style="width: 50rem;"> <div class="card-body"> <form action="returnitm_PK" method="POST" > <div class="card-header">add {{ item.name }}</div> {% csrf_token %} <input type="hidden" name="item" value="{{ item.name }}"> <div class="form-group"> <label for="clientR">clientR</label> <select name="clientR" class="form-control" id="client"> {% for clientR in ClientPKs %} <option value="{{ clientR.place }}">{{ clientR.place }}</option> {% endfor %} </select> </div> <!-- <div class="form-group"> <label for="Ear_number">رقم الاذن</label> <input type="text" class="form-control" … -
over riding django allauth template
when I override the default template as shown below it is showing only password field, but if i change the template location it shows both field why it behave so, any idea class CustomLoginView(MetadataMixin, LoginView): template_name = 'account/login.html' and url is path('login/', CustomLoginView.as_view(), name='custom_login'), this code only shows password field but if change the template location it shows both fields and works, also if I change the url path('account/login/', CustomLoginView.as_view(), name='custom_login'), it don't show both the fields -
how can i use python-magic in python,docker
i'm using docker, python 3.8.5-alpine and i want to check upload file's mime type i make validators.py and download python-magic-bin module it is working in test side(window, pycharm) so I'm trying to upload to ubuntu 18.04 docker build is success. but I get an Import Error: No module called magic. message python-magic python-magic-bin libmagic libmagic1 etc.. it isn't working... Is there any solution in this situation? I wonder what to add in my code my Dockerfile FROM python:3.8.5-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update RUN apk add g++ postgresql-dev cargo gcc python3-dev libffi-dev openssl-dev musl-dev zlib-dev jpeg-dev #--(5.2) COPY . /usr/src/app/ RUN pip install --upgrade pip RUN pip install -r requirements.txt requrements.txt asgiref==3.3.2 backcall==0.2.0 beautifulsoup4==4.9.1 certifi==2020.6.20 chardet==3.0.4 colorama==0.4.3 Cython==0.29.22 decorator==4.4.2 defusedxml==0.6.0 Django==3.2.6 django-allauth==0.42.0 django-crispy-forms==1.9.2 django-extensions==3.0.9 django-markdownx==3.0.1 django-summernote==0.8.11.6 django-axes==5.17.0 et-xmlfile==1.0.1 gunicorn==20.0.4 idna==2.10 importlib-metadata==2.0.0 ipython==7.18.1 ipython-genutils==0.2.0 jdcal==1.4.1 jedi==0.17.2 Markdown==3.2.2 numpy==1.20.2 numexpr==2.8.1 oauthlib==3.1.0 openpyxl==3.0.6 pandas==1.3.0 parso==0.7.1 pickleshare==0.7.5 Pillow==7.2.0 prompt-toolkit==3.0.7 psycopg2==2.8.6 pycparser==2.20 Pygments==2.7.1 python-dateutil==2.8.1 python-magic==0.4.24 python3-openid==3.2.0 pytz==2020.1 requests==2.24.0 requests-oauthlib==1.3.0 semantic-version==2.8.5 setuptools setuptools-rust==0.11.6 six==1.15.0 soupsieve==2.0.1 sqlparse==0.3.1 toml==0.10.2 traitlets==5.0.4 urllib3==1.25.10 wcwidth==0.2.5 zipp==3.2.0 validators.py import os #import magic from django.core.exceptions import ValidationError def validate_extension(file): #valid_mime_types = ["application/avi", "application/mp4", "application/xlsx", "application/xls", "application/ppt", "application/pptx", "application/hwp", "application/doc", … -
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.