Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement Django-private-chat2?
Has anyone used Django-private-chat2? I am struggling to find a tutorial on this as no documentation is available. Please tell how to implement it? -
I am new to python and This is the TypeError:'<=' not supported between instances of 'datetime.datetime' and 'module'
import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("Date published!!!") def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now -
how to make text stay after the search has been made
I have a serch field on my page <form method="GET" class="container mb-5"> <input type="search" class="form-control rounded" placeholder="Write a name" aria-label="Search" aria-describedby="search-addon" name="search"/> <button type="submit" class="btn btn-outline-primary px-5" >Search</button> </form> And here is my views def my_view(request): value_one = request.GET.get("search", None) objects = MyModel.objects.all() if value_one: objects = objects.filter(field_one=value_one) After I input something in a search field and push the button 'search', text which was in search field dissapears, I want it to stay until the next input. Is it possible to do with Django or not? Don't even know how to google it, everything I found was on different topic -
How to automatically update a page without refreshing in django?
I am creating a website using Django on the stock market. I am fetching the live stock market data from an API. I want to update the live price of a stock every 5 seconds (which is given by the API). How can I do this without refreshing the page? I found that Ajax is very helpful for this but I am not being able to implement this properly. Thus, can someone please give an example of the code which is required in the html page to update the values using Ajax. I was thinking of using a separate URL which could send the data in a JSON format. Please help me out if possible. -
Post request Manytomany field DRF with postman
Objective: Creating a new entry in database from Postman using the "POST". I am trying to send the data from Postman and I am using nested serializing. I have changed the create method i have shared the snippet below. Also, I tried this solution but it did not work. Can someone please point out the mistake I am making? When I am trying to post as form-data the error is {"magazine":["This field is required."]}. When I am trying to post it as raw data the error is Direct assignment to the forward side of a many-to-many set is prohibited. Use magazine.set() instead. Here is my models: class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey('authors.Author', on_delete=models.CASCADE) magazine = models.ManyToManyField('articles.Magazine') def __str__(self): return self.title class Magazine(models.Model): name = models.CharField(max_length=30) title = models.CharField(max_length=100) def __str__(self): return self.name This is my serializers: class MagazineSerializer(serializers.ModelSerializer): class Meta: model = Magazine fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = AuthorSerializer(read_only=True, many=False) magazine = MagazineSerializer(many=True) class Meta: model = Article fields = [ 'title', 'content', 'author', 'magazine', ] def create(self, validated_data): allmags = [] magazine = validated_data.pop('magazine') for i in magazine: if Magazine.objects.get(id=magazine["id"]).exists(): mags = Magazine.objects.get(id=magazine["id"]) allmags.append(mags) else: return Response({"Error": "No such magazine exists"}, status=status.HTTP_400_BAD_REQUEST) … -
How to automatically fill pre-existing database entries with a UUID in Django
I have added a UUID to the following model: class Post(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) ... But there already are entries in the database that were created without the uuid field. When I run migrate, it adds the same UUID to all my previous objects. Is there an easy way of populating the existing objects with a different UUID automatically? -
why my server terminal doesnt show error?
I am connected to my VPS (Ubuntu) via SSH. I use Django, where I process 1000's of images via Django-imagekit ( PIL ). but for some reason, it is not generating an error it just stops/terminates there. it shows all other print commands and everything. yes, I tried 'try and except' but it doesn't work, it just terminates at 'try' only. anyone any idea? -
AttributeError while accessing serializer.data in DRF serializer
This is my model and BaseManager: class CustomUserMangager(BaseUserManager): def create_user(self,email,password,**extra_fields): if not email: raise ValueError(_("Email is required")) email = self.normalize_email(email) user = self.model( email = email, **extra_fields ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(_("Email address"), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserMangager() def __str__(self) -> str: return self.email and this is my Serializer: class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id','email','is_active') In Python mange.py shell: I try to use this: user = CustomUser.objects.get_or_create(email="a@gmail.com",password="1") >>> user (<CustomUser: a@gmail.com>, True) >>> user_serializer = CustomUserSerializer(user) >>> user_serializer.data and get this error: AttributeError: Got AttributeError when attempting to get a value for field email on serializer CustomUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the tuple instance. Original exception text was: 'tuple' object has no attribute 'email' I dont know wwhat is the problem here :(( -
Uncaught ReferenceError: localstorage is not defined at (index):1228
when I tried to create a cart using javascript in local storage using django, it is showing me this error into the chrome console section.. what should I do now..? what is the proper code to not to get any kind of error like that. -
How to filter a comma separated string in Django Rest Framework?
I have some data that is similar to this: position: "1B, 2B, 3B, SS" I'd like to be able to run a query such as /players/?position=1B, however, this currently does not return anything because the items are separated by a comma. Here is stripped down version of the views.py: class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter): pass class PlayerProfileFilter(django_filters.FilterSet): position = CharInFilter(field_name='display_position', lookup_expr='in') Is there a way to filter the data in this way? -
how to do Django nested comment branching like linkedin social media website
how to make step by wise nested comment branching for social media website. like linked in comment section working. how to create a comment branching in the social media website .im trying too much no response in the social media website -
Audios files served by django not working properly
If I go to this link http://127.0.0.1:8000/media/some_file.mp3 Play and Pause works properly. But not able to change currentTime. see gif here. Django 3.0.10 and python 3.6 models.py class Audios(models.Model): name = models.CharField(max_length=50, null=True) audio = models.FileField(upload_to='', null=True) def __self__(self): return self.name views.py def index(request): obj = Audios.objects.all() return render(request, 'index.html', {'audios': obj}) index.html {% for i in audios %} <audio controls> <source src="{{i.audio.url}}"> </audio> {% endfor %} settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns += [ re_path(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), ] -
updating PostgreSQL database index in Django
I have added the following to my model in order to activate indexing for my data in database: class Meta: indexes = [ models.Index(fields=['symbol', 'interval', '-date_time']), ] when migrating, it takes a while to index, which is fine. My question is that when adding new data, how should I update the index again? would it get indexed automatically or I need to run something? Thanks -
Client() got an unexpected keyword argument 'domain_url'
I start using Django multi-tenancy schemas: https://django-tenant-schemas.readthedocs.io/en/latest/use.html I followed the documentation but I'm getting an error I can't create a new tenant : this is my code : from customer.models import Client def create(self, request): formSerializer = self.serializer_class(data = request.data) if formSerializer.is_valid(): ## tenant = Client(domain_url='my-domain.com', schema_name='tenant1', name='Fonzy Tenant', paid_until='2014-12-05', on_trial=True) tenant.save() This is the client as described in the documentation from django.db import models from django_tenants.models import TenantMixin, DomainMixin class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField() on_trial = models.BooleanField() created_on = models.DateField(auto_now_add=True) # default true, schema will be automatically created and synced when it is saved auto_create_schema = True class Domain(DomainMixin): pass Error Message ; Client() got an unexpected keyword argument 'domain_url' -
After adding bootstrap to datatables colvis dropdown stopped working
i am working on a django project where i am using datatables, and i am trying to beautify it by using bootstrap. It works as expected colvis dropdowns show the columns without a problem but when i add bootstrap i can't see the columns to filter in dropdowns there is no explanation or errors on the console. I wonder if anyone had the same problem before and how did you solve it? Thanks Colvis dropdown image -
How to store and authenticate different user types in Django?
There are two different types of users, A & B. Users of type A authenticate using username and password while type B have email and password. The project uses token based authentication. The question is: how to manage both user types simultaneously? The approaches I have considered: Separate models for both user types and implement a custom auth backend to authenticate user signing in using email Single user model to cater for both user types. However, this would mean I have to an add additional field (email) and populate some random value for users of type A Apart from this, I have to store some custom information for logged in users like device type, location etc. Is it possible to override authtoken_token table to store this info or I have to create a separate model for that? -
ID parameter in Django REST API URL
I have two models: Article Comment Comments are connected to Article with ForeingKey. I want to create an endpoint like: {GET} /article/97/comments # get all comments of article (id:97) {POST} /article/97/comments # create an comment for article (id=97) But I want to use GenericViewSet or ModelMixins. Can you guide me, how can I do so? Thanks. -
Got Key Error on Django Serializer when combining 2 models
Good day SO. I want to combine two models in one django serializer. I just want to first get them inside one serializer and I can do the rest. Based on other SO question, I need to first declare a serializer and add it to my 2nd serializer. But it is giving me an error. I thought I just need to use the word major and declare it to my minor fields. class PrefectureMajorSerializer(serializers.ModelSerializer): id = serializers.IntegerField() text = serializers.CharField(source='prefecture_name') class Meta: model = PrefectureMajor fields = ["id", "text"] class PrefectureSerializer(serializers.ModelSerializer): id = serializers.IntegerField() text = serializers.CharField(source='prefecture_name') major = PrefectureMajorSerializer() class Meta: model = PrefectureMinor fields = ['id', 'text', 'prefecture_major_id', 'major'] Models: class PrefectureMajor(models.Model): prefecture_name = models.CharField(max_length=100, default='', null=False) is_active = models.BooleanField(default=True, null=False) def __str__(self): return self.prefecture_name class PrefectureMinor(models.Model): prefecture_major = models.ForeignKey("PrefectureMajor", related_name="PrefectureMinor.prefecture_name +", on_delete=models.CASCADE) prefecture_name = models.CharField(max_length=100, default='', null=False) is_active = models.BooleanField(default=True, null=False) def __str__(self): return self.prefecture_name -
Why does Django update other apps/databases while migrating?
I would just like to understand something about Django migrations. I have a project with several apps and most of them have their own database. Now, let's say I add one field to the app App_A in the models.py and run makemigrations App_A. Then this runs smoothly and tells me that there is just one field to be added. But when I run migrate --database=the_db_of_app_a it lists lots of migrations of other apps, but there I haven't change anything lately. So, I would like to know, why it does not only list the migrations of App_A. Best regards -
Get the database of the Django web application deployed on Heroku
I have deploy a Django web application on Heroku. How can I get the database link to that web application which is deployed on Heroku? Once I get that database, then how can I link that database to my new Django project? Basically, I want to do this because we need to change the URL of the web application deployed on Heroku. If there is any other way via which we can do then please let me do. Thanks in advance. -
Django: Get previous values of a multi-step form to dynamically display the fields of the next step
I am making a project in Django but Im not using Django built-in forms. Rather, I am using html and bootstrap to render forms. On a page, I want to create a quiz. I am doing this via a multi-step form where I input the number of questions on the first form. Then based upon this field, when I hit next, I want to have the same number of the fields for questions and corresponding answers to appear so that I can set them. For example, if I type 5 questions and hit next, it should have 5 fields for me to enter the questions and each question field should have 4 answer fields. Is there a way to dynamically do this? Please help :(((( This is very important. Thank you n here is my code snippet {% block content %} <div class="row"> <h2 style="color: darkblue;" class="text-center">Add a Quiz</h2> </div> <form action="" id="add_test_form" method="POST"> <!--This form will contain the quiz information--> {% csrf_token %} <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Name of test</label> <input type="text" class="form-control" name="test_name" required> </div> </div> </div> <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Number of questions</label> <input type="number" class="form-control" name="test_num_questions" min="1" oninput="validity.valid||(value='')" required> </div> … -
my program doen"t enter the try portion? I have write program for login but that doesn't work
def signin(request): if request.method=="POST": try: userdetails = employees.objects.get(username = request.POST.get('username'),password = request.POST.get('password')) print("username" , userdetails) request. Session['username'] = userdetails.username return render(request,'pimapp/main.html') except employees.DoesNotExist as e : messages. Success(request, 'username/password is invalid..!') return render(request,'pimapp/home.html') -
django: log raw sql and als othe output
In django to see the logging of raw sql we can use 'loggers': { 'django.db.backends': { 'handlers': ['sql'], 'level': 'DEBUG', 'propagate': False, }, in the settings file Is there any chance we can see the output of these raw sqls, i.e the data being fetched etc -
How to extract text from images and populate them into output fields using tesseract-ocr in django project?
I am developing an application to detect text from images(when user upload images), and then populate those extracted text into output fields. I have completed the text extraction part using tesseract-ocr (This part is working). But I'm stuck with populating those extracted text into output fields. Here's my code for text extraction: utils.py Here's my utils.py file where I have written the text extraction code. This is working. I need ideas to populate these extracted result into output fields. (It is better if I can do it without saving extracted data into database. I need to save into database only after validating the extracted data by the user.) import pytesseract pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe' def get_filtered_image(image, action): img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if action == 'NO_FILTER': filtered = img elif action == 'COLORIZED': filtered = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) elif action == 'GRAYSCALE': filtered = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) elif action == 'BLURRED': width, height = img.shape[:2] if width > 500: k = (50,50) elif width > 200 and width <= 500: k = (25,25) else: k = (10,10) blur = cv2.blur(img, k) filtered = cv2.cvtColor(blur, cv2.COLOR_BGR2RGB) elif action == 'BINARY': gray = filtered = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, filtered = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY) elif … -
How to get the name of the user with their id in follower and following system in Django rest framework?
I want to create a follower and following system, and I created but I want to add username along with their following_user_id or user_id. How can I do this? models.py from django.db import models from django.contrib.auth.models import User from django.http import JsonResponse ## Create your models here. class UserFollowing(models.Model): user_id = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user_id = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: unique_together = (('user_id', 'following_user_id'),) index_together = (('user_id', 'following_user_id'),) ordering = ["-created"] def __str__(self): f"{self.user_id} follows {self.following_user_id}" serializers.py/UserSerializers class UserSerializer(serializers.ModelSerializer): following = serializers.SerializerMethodField() followers = serializers.SerializerMethodField() # for validate user email def validate_email(self, value): lower_email = value.lower() if User.objects.filter(email=lower_email).exists(): raise serializers.ValidationError("Email already exists") return lower_email class Meta: model = User fields = ['id', 'first_name', 'username', 'last_name', 'email', 'password', 'date_joined','following','followers'] # extra_kwargs for validation on some fields. extra_kwargs = {'password': {'write_only': True, 'required': True}, 'first_name': {'required': True}, 'last_name': {'required': True}, 'email': {'required': True} } def get_following(self, obj): return FollowingSerializer(obj.following.all(), many=True).data def get_followers(self, obj): return FollowersSerializer(obj.followers.all(), many=True).data def create(self, validated_data): user = User.objects.create_user(**validated_data) # create user Token.objects.create(user=user) # create token for particular user return user FollowingSerializer and FollowerSerializes class FollowingSerializer(serializers.ModelSerializer): class Meta: model = UserFollowing fields = ("id", "following_user_id", "created") class FollowersSerializer(serializers.ModelSerializer): class Meta: model = UserFollowing fields …