Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form says image field is required meanwhile image is uploaded in Graphql Altair client
I'm using GraphQL in a Django project and the Altair GraphQL client, and I'm facing an issue with file uploads. When the request is submitted via Altair, the submitted fields are detected in my ImageUploadMutation. After initialising the form with the fields (form = ArtistPhotoForm({'photo': file})), form.data also prints the right fields. However, after calling the form.is_valid() method, I get photo: This field is required! Here are the important code segments: models.py class ArtistPhoto(models.Model): # Use width_field and height_field to optimize getting photo's width and height # This ThumnailerImageField is from easy_thumbnails; but i don't think the issue is here photo = ThumbnailerImageField( thumbnail_storage=FILE_STORAGE_CLASS(), upload_to=ARTISTS_PHOTOS_UPLOAD_DIR, resize_source=dict(size=(1800, 1800), sharpen=True), validators=[FileExtensionValidator(['png, jpg, gif'])], width_field='photo_width', height_field='photo_height' ) photo_width = models.PositiveIntegerField() photo_height = models.PositiveIntegerField() forms.py class ArtistPhotoForm(forms.ModelForm): class Meta: model = ArtistPhoto fields = ['photo'] mutation # Output class contains the fields success and errors class ImageUploadMutation(graphene.Mutation, Output): class Arguments: file = Upload(required=True) form_for = ImageFormEnum(required=True) # Apparently this should be an instance method not a class method @verification_and_login_required def mutate(self, info, file: InMemoryUploadedFile, form_for, **kwargs): if form_for == 'artist_photo': form = ArtistPhotoForm({'photo': file}) if form.is_valid(): print("Form is valid") print(form.cleaned_data) return ImageUploadMutation(success=True) print(form.errors) return ImageUploadMutation(success=False, errors=form.errors.get_json_data()) I get the error message { "data": { … -
Python django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration?
Python Django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration? def Unreg(request): if request.method=='POST': studnumber=request.POST['studnumber'] fname=request.POST['fname'] age=request.POST['age'] gender=request.POST['gender'] uname=request.POST['uname'] email=request.POST['email'] pwd=request.POST['pwd'] contact=request.POST['contact'] newacc(studnumber=studnumber,fname=fname,age=age,gender=gender,uname=uname,email=email,pwd=pwd,contact=contact).save() messages.success(request,"The New User is save !") return render(request,'Registration.html') else: return render(request,'Registration.html') -
My local django project works, and it also works on Heroku until i submit form and then i get error when it works fine locally
I have a website with an email form and when i submit locally it works. When i submit form on heroku i got a 500 server error or an application error. What can i do?? 2022-02-02T01:30:06.285140+00:00 app[web.1]: response = response or self.get_response(reque st) 2022-02-02T01:30:06.285140+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/handlers/exception.py", line 49, in inner 2022-02-02T01:30:06.285140+00:00 app[web.1]: response = response_for_exception(request, exc ) 2022-02-02T01:30:06.285140+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/handlers/exception.py", line 103, in response_for_exception 2022-02-02T01:30:06.285141+00:00 app[web.1]: response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 2022-02-02T01:30:06.285141+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/handlers/exception.py", line 47, in inner 2022-02-02T01:30:06.285141+00:00 app[web.1]: response = get_response(request) 2022-02-02T01:30:06.285141+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/handlers/base.py", line 179, in _get_response 2022-02-02T01:30:06.285142+00:00 app[web.1]: response = wrapped_callback(request, *callback _args, **callback_kwargs) 2022-02-02T01:30:06.285142+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/views/generic/base.py", line 70, in view 2022-02-02T01:30:06.285143+00:00 app[web.1]: return self.dispatch(request, *args, **kwargs) 2022-02-02T01:30:06.285143+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/views/generic/base.py", line 98, in dispatch 2022-02-02T01:30:06.285143+00:00 app[web.1]: return handler(request, *args, **kwargs) 2022-02-02T01:30:06.285143+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/views/generic/edit.py", line 142, in post 2022-02-02T01:30:06.285144+00:00 app[web.1]: return self.form_valid(form) 2022-02-02T01:30:06.285144+00:00 app[web.1]: File "/app/mainpage/views.py", line 30, in for m_valid 2022-02-02T01:30:06.285144+00:00 app[web.1]: send_mail( 2022-02-02T01:30:06.285144+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/mail/__init__.py", line 61, in send_mail 2022-02-02T01:30:06.285145+00:00 app[web.1]: return mail.send() 2022-02-02T01:30:06.285145+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/mail/message.py", line 284, in send 2022-02-02T01:30:06.285146+00:00 app[web.1]: return self.get_connection(fail_silently).send _messages([self]) 2022-02-02T01:30:06.285149+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-p ackages/django/core/mail/backends/smtp.py", line 109, in send_messages 2022-02-02T01:30:06.285149+00:00 app[web.1]: sent … -
Como rescato informacion de un select en html con Django
Buenas a todos estoy trabajando con formularios con Django y necesito rescatar la informacion de un select y mandarla hacia la view pero no encuentro manera de hacerlo, si alguien podria ayudarme porfavor, gracias de antemanoenter image description here -
Production not the same as local
When running locally my files are correct but on production it seems that none of the changes are through. I might be forgetting to do something to make the production files the same as local. TemplateDoesNotExist at / inbox.html Request Method: GET Request URL: https://url.com/ Django Version: 3.2.9 Exception Type: TemplateDoesNotExist Exception Value: inbox.html Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py, line 84, in reraise Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Tue, 01 Feb 2022 16:02:49 -0800 settings.py """ Django settings for portfolio project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! import os #Gets rid of from decouple import config SECRET_KEY = config("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #DEBUG = config('DJANGO_DEBUG',default=True, cast=bool) ALLOWED_HOSTS = ["url.com",'127.0.0.1','localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
Best way to create a queue for handling request to REST Api created via Django
I have the following scenario: Back end => a geospatial database and the Open Data Cube tool API => Users can define parameters (xmin,xmax,ymin,ymax) to make GET requests Process => On each requests analytics are calculated and satellite images pixels' values are given back to the user My question is the following: As the process is quite heavy (it can reserve many GB of RAM) how it is possible to handle multiple requests at the same time? Is there any queue that I can save the requests and serve each one sequently? Language/frameworks => Python 3.8 and Django Thanks in advance -
Render ModelForm in different app's template
Is there a way I could render the following modelform in a different template outside of it's app, it works correctly on a template inside the app but does not work outside of it. Models.py class Bid(models.Model): tasker = models.ForeignKey(Tasker, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=0) task_owner = models.ManyToManyField(User, blank=True) completed = models.BooleanField(default=False) Forms.py class CreateBidForm(forms.ModelForm): class Meta: model = Bid fields = ( 'tasker', 'price', 'task_owner', 'completed' ) Views.py class SubmitBid(CreateView): template_name = "listing_detail.html" form_class = CreateBidForm def post(self, request): form = CreateBidForm(request.POST or None, request.FILESquest) if form.is_valid(): bid = form.save(commit=False) bid.tasker = request.user bid.save() return redirect('/') -
Trying to add new model and field to existing data in Django
I'm learning Django and making a kind of social network and am trying to add a model and field to my models. The following post perfectly explains what I'm trying to do... Django - Private messaging conversation view I'm trying to add the model and field after I already have some messages saved. I'm making this for learning purposes for now, so deleting the existing messages and starting over would probably solve the problem, but I'm trying to learn how to navigate this because next time I could have actual users and deleting the messages might not be possible. Here are my models: from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=60) country = models.CharField(max_length=60) skillstolearn = models.CharField(max_length=200) skillstoteach = models.CharField(max_length=200) description = models.TextField() def __str__(self): return self.user.username class Conversation(models.Model): participants = models.ManyToManyField(User) def __str__(self): return self.participants class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') content = models.TextField() conversation = models.ForeignKey(Conversation, default=None, on_delete=models.CASCADE) timestamp = models.DateTimeField() def __str__(self): return self.sender.username + ' to ' + self.receiver.username Before trying to make the current migrations, the file did not have the Conversation model nor the … -
Is there any other way passing lookup parameters in django
I'm trying to pass a lookup parameter to my views.py to render to the templates model.py class Category(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=200, blank=True, unique=True) class Post(models.Model): """" created_on = models.DateTimeField(auto_now_add=True) cover = models.ImageField(null=True, blank=True ) categories = models.ManyToManyField(Category, related_name='posts', blank=True) views.py def index_category(request, category): posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') context = { "category": category, "posts": posts, } return render(request, "blog/index_category.html", context) index_category.html {% extends "base.html" %} {% block content %} <div class="col-md-8 offset-md-2"> <h1>{% block title %}{{ category | title }}{% endblock title %}</h1> <hr> {% for post in posts %} <h2><a href="{% url 'index-detail' post.slug %}">{{ post.title }}</a></h2> <small> {{ post.created_on.date }} |&nbsp; Categories:&nbsp; {% for category in post.categories.all %} <a href="{% url 'blog-category' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> <p>{{ post.body | slice:":200" }}...</p> {% endfor %} </div> {% endblock %} When i refresh my localhost on my category page, it's returning nothing except the block title. Is there any other way to filter the many-to-many relationship between the post and the category??? -
I want to nest a model into the Serialiazer. Category' object has no attribute 'brand_set'
I want to nest a model into the serializer. Like on list of Category, there should be fields from Brand model, But I m getting error by on setting this way ? models.py class Category(models.Model): title = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True) #.... class Brand(models.Model): title = models.CharField(max_length=50) category = models.ForeignKey( Category, blank=True, null=True, on_delete=models.SET_NULL, related_name="category") #.... Serializers class CategorySerializerNested(serializers.ModelSerializer): brands = serializers.SerializerMethodField(read_only=True) class Meta: model = Category fields = '__all__' def get_brands(self, obj): brands = obj.brand_set.all() #this thin popping error how to fix that.... serializer = BrandSerializerNested(brands, many=True) return serializer.data class BrandSerializerNested(serializers.ModelSerializer): products = serializers.SerializerMethodField(read_only=True) def get_products(self, obj): products = obj.product_set.all() serializer = ProductSerializer(products, many=True) return serializer.data class Meta: model = Brand fields = '__all__' View.py @api_view(['GET']) def getCategoryWithBrands(request, pk): category = Category.objects.get(id=pk) serializer = CategorySerializerNested(category, many=False) return Response(serializer.data) url.py path('nested/<str:pk>/', views.getCategoryWithBrands, name="category-with-brands"), Error: AttributeError: 'Category' object has no attribute 'brand_set' [02/Feb/2022 03:24:49] "GET /api/v1/categories/nested/1/ HTTP/1.1" 500 125121 I'm sure im doing something illogical but i dont know now, please help me to fix this , if there's any better way to do that please also help there as well. Thanks -
Duplicates with ManyToMany
I have model: class GPD(models.Model): employee = models.ForeignKey(Employee, verbose_name='Employee', on_delete = models.CASCADE, related_name='+') gpd_year = models.PositiveIntegerField(default=2021, validators=[ MaxValueValidator(2121), MinValueValidator(2021) ]) corp_goal = models.ManyToManyField(CorporateGoal, blank=True) team_goal = models.ManyToManyField(TeamGoal, blank=True) ind_goal = models.ManyToManyField(IndividualGoal, blank=True) def __str__(self): print('**********************') print(self.corp_goal.all()) print('**********************') return 'GPD ' + str(self.gpd_year) + ' for ' + self.employee.name + ' ' + self.employee.lastname As you can see, I have many to many relationship and when I am trying to print(self.corp_goal.all()) I have duplicates: When I am using print(self.corp_goal.all().distinct()) - I have the same problem. How fix it? -
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name. Even though I deleted that part
I'm implementing a search functionality in my Meme List View: class MemeListView(ListView): model = Meme paginate_by = 100 ordering = ['-created_at'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() search_value = self.request.GET.get("search", False) if search_value: memes = Q(title__icontains=search_value) objects = Meme.objects.filter(memes).select_related().distinct().order_by('-created_at')[:10] context['meme_list'] = objects context['search'] = search_value return context The only part of template that contains logout(I deleted it and restarted the server. The error is still there) {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href='{% url 'site:logout' %}'>Logout</a> </li> {% endif %} Now the issue is only if I search for a thing that has 0 results. If I search and find something everything works fine. Any Idea what is going on? -
How I display wagtail blog post in other pages like homepage
Noob here. So as the title I'm trying to display blog around my pages. What I'm trying to achive is: homepage who has a list of the latest post. Blog index Page. Blog category pages. a sidebar to use in my other pages. So that's has been my step so far: set up a wagtail project; install wagtail-blog; moved blog folder to Lib in my root folder set up root, template, and staticfolder. As I know by now my blog will show up only in my blog_index_page.html as a http:127.0.0.1/blog/ and blogpost showing up in 127.0.0.1/blog/blog-post-name. So blog looks like working fine. I'm really struggling to unbderstand how to implement the latest post in my homepage; making a category blog page and the sidebar who display latestpost around my site. so that's my code: blog/models.py from django.core.exceptions import ValidationError from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.conf import settings from django.contrib.auth import get_user_model from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from django.shortcuts import get_object_or_404 from django.template.defaultfilters import slugify from wagtail.snippets.models import register_snippet from taggit.models import Tag from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from .abstract import ( BlogCategoryAbstract, BlogCategoryBlogPageAbstract, BlogIndexPageAbstract, BlogPageAbstract, BlogPageTagAbstract … -
Request to Django views that start Celery tasks time out
I'm deploying a Django app with Docker. version: '3.1' services: b2_nginx: build: ./nginx container_name: b2_nginx ports: - 1904:80 volumes: - ./app/cv_baza/static:/static:ro restart: always b2_app: build: ./app container_name: b2_app volumes: - ./app/cv_baza:/app restart: always b2_db: container_name: b2_db image: mysql command: --default-authentication-plugin=mysql_native_password restart: always environment: MYSQL_ROOT_PASSWORD: - MYSQL_DATABASE: cvbaza2 volumes: - ./db:/var/lib/mysql - ./init:/docker-entrypoint-initdb.d rabbitmq: container_name: b2_rabbit hostname: rabbitmq image: rabbitmq:latest ports: - "5672:5672" restart: on-failure celery_worker: build: ./app command: sh -c "celery -A cv_baza worker -l info" container_name: celery_worker volumes: - ./app/cv_baza:/app depends_on: - b2_app - b2_db - rabbitmq hostname: celery_worker restart: on-failure celery_beat: build: ./app command: sh -c "celery -A cv_baza beat -l info" container_name: celery_beat volumes: - ./app/cv_baza:/app depends_on: - b2_app - b2_db - rabbitmq hostname: celery_beat image: cvbaza_v2_b2_app restart: on-failure memcached: container_name: b2_memcached ports: - "11211:11211" image: memcached:latest networks: default: In this configuration, hitting any route that is supposed to start a task just hands the request until it eventually times out. Example of route class ParseCSV(views.APIView): parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): path = default_storage.save("./internal/documents/csv/resumes.csv", File(request.data["csv"])) parse_csv.delay(path) return Response("Task has started") Task at hand @shared_task def parse_csv(file_path): with open(file_path) as resume_file: file_read = csv.reader(resume_file, delimiter=",") for row in file_read: new_resume = Resumes(first_name=row[0], last_name=row[1], email=row[2], tag=row[3], … -
wsgi: ModuleNotFoundError: No module named 'django' error
I am trying to host my Django app on my Ubuntu server and when trying to access my website, I get this error from the Apache log: ModuleNotFoundError: No module named 'django' I am using a venv for my Django app with python version 3.8 (I have also compiled and installed mod_wsgi in my venv). Running pip freeze I see that I do have Django installed in my venv: APScheduler==3.8.1 asgiref==3.5.0 backports.zoneinfo==0.2.1 certifi==2021.10.8 charset-normalizer==2.0.10 colorama==0.4.4 commonmark==0.9.1 deepdiff==5.7.0 Django==4.0.1 django-cors-headers==3.11.0 djangorestframework==3.13.1 idna==3.3 lxml==4.7.1 mod-wsgi==4.9.1.dev1 ordered-set==4.0.2 prettytable==3.0.0 psycopg2-binary==2.9.3 Pygments==2.11.2 pytz==2021.3 pytz-deprecation-shim==0.1.0.post0 requests==2.27.1 rich==11.1.0 six==1.16.0 soupsieve==2.3.1 sqlparse==0.4.2 tzdata==2021.5 tzlocal==4.1 urllib3==1.26.8 wcwidth==0.2.5 whitenoise==5.3.0 And just in case it might solve it, I installed Django globally but still got the error in Apache. I have been trying to follow some of the common solutions but can't seem to get it to work. Is there anything I am missing or any setting that may be off? I do notice my Apache says it is configured with 3.6, could this be the cause? is there a way to make it use 3.8 which is my python3 default? My wsgi for my Django project (backend/core/wsgi.py): import os, sys sys.path.append('/home/brickmane/djangoapp/pricewatcher/backend/') sys.path.append('/home/brickmane/djangoapp/pricewatcher/backend/core/') sys.path.append('/home/brickmane/djangoapp/pricewatcher/venv/lib/python3.8/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application … -
Static files show in test server but not in production
I have a problem with my Django app not finding static files. When I try to look up the file in the test server, it shows up, on the console I get: [01/Feb/2022 21:34:25] "GET /static/2022/2022-01-12/20220630.pdf HTTP/1.1" 200 295223 But when I try to look at the file in the production server I get this in the error log: 2022/02/01 21:34:08 [error] 6769#6769: *317 open() "/home/pi/Django/my_project/static/2022/2022-01-12/20220630.pdf" failed (2: No such file or directory), client: 192.168.178.**, server: ********, request: "GET /static/2022/2022-01-12/20220630.pdf HTTP/1.1", host: "*******", referrer: "http://myraspi4/documents/doc_show/261" In the settings file I have static directories set up like this: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [ '/mnt/ssd/doc_storage', ] Permissions are -rwxrwxrwx on all files. Other files in other subdirectories show up no problem. What am I doing wrong? -
Creating a function to auto-populate field with another model's field
I want to auto-populate item_selected field from my Order model with the items of the Order (which also a field from Order model). Its difficult for me because they represent different things but similar. Please follow me I will explain better below: From the image above. What I want is to have item selected populate by whatever is selected in items, so in this case, I want "titletitle2" be chosen in item selected since it is selected in Items. So no matter how many times "titletitle2" is selected in items it will just be chosen in item selected once. I assume this can be achieved in the Models, this is the Estore Model below: class eOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey('blog.Post', on_delete=models.CASCADE) item_variations = models.ManyToManyField( ItemVariation) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price def get_total_discount_item_price(self): return self.quantity * self.item.discount_price def get_amount_saved(self): return self.get_total_item_price() - self.get_total_discount_item_price() def get_final_price(self): if self.item.discount_price: return self.get_total_discount_item_price() return self.get_total_item_price() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(eOrderItem) item_selected = models.ManyToManyField( 'blog.Post', blank=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, … -
Styling an html form [closed]
I am trying to have an html form where i can have users style their texts such as make some parts bold, italic, list items, add pictures etc just like the stackoverflow ask question form. Here is a sample I want to save the input using python flask or django into a database and load the data exactly the way it was sent to the database (styled). -
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 24: 'trans'. Did you forget to register or load this tag?
My question is related to DJANGO application After developed my code using locale capability {% trans 'value' %} tag in the correct order all works fine until I turned DEBUG = False in the settings.py.The following error shows: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 24: 'trans'. Did you forget to register or load this tag? The application blocked showing the following message in the Screen. A server error occurred. Please contact the administrator. In the server the following message has been showed. Traceback (most recent call last): File "C:\Python38\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Python38\lib\site-packages\django\core\handlers\wsgi.py", line 133, in __call__ response = self.get_response(request) File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 130, in get_response response = self._middleware_chain(request) File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 49, in inner response = response_for_exception(request, exc) File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 103, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 142, in handle_uncaught_exception return callback(request, **param_dict) File "C:\Python38\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Python38\lib\site-packages\django\views\defaults.py", line 88, in server_error template = loader.get_template(template_name) File "C:\Python38\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Python38\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Python38\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Python38\lib\site-packages\django\template\engine.py", line 125, in find_template template = … -
Real time updates from Rest API
I created the REST API in Django and android application in Java. I need to send/receive real-time updates from the API I developed. May anyone tell me the possible solution to achieve this, Django channels or polling data periodically or other alternatives. Right now I have rest endpoints and data is synchronized using the button(in the android application) to poll data. -
when my project run in locally at that time email is send successfully . but when i deploy my project in heroku that time i get error
SMTPAuthenticationError at /products/registration_phase2/ (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu\n5.7.14 lB4WsSLkRxiExbfj6x9Dp7AeoK9Y8OAbTy2PD236kQLn5wAbGEkCO5hpMPOuH6qb4DGi6\n5.7.14 2_bs9L4dKNiEm63cGZbj4a8UGEPry8XAh437kKQYVIF63wHKoG4OgjwYzRxtyBh->\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 bs8sm7309041qkb.103 - gsmtp') Request Method: POST Request URL: https://aas-system.herokuapp.com/products/registration_phase2/?id=15 Django Version: 3.2.11 Exception Type: SMTPAuthenticationError Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu\n5.7.14 lB4WsSLkRxiExbfj6x9Dp7AeoK9Y8OAbTy2PD236kQLn5wAbGEkCO5hpMPOuH6qb4DGi6\n5.7.14 2_bs9L4dKNiEm63cGZbj4a8UGEPry8XAh437kKQYVIF63wHKoG4OgjwYzRxtyBh->\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 bs8sm7309041qkb.103 - gsmtp') Exception Location: /app/.heroku/python/lib/python3.9/smtplib.py, line 662, in auth Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Tue, 01 Feb 2022 18:33:35 +0000 -
Django REST to_representation: Have serializer fields appear last
I have the following serializer class: class DataLocationSerializer(QueryFieldsMixin, serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = MeasurementsBasic fields = ['temp', 'hum', 'pres', 'co', 'no2', 'o3', 'so2'] def to_representation(self, instance): representation = super().to_representation(instance) representation['timestamp'] = instance.time_received return representation The data is returned in a JSON file structured like this: { "source": "ST", "stations": [ { "station": "ST1", "data": [ { "temp": -1.0, "hum": -1.0, "pres": -1.0, "co": -1.0, "no2": -1.0, "o3": -1.0, "so2": null, "timestamp": "2021-07-04T21:00:03" } ] } ] } How can i make it so the timestamp appears before the serializer's fields? -
I'm trying to add a search functionality to my ListView but it gives Method Not Allowed (POST): error
My search form: <form class=" my-2 my-lg-0 d-flex flex-row-reverse" method=POST action="{% url 'memes:all' %}" > {% csrf_token %} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> <input class="form-control mr-sm-2" name="search" placeholder="Search" aria-label="Search"> </form> My List View: class MemeListView(ListView): model = Meme paginate_by = 100 ordering = ['-created_at'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() search_value = self.request.GET.get("search", False) if search_value: memes = Meme.objects.filter(name_contains=search_value) objects = Meme.objects.filter(memes).select_related().distinct().order_by('-created_at')[:10] context['meme_list'] = objects context['search'] = search_value return context My url: path('', MemeListView.as_view(), name='all'), error: "GET / HTTP/1.1" 200 4455 Method Not Allowed (POST): /all/ Method Not Allowed: /all/ [01/Feb/2022 19:23:22] "POST /all/ HTTP/1.1" 405 0 I've done almost identical search functionality in my other crud and it seems to work. What's the issue? -
How to pass additional arguments to class view in django?
def edit_course(request,course_id): course=Courses.objects.get(id=course_id) return render(request,"hod_template/edit_course_template.html",{"course":course,"id":course_id}) The code above shows a view in django that is defined as a function. I want to recreate the same view as a class based view in django but I couldn't pass in an additional argument such as course_id into the class based view as it shows an error. Can someone tell me how to recreate that above function into a class based view ? -
Get an error when migrate to MySQL in the Django project
I get the same error when I try to browse the app models. My project is on C Panel and connected to MySQL django.db.utils.OperationalError: (1118, 'Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs')