Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need help displaying data in a specific format using Django and Python
I am very much a newbie at Django and python, so please be gentle! I have a database with a table that has date, time, position, group number, and the names of the people in each group. This table is for scheduling purposes. The table has several lines with date, depending on the total number of people scheduled per day, three different shifts at the moment (time), and three positions. Each group that fills each position can have a varying number of people in it, and each position has a different number of groups for each time slot. What I want is something that has the date on the first row, the three times on the second row, the three positions under each of the three times on the third row, then list the group number and each person. Row 1: 1 column (date) Row 2: 3 columns (time) Row 3: 9 columns (position) Row 4-? 9 columns (group number, names listed under each group number) Honestly, I have no idea how to accomplish this layout. Any ideas? Here's the code I have so far. Thanks! View: def index(request): context = {} sched= Schedule.objects.all() context['sched'] = sched return render(request, 'index.html', … -
ModuleNotFoundError while deploying django server on heroku
I am having trouble while deploying server on heroku (ModuleNotFoundError: No module named 'screen_sender') I think it may be because I use django-channels you can see my directories below and files: Procfile web: gunicorn websocket_image_sender.wsgi settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'key' IS_HEROKU = "DYNO" in os.environ if not IS_HEROKU: DEBUG = True if IS_HEROKU: ALLOWED_HOSTS = ["*"] else: ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'screen_sender', 'channels', ] ASGI_APPLICATION = 'websocket_image_sender.asgi.application' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'websocket_image_sender.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'websocket_image_sender.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' # Default primary key … -
Can I deploy a Django App if there is no "" (empty) url?
I'm trying to deploy a Django App with railways for the first time and I was wondering where exactly will be my landing page. So basically my urls.py looks something like this: path('home/', views.home, name="home"), path('blogposts/', views.blogposts, name="blogposts"), path('posts/', views.posts, name="posts"), After deploying my Blog website, let's say with the domain 12345xxx.com, where will I land? -
Python WSGI Server for Kubernetes?
I want to run my Django application in Kubernetes. In Kubernetes the available ressources could limited, and the amount of CPUs you get with traditional methods could be wrong. For Go this gets handled with https://github.com/uber-go/automaxprocs Up to now I use gunicorn, but I could switch to a different wsgi server. Which wsgi server is recommended to run Django applications in Kubernetes? -
Admin approval and email verification with all-auth
I want to implement an admin approval and email confirmation system for the signup process. For now, I am using the 'is_active' field set False by default, until the admin sets it manually to True. It works so far, the only problem is that the confirmation mail is not being sent out when 'is_active' is False. The email-confirmation flag is actually in another table called accounts_emailaddress, so I am wondering why this is not working? Depending on which flag is set to False, the user should be redirected to the corresponding Templates. The user should not be able to log in, unless the email is verified and his profile approved by the administrator. How can I achieve this result? -
Using VCR mechanics to record and play queries to SQL database
Is it a viable approach to allow recording SQL queries to a file and later loading these queries from the file to memory and playing queries by monkey patching the db driver? I had employed this method in the past for recording http queries to external services with library vcrpy. I don't see any obstacles in implementation. The question is, does it even make sense in terms of test speed improvement? Also, what inconsistencies or pitfalls in usage of such an approach might this cause? -
DigitalOcean Django Rest Framework Authentication credentials were not provided
My live site decided to throw a 403 Forbidden error yesterday on authenticated users when calling an Ajax API and I've trying to troubleshoot with no success. The localhost on my machine works fine when DEBUG = True in my settings.py, but the same code throws the following error: HTTP 403 Forbidden Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Authentication credentials were not provided." } My rest framework setting in settings.py: ## REST framework default permissions REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } Since the browsable API requires SessionAuthentication, I tried the following with no success: ## REST framework default permissions REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } I did look at Django Rest Framework Docs and it seems to suggest that if my user is logged in, the Ajax calls after login should work fine. Am I missing something? Really appreciate your input UPDATE 1: When I run the command: sudo journalctl -u gunicorn -n 25 One of the things I see is gunicorn[820]: Session data corrupted I did restart the server, hoping that by logging back in, the new session data will be generated, but the same message is … -
Modifying X-frame-options in a Django app deployed using Heroku
I'm trying to embed an iframe on my portfolio page of a django app that I deployed on heroku. After doing some reading, apparently, I have to modify this property called X-frame-options in my HTTP headers, but I'm not sure where I'm supposed to find it in my Django or Heroku files/dashboards and what I'm supposed to set it to if I want to allow it to be embedded on an external website? -
Django Rest Framework | How to create a new product with Category name not ID
I have two models created in Django. I am trying to send post request from react frontend using axios API call. My react is working fine and I can post request using category id but not with category name ( either hardcoded or from the dropdown list) I tried using Postman, I get the same result. class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(unique=True, null=True, blank=True) def save(self,*args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def __str__(self): return self.name class Product(models.Model): upc = models.CharField(max_length=30) name = models.CharField(max_length=100) description = models.TextField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() price = models.IntegerField() def __str__(self): return self.name views.py from .models import Product from .serializers import ProductSerializers from rest_framework import generics class ProductList(generics.ListCreateAPIView): serializer_class = ProductSerializers def get_queryset(self): queryset = Product.objects.all() return queryset class ProductDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = ProductSerializers queryset = Product.objects.all() Serializers.py from .models import Product, Category from rest_framework import serializers class CategorySerializers(serializers.ModelSerializer): class Meta: model = Category fields="__all__" class ProductSerializers(serializers.ModelSerializer): category_name = serializers.SerializerMethodField('get_category_name') def get_category_name(self, obj): if obj.category_id: return obj.category.name class Meta: model = Product fields = '__all__' I am sending post request from react axios. axios.post(productListURL, data) How do I send post request with category name: name:"Coca Cola" , category:"Beverage" Instead … -
Django Filters on multiple models
I am a new django/python user and I am having an issue using django-filters with related models. I have created a tutorial application for myself with two models: class Customer(models.Model): def __str__(self): return self.Customer_Name Customer_Name = models.CharField(max_length=100) SFDC_Customer_Record_Number = models.IntegerField(default='') Zone = models.CharField(max_length=50, default='') Government = models.BooleanField(default=False) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.DO_NOTHING,default=User) class Vue_Quote(models.Model): def __str__(self): return self.Quote_Name Quote_Name = models.CharField(max_length=100) SFDC_Golden_Opp_ID = models.IntegerField() Vue_System_Count = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.DO_NOTHING,default=User) Quote_Type = models.CharField(max_length=100) Customer = models.ForeignKey(Customer , on_delete=models.DO_NOTHING, default='') I have also created a filter.py file: import django_filters from .models import * class CustomerFilter(django_filters.FilterSet): class Meta: model = Customer fields = { 'Customer_Name': ['icontains'], 'Zone' : ['icontains'], } class QuoteFilter(django_filters.FilterSet): class Meta: model = Vue_Quote fields = { 'Quote_Name': ['icontains'], 'author__username' : ['icontains'], 'Customer__Customer_Name' : ['icontains'], } In my templates I want to display the filter fields for quoteFilter and customerFilter (this is working). Then I have a sort of gallery/list that iterates through each customer and their respective quotes. My issue is that only my customerFilter works. I cannot find anyway to create nested for loops that can provide results for the user input across both model's fields. Here is my current html … -
Django Duplicate Detection
I've got a large database of contacts, each owned by a specific user. I'm attempting to remove any duplicates within each user's contact list. The simplest seemed to be to annotate with a string of user_id||name||address||zipcode, Count, and filter by count > 1. This has worked in most cases, but I've got some weird holdouts. Can anyone point out what I'm missing? Here's some code... I'm filtering to a specific name that I know has duplicates for testing. neighbors = neighbors.filter(name__icontains='JOHN WILLIAMS') keyed_neighbors = neighbors.values('user_id', 'name', 'address', 'zipcode', 'pk' ).annotate(dupe_id=Concat( Cast('user_id', CharField(max_length=25)), Value('||'), Upper('name'), Value('||'), Upper('address'), Value('||'), Substr('zipcode', 1, 5), Value('||'), Upper('address_line_two'), output_field=CharField())) dupes = keyed_neighbors.annotate(dupe_id_count=Count('dupe_id')) Here's a subset of the dupe_ids that I get back, and the counts: {'dupe_id': u'174563||JOHN WILLIAMS||222 WEDGEFIELD DR||28376||', 'dupe_id_count': 1} {'dupe_id': u'175875||JOHN WILLIAMS||4 TALLIN CT||29607||', 'dupe_id_count': 1} {'dupe_id': u'175875||JOHN WILLIAMS||4 TALLIN CT||29607||', 'dupe_id_count': 1} {'dupe_id': u'177178||JOHN WILLIAMS||5106 PAUL PEEL PL||28348||', 'dupe_id_count': 1} {'dupe_id': u'51||JOHN WILLIAMS||2410 COLGATE DR||28304||', 'dupe_id_count': 1} {'dupe_id': u'51||JOHN WILLIAMS||2410 COLGATE DR||28304||', 'dupe_id_count': 1} {'dupe_id': u'51||JOHN WILLIAMS||4 TALLIN CT||29607||', 'dupe_id_count': 1} If anyone can shine a light on my mistake I'd very much appreciate it. -
How to create a mysql database in Django on the first run?
I'd like my application to be "plug-and-play", so I need to automatically create the database on the first run. I use docker with docker-compose My attempt is to connect without specifying the database name and run a custom command before running the server: command: sh -c "python manage.py create_db && python manage.py runserver 0.0.0.0:8000" And the command itself: class Command(BaseCommand): """Django command to create DB""" def handle(self, *args, **options): con = connections['default'] db_name = os.environ.get('DB_NAME') db_up = False while not db_up: try: cursor = con.cursor() cursor.execute(f'CREATE DATABASE IF NOT EXISTS {db_name}') cursor.execute(f'USE {db_name}') db_up = True except Exception as err: self.stdout.write('Database unavailable, waiting 1 second...') self.stdout.write(str(err)) time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) If this is the right way, then now I just need to update the connection to use the newly created database, but I don't know how. The line cursor.execute(f'USE {db_name}') of course doesn't work. Is it the right way to create the database? If so, how to update the connection? If not, how to do it? Thanks! -
How do I route my databases in Django based on which user is logged in?
I am making a django website and I want each user to have their own database, for example now I have 2 databases hosted on azure, and in my settings.py file I have this: DATABASES = { 'default' :{}, 'user1': { 'ENGINE': 'django.db.backends.mysql', 'NAME' : 'temp monitoring', 'USER' : 'maxwhitehead@maxiot', 'PASSWORD' : '#######', 'PORT' : 3306, 'HOST' : 'maxiot.mysql.database.azure.com', }, 'user2':{ 'ENGINE': 'django.db.backends.mysql', 'NAME' : 'temp monitoring', 'USER' : 'maxwhitehead@maxiot2', 'PASSWORD' : '#######', 'PORT' : 3306, 'HOST' : 'maxiot2.mysql.database.azure.com', } } I have a folder called users, and within that I have a file called Fields that includes this: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] So I want people to login and see the posts from their associated database. I know I have to do something with database routing but I am not sure what, any help would be appreciated, thanks. -
Django Like Function With viewsets
Hey guys I try make blog app I take "detail": "Method "POST" not allowed." whwn I send get request to "/blog/like/1,2..." I take response but i cant send Post request That is The Models class Like(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.created_by.username That is serializers class LikeSerializer(serializers.ModelSerializer): created_by = serializers.StringRelatedField() post = serializers.StringRelatedField() class Meta: model = Like fields = ( 'created_by', 'post', 'post_id' ) That is views class LikeView(viewsets.ModelViewSet): queryset = Like.objects.all() serializer_class = LikeSerializer def perform_create(self, serializer): serializer.save(created_by=self.request.user) def post(self, post_id): post = Post.objects.get(id=post_id) if Like.objects.filter(post=post, created_by=self.request.user).exists(): Like.objects.filter( post=post, created_by=self.request.user).delete() else: Like.objects.create(post=post, created_by=self.request.user) that is Urls from django.urls import path from .views import ( PostView, PostView_View, LikeView, CommentView ) from rest_framework import routers router = routers.DefaultRouter() router.register('', PostView) router.register('like', LikeView) urlpatterns = [ ] + router.urls -
Accessing the attribute of a model through a shared foreign key in another model
I am a complete newbie to the world of Django and I'm confused as to how I can access the list of values from a table that has access to another table through a foreign key. Here is the Request model: class Request(models.Model): """ Carry requests """ sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="requests") offers = models.ManyToManyField("Offer", blank=True) code = models.UUIDField(max_length=64, default=uuid.uuid4, editable=False) weight = MeasurementField( measurement=Weight, validators=[MinValueValidator(Weight(g=1))], verbose_name=gettext_lazy("Weight") ) description = models.TextField(blank=False) origin_country = models.ForeignKey( Country, on_delete=models.PROTECT, related_name="origin_requests", verbose_name=gettext_lazy("Origin Country") ) origin_city = models.ForeignKey( City, on_delete=models.PROTECT, related_name="origin_requests", verbose_name=gettext_lazy("Origin City") ) destination_country = models.ForeignKey( Country, on_delete=models.PROTECT, related_name="destination_requests", verbose_name=gettext_lazy("Destination Country"), ) destination_city = models.ForeignKey( City, on_delete=models.PROTECT, related_name="destination_requests", verbose_name=gettext_lazy("Destination City"), ) status = models.CharField(max_length=40, choices=Status.choices, default=Status.AVAILABLE) reward = MoneyField( max_digits=1000, decimal_places=2, default_currency="PHP", validators=[MinMoneyValidator(defaultdict(lambda: 0.01))], verbose_name=gettext_lazy("My Initial Offer Fee"), ) photo = models.ImageField(upload_to="requests/", verbose_name=gettext_lazy("Photo of Item")) accepted_offer = models.ForeignKey( "Offer", on_delete=models.SET_NULL, blank=True, null=True, related_name="accepted_requests" ) add_insurance = models.BooleanField(default=False, verbose_name=gettext_lazy("I WANT 100% INSURANCE FOR MY ITEMS")) declared_amount = MoneyField( max_digits=1000, decimal_places=2, default_currency="PHP", validators=[MinMoneyValidator(defaultdict(lambda: 0.01))], verbose_name=gettext_lazy("Declared Amount"), blank=True, null=True, ) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) history = HistoricalRecords(excluded_fields=["sender", "code", "created", "modified"]) @property def short_code(self) -> str: return str(self.code)[:8] def __str__(self) -> str: return f"({str(self.code)[:8]}) @{self.sender.username}: {self.origin_country} -> {self.destination_country}" Here is the Negotiation model: class Negotiation(models.Model): request … -
Using VCR mechanics to record and play queries to SQL database [closed]
Are there any libraries for python that would allow recording SQL queries to a file and later loading these queries from the file to memory and playing queries by monkey patching the db driver? I had employed this method in the past for recording http queries to external services with library vcrpy. I don't see any obstacles in implementation. The question is, does it even make sense in terms of test speed improvement? Also, what inconsistencies or pitfalls in usage of such an approach might this cause? -
Why the ListView not showing data in the template?
I'm working on my first Django project (the final project for codecademy's Django class) and I'm making webpages to show the inventory and menu that a restaurant has. I made the model, view, template, etc. for inventory and it displays the ListView perfectly. I did the same thing for my menu and it doesn't work. The page loads but the table that's supposed to output data is empty. Any insight on what might be going wrong? PS I'm new to programming and this is my first stackoverflow post so forgive any formatting errors or other faux pas ## views.py from django.http import HttpResponse from django.shortcuts import render from .models import Inventory, MenuItem, RecipeRequirement, Purchase from django.views.generic.edit import CreateView, DeleteView, UpdateView from django.views.generic import ListView # Create your views here. def index(request): return render(request, "index.html") class InventoryList(ListView): template_name = "inventory.html" model = Inventory class MenuList(ListView): template_name = "menu.html" model = MenuItem Inventory (below) works fine! :) {% extends './base.html' %} {% block content %} <h2>Inventory</h2> <table id="inventory"> <tr> <th>Ingredient</th> <th>Price</th> <th>Units Available</th> </tr> {% for ingredient in inventory_list %} <tr> <tr> <td>{{ ingredient.ingredient_name }}</td> <td>{{ ingredient.price }}</td> <td>{{ ingredient.units_avail }}</td> </tr> {% endfor %} </table> {% endblock %} This one (Menu) … -
How to print multiple values from two lists in django template
I am trying to figure out a way to print values from two different context variables in a single loop. I have tried the zip() method but it does not seem to work and does not print variables on the template. This is how I tried index.html <tbody> {% for item1, item2 in mylist %} <tr> <td><a href="/{{ url.short_url }}">/{{ item1.short_url }}</a></td> <td>{{ item1.original_url }}</td> <td>{{ item1.created_at }}</td> <td>{{ item1.clicks|intcomma }}</td> <td>{{ item2.browser }}</td> <td>{{ item2.platform }}</td> <td><a href="#"> <svg class="octicon octicon-graph" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"> </path> </svg> </a></td> </tr> {% endfor %} </tbody> views.py def index(request): urls = Url.objects.order_by('-created_at') clicks = Click.objects.order_by('-created_at') # context = {'urls': urls, 'clicks': clicks} mylist = zip(urls, clicks) context = { 'mylist': mylist, } return render(request, 'heyurl/index.html', context) But on running the local server I don't see anything on the table view. What am I doing wrong here? Are there any alternatives ? Here's my current version of code. models.py from django.db import models class Url(models.Model): short_url = models.CharField(max_length=255) original_url = models.CharField(max_length=255) clicks = models.IntegerField(default=0) created_at = models.DateTimeField('date created', auto_now_add=True) updated_at = models.DateTimeField('date updated', auto_now=True) class Click(models.Model): url = models.ForeignKey(Url, on_delete=models.CASCADE, related_name='related_clicks') browser … -
Invalid default value for 'id' - Django project
When I try to migrate I get this error Invalid default value for 'id' And in my dictionary I have no 'id' fields models.py from django.db import models class Product(models.Model): code=models.SlugField(max_length=70,unique=True) designation=models.CharField(max_length=255) def __str__(self): return self.article.code views.py from .models import Product def viewproduct(request): products={'message':'passe','my_product':[{'code':'mlkk','designation':'toto'}, {'code':'molo','designation':'patate'},...]} all_products=products['my_product'] for product in all_products: object_product=Product(code=product['code'],designation=product['designation']) object_product.save() Noted that my dictionary contains several products -
django 404 error The current path, didn’t match any of these
i have such error, when i try edit or delete: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/edit/ Using the URLconf defined in lab4new.urls, Django tried these URL patterns, in this order: create/ edit/<int:id>/ delete/<int:id>/ The current path, edit/, didn’t match any of these. but i can't get what's wrong with path: that's my urls.py: from django.urls import path from lab4 import views urlpatterns = [ path("", views.index), path("create/", views.create), path("edit/<int:id>/", views.edit), path("delete/<int:id>/", views.delete), ] Create works fine by the way, but what's the problem with edit and delete? -
Django Queryset not working after tranformation to Abstract class child
For more than a year, I construct many of my query using a Django Model where I have simple relation between none abstract model objects and everything was working perfectly : class Taxon(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='children') rank = models.CharField(max_length=200, unique=False, default="NA") name = models.CharField(max_length=200, unique=False, default="NA") class Sequence(models.Model): taxon = models.ForeignKey(Taxon, null=True, blank=True, on_delete=models.CASCADE) amplicon = models.CharField(max_length=1000, unique=False) sequence = models.CharField(max_length=1000, unique=False) score = models.FloatField() Exemple of queryset using my Model : taxon.sequence_set.filter(stuff_filtering) But recently I had to apply some modifications on my database and my Sequence objects are now derivated from an Abstract class called Observation, becoming this class Observation(models.Model): taxon = models.ForeignKey(Taxon, null=True, blank=True, on_delete=models.CASCADE) class Meta: abstract = True class Sequence(Observation): amplicon = models.CharField(max_length=1000, unique=False) sequence = models.CharField(max_length=1000, unique=False) score = models.FloatField() def __str__(self): return str((self.amplicon, self.sequence, self.score, self.taxon)) I didn't changed anything in my queryset because django documentation about abstract class (https://docs.djangoproject.com/en/3.2/topics/db/models/) say you can still use your chlid_set in a query. However i'm facing this error and I couldn't understand why. AttributeError: 'QuerySet' object has no attribute 'sequence_set' Knowing that in case of Abstract base classes, a table should be created in db for each child with parent attribute... So i … -
Serializing Array Field to String
I have an array field in my model i need to serialize and return the first 10 tags from the query getting error while serialising the data. referred - DRF serialize ArrayField as string serializers.py class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation(self, obj) # convert list to string return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") # convert string to list return super().to_internal_value(self, data) class TagsSearchSerializer(serializers.ModelSerializer): tags = StringArrayField() class Meta: model = Mymodel fields = ('id', 'tags') models.py class Mymodel(models.Model): tags = ArrayField(models.CharField(max_length=64, blank=True),default=list, blank=True) views.py class TagsSearchAPIView(APIView): """ Used on dropdown menus to dynamically fetch Tags data """ def get(self, request): queryset = Mymodel.objects.all() tags = queryset.order_by('tags')[:10] serialized_tags = TagsSearchSerializer(tags, many=True, context={'request': request}) results = serialized_tags.data return Response({'results': results}) error to_representation() takes 1 positional argument but 2 were given -
User passes test in django to check subscription
I have a django application where I need to check if a user has a valid subscription, otherwise it redirects the user to his/her dashboard. I was thinking to use the django decorator user_passes_test but I couldn't find a proper way to create the function to check the user. My models for user and subscription are: class CustomUser(AbstractUser): user_type_data = ( ('admin', 'admin'), ('school_admin', 'school_admin'), ('student', 'student'), ) user_type = models.CharField( max_length=20, choices=user_type_data, default='student') address = models.CharField(max_length=500, null=True, blank=True) city = models.CharField(max_length=200, null=True, blank=True) zip_code = models.CharField(max_length=100, null=True, blank=True) country = CountryField(null=True, blank=True) phone = models.CharField(max_length=200, null=True, blank=True) selected_course = models.ForeignKey(QuizTheoryCourse, on_delete=models.CASCADE, null=True, blank=True) class Subscription(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) issue_date = models.DateTimeField(null=True, blank=True) duration = models.IntegerField(choices=DURATION_CHOICES) expiration_date = models.DateTimeField() def __str__(self): return f'{self.user} - {str(self.expiration_date)}' def get_expiration(self): if self.expiration_date: if self.expiration_date > timezone.now(): expiration_date = self.expiration_date + timedelta(days=int(self.duration)) else: expiration_date = dt.now() + timedelta(days=int(self.duration)) else: expiration_date = dt.now() + timedelta(days=int(self.duration)) return expiration_date def is_subscription_valid(self): today = timezone.now() return today < self.expiration_date The function I am using to pass in the decorator is: def subscription_valid(user): try: superuser = user.is_superuser user_valid = user.subscription.is_subscription_valid return superuser or user_valid except user.DoesNotExist: return False My problem is that, anytime the user doesn't have any … -
ImportError: cannot import name 'fromshare' from 'socket'
im facing this error ImportError: cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.10/socket.py) File "/app/coreapp/forms.py", line 1, in <module>from socket import fromshare ` im facing this error ImportError: cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.10/socket.py) File "/app/coreapp/forms.py", line 1, in <module>from socket import fromshare` #i was trying to run Heroku run python manage.py migrate #my forms file : from django import forms from django.contrib.auth.models import User from coreapp.models import Restaurant from django.db import models class UserForm(forms.ModelForm): email = forms.CharField(max_length=100, required=True) password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ("username", "password", "first_name", "last_name", "email") class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = ("name", "phone", "address", "logo") ``` ` File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() … -
Value: "" must be an instance of <class 'dict'> in django, djongo
I am using Django and connecting with a mongodb database using djongo. My database requirements are such that I need to use an embedded field in one of the collections. On adding any entry on Django Admin I am getting a preview error - I have 2 models, City containing 3 fields, and the Address containing 2 fields a city object and a pincode. Hence the city is an embedded field in model Address. On adding this entry through django-admin an error message pops up, and the entry doesn't get saved in the database. Please correct the error below -> Value: gwalior-MP-India must be an instance of <class 'dict'> An entry in address table looks like - { "city": { "city":"gwalior", "state":"MP", "country":"India" }, "pincode":"9999" } P.S. - I was not able to attach the screenshot of django-admin panel, as I was getting an error while posting this question -> Failed to upload image; an error occurred on the server. Here are the code snippets and the versions of the installed packages. models.py class City(models.Model): _id = models.ObjectIdField() city = models.CharField(db_column='city', max_length=255, null=True, blank=True) state = models.CharField(db_column='state', max_length=255, null=True, blank=True) country = models.CharField(db_column='country', max_length=255, null=True, blank=True) def __str__(self): return self.city …