Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mirror an application window in django app?
I am trying to develop a Django app, in which an application window in my windows PC to be shared. So that the clients can view what is happening in the window through the web browser by accessing my Django server. Is there any solution to do this? Please suggest any method to achieve this. -
How to preview images uploaded in django using javascript/jquery
I am having trouble previewing images properly, my code shown below. When I upload the first image for 'Licence Front' it goes to where the image for 'Licence back' should go. What is causing this issue and how can I fix it. Html snippet <!-- LICENCE (FRONT)--> <div class="row"> <div class="form-group col-md-4"> {{ wizard.form.licence_front.label_tag }} {{ wizard.form.licence_front|add_class:"form-control form-control-lg img" }} <div class="error"> {{form.licence_front.errors}}</div> </div> </div> <div class="row"> <div class="col-md-4" style="text-align: center"> <img id="licencefront" style="height: 80px;text-align: center;"> </div> </div> <!-- LICENCE(BACK) --> <div class="row"> <div class="form-group col-md-4"> {{ wizard.form.licence_back.label_tag }} {{ wizard.form.licence_back|add_class:"form-control form-control-lg img" }} <div class="error"> {{form.licence_back.errors}}</div> </div> </div> <div class="row"> <div class="col-md-4" style="text-align: center"> <img id="licenceback" style="height: 80px;text-align: center;"> </div> </div> Javascript <script> function readURL(input) { if (input.files && input.files[0]) { $("#licencefront").show(); var reader = new FileReader(); reader.onload = function(e) { $('#licencefront').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $(function() { //document ready call $("#id_uploads-licence_front").change(function() { readURL(this); }); }); </script> <script> function readURL(input) { if (input.files && input.files[0]) { $("#licenceback").show(); var reader = new FileReader(); reader.onload = function(e) { $('#licenceback').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $(function() { //document ready call $("#id_uploads-licence_back").change(function() { readURL(this); }); }); </script> Css snippet #licencefront{ display: none; } #licenceback{ display: none; } I know my code looks … -
How to test how intensive a Django ORM Query is
I want to know if there is a way to test how intensive a Django ORM Query is. I want to compare two model schemas side by side with different queries. What is the best way to do this? Thanks!! -
Image subcategories from the same image model using foreign keys
I'm seeking to upload an image to the admin, set the image type(primary or thumbnail) and select its thumbnails from a list (none or pick 3-4 from a list of already uploaded images that the image type set to thumbnail). Once that is set, loop through the photo in object_list and also loop through the thumbnails corresponding to that primary image. It seems like an easy task but I just don't know how to correctly approach it. I would really appreciate some experienced help and a details, foolproof answer. Here's what I have so far and what I have been struggling to accomplish. models.py IMAGE_TYPE_CHOICES = ( ('primary', _('Primary')), ('thumbnail', _('Thumbnail')), ('single', _('Single')), ) class ImageModel(models.Model): image = models.ImageField(_('image'), max_length=100, upload_to='myimages') date_taken = models.DateTimeField(_('date taken'), null=True, blank=True, help_text=_('Date image was taken; is obtained from the image EXIF data.')) class Photo(ImageModel): position = models.PositiveIntegerField(default=0, blank=False, null=False) title = models.CharField(_('title'), max_length=250, unique=True) slug = models.SlugField(_('slug'), unique=True, max_length=250, help_text=_('A "slug" is a unique URL-friendly title for an object.')) caption = models.TextField(_('caption'), blank=True) date_added = models.DateTimeField(_('date added'), default=now) image_type = models.CharField(_('image type'), blank=True, max_length=10, default='center', choices=IMAGE_TYPE_CHOICES) #struggling part thumbnails = models.ForeignKey(ImageModel, null=True, blank=True, on_delete=models.CASCADE) objects = PhotoQuerySet.as_manager() class Meta: ordering = ['position'] get_latest_by = … -
How to programatically determine which folder location to store an ImageFile in Django
I have a model that can be used by other models in a foreign key relationship to store images. I want the images to be stored in a directory based on the the calling(??) model. For example: ImageModel(models.Model): title=models.CharField() image = models.ImageField(upload_to="XXX") ModelA(models.Model): image = models.ForeignKey(ImageModel) ModelB(models.Model): image = models.ForeignKey(ImageModel) What's the best way to determine in ImageModel where to store the image based on whether it is coming from ModelA or ModelB? I want to keep the images separate, and so if I don't specify the "upload_to" field then it will store ALL images in the MEDIA_URL field. I want to create subdirectories in the MEDIA_URL field like so: > MEDIA_URL > ModelA img1 img2 > ModelB img3 But I need the ImageModel to know where to put it. I hope this makes sense, maybe another approach would be better but I would love to have feedback! Thanks -
Django & Postgres - Index Row Size Exceeds btree version 4 maximum
I have defined the following in Django to store an SSL certificate in plain-text PEM format: class Certificate(models.Model): pem = models.CharField(max_length=4096, unique=True, blank=False, null=False) When populating the table column in Postgres, I'm seeing this error which says the size of the data is too large for the b-tree index: django.db.utils.OperationalError: index row size 2720 exceeds btree version 4 maximum 2704 for index "app_certificate_pem_key" DETAIL: Index row references tuple (1,6) in relation "app_certificate". HINT: Values larger than 1/3 of a buffer page cannot be indexed. Consider a function index of an MD5 hash of the value, or use full text indexing. Is there a "Django" way to create a unique index based on a hash of my pem column? -
unable to render many to many relationship in html template
I'm trying to render a many to many relationship field values in an HTML template, but nothing shows up in the template. class Order(models.Model): orderitem = models.ManyToManyField('OrderItem') name = models.CharField(max_length=30) address = models.CharField(max_length=100) class OrderItem(models.Model): item = models.ForeignKey(Supplement,on_delete=models.CASCADE) purchase_quantity = models.IntegerField(default=1) def __str__(self): return str(self.item) HTML {% for Order in order %} <tbody> <tr> {% for item in Order.orderitem.all %} <td>{{item}}</td> {% endfor %} {% endfor %} -
How can i solve this issue error during template rendering rendering django?
Error during template rendering in django I'm trying to run the server but it always shows this error. How can i solve this issue. In my item_list.html {% extends "main/base.html" %} {% block body %} <h1>Here is the list of items.</h1> {% for item in items %} {{ item }} {% endfor %} {% endblock %} In base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>merobooks</title> </head> <body> {% block body %} {% endblock %} </body> </html> in views.py from django.shortcuts import render from . models import Item def item_list(request): context = { 'items': Item.objects.all() } return render(request, 'main/item_list.html', context) In urls.py from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('', views.item_list, name='item-list') ] This shows the following error ProgrammingError at / relation "main_item" does not exist LINE 1: ...d", "main_item"."title", "main_item"."price" FROM "main_item... ^ Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.0.8 Exception Type: ProgrammingError Exception Value: relation "main_item" does not exist LINE 1: ...d", "main_item"."title", "main_item"."price" FROM "main_item... ^ Exception Location: C:\Users\keskh\.virtualenvs\merobooks-K3uFXFWX\lib\site-packages\django\db\backends\utils.py in _execute, line 86 Python Executable: C:\Users\keskh\.virtualenvs\merobooks-K3uFXFWX\Scripts\python.exe Python Version: 3.8.1 Python Path: ['C:\\Users\\keskh\\Desktop\\Python\\dev\\djangoDev\\merobooks', 'C:\\Users\\keskh\\.virtualenvs\\merobooks-K3uFXFWX\\Scripts\\python38.zip', 'c:\\users\\keskh\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\keskh\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\keskh\\appdata\\local\\programs\\python\\python38-32', 'C:\\Users\\keskh\\.virtualenvs\\merobooks-K3uFXFWX', 'C:\\Users\\keskh\\.virtualenvs\\merobooks-K3uFXFWX\\lib\\site-packages'] Server time: Fri, … -
PYTHON + DJANGO or KIVY..... VS REACT or VUE...how is using Python for a website vs react or Vue?
im starting to use Python, vs JS, the beginning seems familar, but the layouts of code are not. how does using Python + Django or Kivy, compare to React + Styled Components, Framer Motion?? or, is Python really meant for Desktop? should i use Python for Websites? -
Getting Mime Type Error when loading Django CSS
today I had an issue with my Django project CSS files. My CSS files do not load when I try accessing my page. At first, I thought the issue was only with the Django admin, so I asked this question, however, I think this issue deserves its own question. My pages load as normal, just without CSS style, and no errors show up. However, in the chrome console, I find this Error: Refused to apply style from 'https://[mywebsite].com/static/pathToMyCssFile/file.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I don't understand what it means by "its MIME type ('text/html') is not a supported stylesheet MIME type"? Is it detecting my CSS code as HTML, or the other way round? my settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import mimetypes # A Bug is was encountering mimetypes.add_type("text/css", ".css", True) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # … -
Why is my session variable not persisting after server restart in Django
I have a Django server handling Reddit authentication via PRAW and OAuth. The following are the views I've written. # unsaver/my_site/views.py def default_view(request): if (request.session.get('refresh_token')): return redirect('/home') else: return redirect('/login') def home_view(request): if (request.session.get('refresh_token')): code = request.session.get('code') rf = request.session.get('refresh_token') print(f'code is {code}\nrefresh_token is {rf}') reddit_authenticated = praw.Reddit("unsaver", refresh_token=rf, user_agent="unsaver for reddit") user_name = reddit_authenticated.user.me() return HttpResponse(user_name) else: return redirect('/login') def login_view(request): if (request.session.get('refresh_token')): return redirect('/home') reddit = praw.Reddit("unsaver", user_agent="unsaver for reddit") authentication_uri = reddit.auth.url(["identity", "read", "save", "history"], random.randint(1, 99999), "permanent") template = loader.get_template('my_site/login.html') return HttpResponse(template.render({'auth_url': authentication_uri}, request)) def authenticated(request): reddit = praw.Reddit("unsaver", user_agent="unsaver for reddit") code = request.GET.get('code', '') refresh_token = reddit.auth.authorize(code) request.session['code'] = code request.session['refresh_token'] = refresh_token return redirect('home') and following is its corresponding urls.py # unsaver/my_site/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.default_view, name='default'), path('home', views.home_view, name="home"), path('login', views.login_view, name="login"), path('authenticated', views.authenticated, name="authenticated") ] Initially when I start my server, it defaults to localhost:8000/login, after clicking on the login link and authenticating via Reddit it redirects to localhost:8000/home and then after subsequent reloads it redirects to home properly, even with multiple tabs. However, when I stop my server and run again, and click on the development server link given by Django, … -
How to check for object after template filter
I need to check if objects exist after using a template filter. The view is a VideoListView but I am filtering the videos by category. If a category contains no videos I need to skip it. {% for category in category_list %} {% if video in videos|in_category:category not None %} <h4 class="main-panel-title">{{ category }}</h4> <div class="tile-row"> <div class="tile-row__inner"> {% for video in videos|in_category:category %} <a href="{% url 'videos-detail' video.id %}" title="{{ video.description }}"> <div class="tile"> <div class="tile__media"> <div class="video-img-container"> {% if video.thumbnail %} <video id="video" poster="{{ video.thumbnail.url }}" preload="none" src='{{ video.video_file.url }}' width='100%'> </video> The line {% if video in videos|in_category:category not None %} gives an error: TemplateSyntaxError at /videos/ Not expecting 'not' as infix operator in if tag. How can I check the value after the template filter? -
Is it possible to use a library with command line functionality inside a python file?
In my Django web app I want to convert an uploaded csv file into a markdown table. I searched around and found this library that does that. However it only has instructions on how to do it from the command line, like so: csvtomd input.csv > output.md, but I want to use it inside my python file (views.py) and I don't know if it is even possible. I understand there might be another way I can get this specific task done, but I want to know if it is possible to use the functionality of such a library, that is accessible from the commandline, inside my python file instead. I came across this question; however, I after something specifically for using a python library inside a python file, and not general prompt commands. -
Unable to import 'users.signals'pylint(import-error)
I am trying this for the first time and i got error in importing signals from apps.py from django.apps import AppConfig class ChitchatConfig(AppConfig): name = 'chitchat' def ready(self): import users.signals from signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import user_Profile @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: user_Profile(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.user_Profile.save() -
Django error: User matching query does not exist
So I have this models in my Django project, I am trying to get the user2 variable or the other user of my models class ThreadManager(models.Manager): def by_user(self, user): qlookup = Q(first=user) | Q(second=user) qlookup2 = Q(first=user) & Q(second=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None qlookup1 = Q(first__username=username) & Q(second__username=other_username) qlookup2 = Q(first__username=other_username) & Q(second__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model( first=user, second=user2 ) obj.save() return obj, True return None, False class Thread(models.Model): first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first') second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() and my views def Messages(request, *args, **kwargs): Chats = Thread.objects.by_user(request.user) other_username = kwargs.get("username") other_user = Thread.objects.get_or_new(request.user, other_username) context = { 'content': Chats, 'chatname': other_user } return render(request, "chat/messages.html", context) But when I try to get the other user I get the title error, Does anybody know what is going on? Thank for the help -
Django rest framework - multiple image uploads not showing
I wanted to upload multiple images in a Post model by following this answer. As Admin, I can successfully upload multiple images to the certificates fields but when I view the post detail, or post list pages in browser, the certificates do not show. Here is the json: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "title": "Post One", "description": "Lorem ipsum", "url": "http://www.postone.com", "country": "United Kingdom", "coverImage": "http://localhost:8000/media/cover_images/Post%20One/earth-large_yPJZXAH.jpg", "tags": [ "UK" ], "creator": "Admin", "slug": "post-one" } ] } For some reason, the certificate images that were uploaded in Admin are not showing on the post details or list pages. Here are the models: class Post(models.Model): creator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='posts') title = models.CharField(_('Title'), max_length=255, blank=False, null=False) description = models.TextField(_('Description'), max_length=500, blank=False, null=False) url = models.URLField(_('URL'), unique=True, max_length=255, blank=False, null=False) country = models.CharField(_('Country'), max_length=255, blank=False, null=False) cover_image = ProcessedImageField( verbose_name=_('Cover'), blank=False, null=False, format='JPEG', options={'quality': 90}, processors=[ResizeToFill(600, 200)], upload_to=cover_image_directory) STATUS_DRAFT = 'D' STATUS_PUBLISHED = 'P' STATUSES = ( (STATUS_DRAFT, 'Draft'), (STATUS_PUBLISHED, 'Published'), ) status = models.CharField(blank=False, null=False, choices=STATUSES, default=STATUS_DRAFT, max_length=2) tags = TaggableManager(blank=True) slug = models.SlugField(max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, … -
How do I use 'Django Forms' to process user input?
I am creating a kind of dashboard which, when it's finished, will allow the user to (1) upload a profile picture, (2) Enter a displayname for themselves, and (3) Edit and change their profile picture as well as their displayname should they want to. https://github.com/pmahalan/Avybe_Database_Project I have the front-end built out (the template and view), and I have the model built out. The I labeled the model "creator", as in content creator - the two objects associated with it are "name" (corresponds to their displayname) and "upload" (corresponds to their picture). I also have URL paths associated with the submit and upload buttons, which do work when clicked on. However, clicking submit after typing in a new username or uploading a new picture still doesn't actually make a change to the person's info. I can alter the info if I personally do it through Django Admin, but that's it. I want the frontend user to be able to effectively change it through their input and when they click the "submit" buttons. Do I create the Django within my views.py file? Do I create two separate forms (one for the display name and one for the profile picture), or just one? … -
Django Celery Redis - Why is the a specific task being done 6 times?
I am using Django, Celery and Redis. I setup a timed task to run in the future using the following: send_message.apply_async((arg1, arg2, arg3), eta=scheduled_time) Most of the times it runs just once, but one time when I set the task to run 5 hours later the task ran 6 times, I know this because I received 6 identical messages exactly 5 hours later. I was able to retrieve the following logs from my servers for this particular issue, I see two tasks that have succeeded with the same task id. Again, most of the times task only runs once, what is causing this occasional issue? 2020-07-30T19:16:05.315426+00:00 app[worker.1]: [2020-07-30 19:16:05,315: INFO/ForkPoolWorker-1] Task myapp.tasks.send_message[12345678-1234-1234-1234-123456789012] succeeded in 0.5926916640019044s: None 2020-07-30T19:16:05.421541+00:00 app[worker.1]: [2020-07-30 19:16:05,421: INFO/ForkPoolWorker-2] POST Response: 201 2020-07-30T19:16:05.527690+00:00 app[worker.1]: [2020-07-30 19:16:05,527: INFO/ForkPoolWorker-2] POST Request: 2020-07-30T19:16:05.530644+00:00 app[worker.1]: [2020-07-30 19:16:05,530: INFO/ForkPoolWorker-2] PAYLOAD 2020-07-30T19:16:05.785784+00:00 app[worker.1]: [2020-07-30 19:16:05,785: INFO/ForkPoolWorker-2] POST Response: 201 2020-07-30T19:16:05.809228+00:00 app[worker.1]: [2020-07-30 19:16:05,808: INFO/ForkPoolWorker-2] POST Request: 2020-07-30T19:16:05.809435+00:00 app[worker.1]: [2020-07-30 19:16:05,809: INFO/ForkPoolWorker-2] PAYLOAD: 2020-07-30T19:16:05.980180+00:00 app[worker.1]: [2020-07-30 19:16:05,979: INFO/ForkPoolWorker-2] POST Response: 201 2020-07-30T19:16:06.010700+00:00 app[worker.1]: [2020-07-30 19:16:06,010: INFO/ForkPoolWorker-2] Task myapp.tasks.send_message[12345678-1234-1234-1234-123456789012] succeeded in 1.0963465569948312s: None -
Django is using relative path for static files
Thank you for reading this. I'm currently working on an e-commerce website, when I ran into a problem, after having finished the home page I branched out to other files, it's at this point that I found out that Django's Static Files are using relatives paths to find the static data, which is not what I want, after having searched online I came across a solution which says to ensure that static_url = '/static/, this, however, is already the case in my settings.py. I have found that the debug_toolbar is still using the same static path (i.e not relative), and is consistent throughout the pages of my website, I will provide the code of my views.py, urls.py, and settings.py. If anyone needs any other files please comment below. Thank you again settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#=8boas)tr(_dzd8zyz%14iksgf(rv(!ee8z@-ou#q)%0#zpti' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Graphene-Django, fetching 10,000+ data points
I am building a backend GraphQL service with Django & Graphene and I am having trouble with figuring out what the best way would be to fetch thousands of data points in a performant manner. Some context, we have an experiment that has 35,000 data points that needs to be displayed on a Plotly plot. The data points are stored in a database table called data_point. Here is the schema of this table: data_point_id | value | type | created_at In my Graphene schema, I have a resolver to get all data points for a given experiment as shown below class ExperimentNode(DjangoObjectType): users = generic.GenericScalar() aliases = generic.GenericScalar() properties = generic.GenericScalar() data_points = graphene.List(DataPointType) class Meta: model = Experiment # what other filter fields would we want for a batch? filter_fields = { 'experiment_id': ['exact'] } interfaces = (graphene.relay.Node, ) def resolve_data_points(self, info, **kwargs): try: data_points_for_experiment = DataPoint.objects.filter(experiment_id=self.experiment_id) data_points = [] for data_point in data_points_for_experiment: value = data_point.numeric_value measured_at = data_point.measured_at attribute = data_point.measurement_type_id data_points.append({ "value": value, "measured_at": measured_at, "attribute": attribute }) return data_points except Exception: return None Here is my query class class Query(graphene.ObjectType): all_batches = DjangoFilterConnectionField(BatchNode) When I run the query, as expected, it takes a very long … -
KeyError: 'user'
good Day fellas i want to extend my django user model using rest_framework to create an api endpoint for project, but i'm getting a KeyError: user, below is my code hoping anyone can help me out profile apiView class ProfileListView(generics.ListCreateAPIView): permission_classes = (IsAuthenticatedOrReadOnly,) queryset = Profile.objects.all() serializer_class = ProfileSerializer profile serializer class ProfileSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source = 'pk', read_only = True) username = serializers.CharField(source = 'user.username', read_only = True) email = serializers.CharField(source = 'user.email', read_only=True) class Meta: model = Profile fields = ('id', 'email', 'username', 'qualification', 'profession', 'phoneNumber', 'city', 'address', 'surname', 'firstName', 'dp', 'yearOfExperience', 'gender' ) def create(self, validated_data, instance=None): user_data = validated_data.pop('user') user = CustomUser.objects._create_user(**validated_data) Profile.objects.create(user=user, **user) return user profile model class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) firstName = models.CharField(max_length=255, blank=True, null=True) surname = models.CharField(max_length=255, blank=True, null=True) yearOfExperience = models.PositiveIntegerField(default=1) profession = models.CharField(max_length=250, blank=True, null=True) dp = models.URLField(blank=True, null=True) qualification = models.CharField(max_length=255, blank=True, null=True) phoneNumber = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=255, choices=GENDER) class Meta: ordering = ('surname', '-firstName', ) verbose_name = 'Profile' verbose_name_plural = 'Profiles' def __str__(self): return self.user.username @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance=None, created=False, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() err msg File "/home/olaneat/Desktop/filez/project/django/funzone/lib/python3.7/site-packages user_data = validated_data.pop('user') KeyError: … -
Django: Converting uuid value to a string in django template engine
I have this code of line that I need to be up and running. <h4 class="page-header"> {% if msg.sent_by_id == request.user.public_id|string %} {% if request.user.role == 'administrator' %}Admin Replied {% elif request.user.role == 'user' %}Your reply {% endif %} {% endif %} </h4> The problem is that these two values are the same, BUT both of them are other format. msg.sent_by_id is a string, neither request.user.public_id, this value is in uuid format. What is the correct way of 'converting' an variable to a string and then comparing the two values? -
How to fix product variants issue in a Django E-commerce
I have a problem with the variations and the quantity related to it in the order summary page. when I add to the cart 2 items: Item X with a size small Item X with a size medium When I change the quantity of item X size medium, this change is reflecting in item X size small which was chosen first. In the order summary, there are a plus and minus in the template to change the quantity. I have recently understood that because there's no form in the template. The code that sends a POST request with form data to the add to cart view is not there, because item_var will always be an empty list so order_item.variation.add(*item_var) does nothing. I do not know how to add a POST request to this template. in the template there is a URL to add-to-cart", but URLs are transmitted by GET, so the code after if request.method == 'POST': never hits. Furthermore, even if it would, the add_to_cart url knows nothing about variations cause it only gets item slugs. Here is the template: {% extends "base.html"%} {% block content %} <!--Main layout--> <main> <div class="container"> <div class="table-responsive text-nowrap" style="margin-top:90px"> <h2> Order Summary</h2> … -
In Django's rest framework, how do I turn off validation for certain fields in my serializer?
I'm using Django 3, Python 3.8, and the Django Rest framework. Additionally, I'm using the address module from here -- https://github.com/furious-luke/django-address. I have built the following serializers for the address objects as well as one of my own taht depends on them ... class CountrySerializer(serializers.ModelSerializer): class Meta: model = Country fields = ['id', 'name', 'code'] def to_representation(self, instance): rep = super().to_representation(instance) return rep class StateSerializer(serializers.ModelSerializer): country = CountrySerializer() class Meta: model = State fields = ['id', 'code', 'country'] def to_representation(self, instance): rep = super().to_representation(instance) rep['country'] = CountrySerializer(instance.country).data return rep class LocalitySerializer(serializers.ModelSerializer): state = StateSerializer() class Meta: model = Locality fields = ['id', 'name', 'postal_code', 'state'] def to_representation(self, instance): rep = super().to_representation(instance) rep['state'] = StateSerializer(instance.state).data return rep def create(self, validated_data): """ Create and return a new `Locality` instance, given the validated data. """ validated_data['state'] = validated_data['state'].id print("\n\n\n\n****####\n\n", validated_data, "\n\n\n\n") return "{bogus}" #return Locality.objects.create(**validated_data) class AddressSerializer(serializers.ModelSerializer): locality = LocalitySerializer() #LocalityTypeField() class Meta: model = Address fields = ['id', 'street_number', 'route', 'raw', 'formatted', 'latitude', 'longitude', 'locality'] def to_representation(self, instance): rep = super().to_representation(instance) rep['locality'] = LocalitySerializer(instance.locality).data return rep def create(self, validated_data): """ Create and return a new `AddressField` instance, given the validated data. """ address = AddressTypeField.objects.create(**validated_data) return address class CoopSerializer(serializers.ModelSerializer): types = CoopTypeSerializer(many=True, … -
Django force using cache on queryset
I am using Django queryset with slicing. I want to evaluate it once and then use the cached result. This is the code: items_filtered = Item.objects.filter(......) items_filtered_sliced = items_filtered[:100] items_filtered_sliced_updated = Item.objects.filter(pk__in=items_filtered_sliced).update(....) I need to use the 'items_filtered_sliced' queryset later to filter it, so in order to prevent filtering sliced queryset (which is not possible) I wanted to use the queryset first result and tried this - items_filtered_sliced2 = Item.objects.filter(pk__in=items_filtered_sliced) But seems like the 'items_filtered_sliced' is evaluated again and returns the next 100 instead of returning the previous result.