Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a javascript variable inside a Django {% url %} tag?
Im trying to dynamically change the link of a button based on which div a user has currently selected. I tried to run a quick test with a JS variable in the HTML script tag, but Django isn't reading the variable like a num. <script type="text/javascript"> const testing = 10 </script> <a href="{% url 'battlefield:onevsone_trainer_selection' num_trainers=testing %}" class='description__button btn btn__large'>Next ></a> URL looks like: path('one-vs-one/trainers/<int:num_trainers>', views.oneVsOne, name='onevsone_trainer_selection') Not sure exactly why it's not working. When I passed it a string of '10' it worked -
django-filter search filed not able to recognize and filter the None value
I'm using django-filter: filter.py: import django_filters TYPE_CHOICES = (('One', 'One'), ('Two', 'Two'),(None,None)) class MyFilterSet(django_filters.FilterSet): Type = django_filters.ChoiceFilter(choices=TYPE_CHOICES) class Meta: model = Mymodel fields = ['Type '] In the UI form select filed, when I choice the None ,and submit ,the system can't find the None value one. Nothing happen. I have tried convert the None to sting None ,but it still not work. Any friend can help ? -
How to perform additional functions from a class UpdateViews
to edit my table I use UpdateViews , and pass there the same template as in the creation function: class CampaignEditor(UpdateView): model = Campaigns template_name = 'mailsinfo/add_campaign.html' form_class = CampaignsForm def get_context_data(self, **kwards): context = super().get_context_data(**kwards) data = list(Emails.objects.values()) # you may want to further filter for update purposes data = MailsTableWithoutPass(data) userID = self.object.user_guid all_mails = CampaignEmail.objects.values_list ('id','campaigne_guid', 'email_guid') context['data'] = editCampaignDataWork(data, userID, all_mails) return context def add_campaign(request): if request.method == 'POST': addCampaignDataToDB(request.POST) data = list(Emails.objects.values()) data = MailsTableWithoutPass(data) form = CampaignsForm() data_ = { 'form': form, 'data': data } return render(request, 'mailsinfo/add_campaign.html', data_) Saving the main form is fine, but apart from that my create function has extra steps, for one more database, it's all done in a function - addCampaignDataToDB : def addCampaignDataToDB(req): formCampaigns = CampaignsForm(req) IDs = req['IDs'] if IDs != '': IDs_list = IDs.split(',') user_guid = req['user_guid'][0] for i in IDs_list: CampaignEmail.objects.create(email_guid=int(i), campaigne_guid=int(user_guid)) if formCampaigns.is_valid(): formCampaigns.save() I encountered a problem that when calling a class for edit from a function addCampaignDataToDB only a fragment is executed: if formCampaigns.is_valid(): formCampaigns.save() But I need this whole feature to work As a result, I get that part of the actions are not executed and it seriously breaks my … -
Non model field in Django ModelSerializer
class Form(models.Model): key = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) class Answer(models.Model): form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='answers') answer = models.TextField() class AnswerSerializer(serializers.ModelSerializer): form_key = serializers.UUIDField(write_only=True) class Meta: model = imported_models.Answer fields = ['id', "answer"] I want to create Answer based access on form_key. So i need to validate form_key as valid UUID key. How can i do that? -
Django. Filtering both related and relating model based on a field in relating one
I have two models: class Genre(models.Model): name=models.CharField() class Book(models.Model): name=models.CharField() genre=models.ForeignKey(Genre, related_name='book', on_delete=models.CASCADE) published=models.BooleanField() I also have basic serializers for them: class BookSerializer(serializers.ModelSerializer): class Meta: model=Book fields='__all__' class GenreSerializer(serializers.ModelSerializer): books = BookSerializer(source='book', many=True) class Meta: model=Genre fields='__all__' I need to query and serialize Genre models and related Book models excluding the books, which aren't published. I also don't need to query genres, which don't have published books. Example: g1=Genre(name='g1') #Serialize b1=Book(genre=g1, name='b1', published=False) #Don't serialize b2=Book(genre=g1, name='b2', published=True) #Don't serialize g2=Genre(name='g2') #Don't serialize, because there's no published books for this genre b3=Book(genre=g2, name='b3', published=False) #Don't serialize Desired result: [ { 'id': 1, 'name': 'g1', 'books': [ { 'id': 2, 'name': 'b2', 'published': true } ] } ] None of the filtering and excluding I tried worked. They all seem to affect only outer model (genre in this case) and I can't figure out how to filter underlying books first and then filter genres based on the result of book filtering. I found a workaround, but it involves multiple queries, creating new temporary genre and deleting it later, so this approach isn't really an option. -
upload_to and storage not working in Django 4.1
i have just upgrade my Django from 2.x to 4.x. I had a function that not working correctly. I have been trying so many things but still not able to figure it out. So i need some help file = models.FileField( upload_to=get_file_path, storage=AbsolutePathStorage(), max_length=500, ) from django.core.files.storage import FileSystemStorage class AbsolutePathStorage(FileSystemStorage): """Storage that allows storing files given absolute paths.""" def path(self, name: str) -> str: """Override path validation to allow absolute paths.""" # Return name if it's a absolute path. if name.startswith("/"): return name # Return regular joined path if this is a relative path. return super().path(name) So before upgrading Django, the file is uploaded to the upload_to folder ( outside of MEDIA_ROOT). Everything is working fine. But after i upgraded Django to 4.1. Its not working anymore and complaining about: The joined path (upload_to) is located outside of the base path component (MEDIA_ROOT ). Any idea ? Thank you. -
Django - unable to add a field in postgres?
I am trying to add a field to existing model. example: from django.db import models # from django.contrib.auth.models import User from test.settings import AUTH_USER_MODEL as User import random class BrModel(models.Model): bro = models.CharField(max_length=20) cl_id = models.CharField(max_length=20) br_pwdd = models.CharField(max_length=255) api_key = models.CharField(max_length=255) # country = models.CharField(choices=COUNTRY_CHOICES["COUNTRY_CHOICES"], max_length=3, blank=True, default="IND") api_sec = models.CharField(max_length=255) t_sec = models.CharField(max_length=255, blank=True, null=True) # The new field I am trying to add, This is a test field because it keeps failing test_field = models.CharField(max_length=10, default="T") created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey( User, related_name='bro', on_delete=models.CASCADE, null=True) I am constantly getting this error on elastic beanstalk postgres RDS: column bro_setting_brmodel.test_field does not exist LINE 1: ...ret", "bro_setting_brmodel"."t_sec", "bro_se... ^ at "t_sec" The field I want to add: def create_new_ref_number(): not_unique = True while not_unique: unique_ref = random.randint(1000, 65535) if not BrModel.objects.filter(test_field=unique_ref): not_unique = False return str(unique_ref) test_field = models.CharField(max_length=10, blank=True, editable=False, unique=True, default=create_new_ref_number) It works on local server which is using sqlite db. I am all out of ideas about why I the migration is not getting applied. -
Django Channels. How to "try-except" the error when the "Event loop is closed"?
I have a trigger that sends a message to the layer group. As it is a WebSocket, it works only on a webpage, but I have also an API point for that trigger because it also saves some object to DB. So I need to handle(pass) an error when the trigger act when Websocket is closed (i.e. web page is closed). So I think I need to "try except" that RuntimeError. But where to make it? What code include in try-except? I try to "try-except" the __init__ of Consumer Class, but to no avail. Pls, advise. -
django-filter AssertionError: Cannot filter a query once a slice has been taken
I'm using Django-filter ,I want to slice the rows ,just want the first 75 row: def hist_view_render(request): all_obj = RunStats.objects.all().order_by('-create_dttm')[:75] hist_filter = RunStatsFilter(request.GET, queryset=all_obj) paginator= Paginator(hist_filter.qs, 15) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) context = {'response': response,'filter': hist_filter} return render(request, 'runstat_hist.html',context) I have tried put the [:75] in different places ,but I always receive the error: Cannot filter a query once a slice has been taken The only way that works is slice it in the template ,but I want to find a way to slice it in the views.py. Any friend can help ? -
How can I paginate the attributes from a model?
I have a single for each series, but I want to paginate inside this page. I want to paginate the episodes because some series have more than 100 episodes and it is too much for a single page. class SerieDetailedView(DetailView): template_name = "tailwind/series_detail.html" model = Serie slug_url_kwarg = "serie_name" slug_field = "name" context_object_name = "project" def get_object(self, queryset=None): return Serie.objects.get(name=self.kwargs["serie_name"]) In this case, I have this as my model: class Serie(models.Model): name = models.CharField(max_length=150, unique=True) finished = models.BooleanField(default=False) episodes = ArrayField(base_field=models.CharField(max_length=100), default=list) published_at = models.DateTimeField(auto_now_add=True) I’m just getting how to paginate all the series, but it’s different, I want to paginate a thing that is inside the series. I’ve tried to do it, but it has not worked because is a single page: class SerieDetailedView(DetailView): template_name = "tailwind/series_detail.html" model = Serie slug_url_kwarg = "serie_name" slug_field = "name" context_object_name = "project" paginate_by = 10 def get_object(self, queryset=None): return Serie.objects.get(name=self.kwargs["serie_name"]).episodes.order_by('-published_at') -
association user with forms
I'm making something like this: admin creates form manually, and user is automatically created with this form. But I need to add association that form to a new automatically created user, that's where I'm stuck. How can I make user auto registration to associate that form I need this because I want to then to show 'filtered, created' form by user. Views.py def create_driver_view(request): if request.method == "POST": add_driver = DriverForm(request.POST) add_driver_files = request.FILES.getlist("file") if add_driver.is_valid(): email = request.POST['email'] usern = 'test' passw = 'test' user = User.objects.create_user(email = email, username = usern, password = passw) user.save() f = add_driver.save(commit=False) f.user = request.user f.save() for i in add_driver_files: DriversFiles.objects.create(driver_files=f, file=i) return redirect('drivers:list_driver') else: print(add_driver.errors) else: add_driver = DriverForm() add_driver_files = DriverFormUpload() return render(request, "drivers/add.html", {"add_driver": add_driver, "add_driver_files": add_driver_files}) Forms.py class DriverForm(forms.ModelForm): class Meta: model = Drivers fields = [ 'full_name', 'phone_number', 'email', 'address', 'country', 'state', 'city', 'zip', 'birth_date', 'license_no', 'license_exp_date', 'last_medical', 'next_medical', 'last_drug_test', 'next_drug_test', 'status', ] class DriverFormUpload(forms.ModelForm): class Meta: model = DriversFiles fields = [ 'file', ] widget = { 'file': forms.ClearableFileInput(attrs={'multiple': True}), } Models.py STATUS = ((0, 'Inactive'), (1, 'Active')) class Drivers(models.Model): full_name = models.CharField(max_length=50, default=None) phone_number = models.CharField(max_length=50, default=None) email = models.EmailField(unique=True,max_length=255, default=None) address = models.CharField(max_length=70, default=None) … -
Сreate a folder for user files when creating a user FastAPI?
How can I create a directory for user files when creating a user? I want to store files from a client in that client's directory the code executes without errors, but the directory does not creating in the specified directory... i have this, but it doesn't work def create_user(db: Session, request: UserBase): new_user = DbUser( # id create automaticly first_name = request.first_name, last_name = request.last_name, email = request.email, password = Hash.bcrypt(request.password) ) db.add(new_user) db.commit() db.refresh(new_user) path = f"/users_files/user_id_{new_user.id}/orders" try: pathlib.Path(path).mkdir(parents=True, exist_ok=True) except OSError: print("Create folder %s error" % path) else: print ("Folder create %s " % path) return new_user when i specify the path = f"../users_files/user_id_{new_user.id}/orders" the dedirectory is created but one level higher. -
How to ensure that the timezone is entered in the ISO UTC format within the request body?
I am using pydantic within FastAPI and I need to ensure that the timestamp is always entered in the UTC ISO format such as 2015-09-01T16:09:00:000Z. from typing import Optional from fastapi import FastAPI from pydantic import BaseModel, Field from datetime import datetime app = FastAPI() measurements = [ { "timestamp": "2015-09-01T16:09:00:000Z", "temperature": 27.1, "dewPoint": 16.7, "percipitation": 0 }, { "timestamp": "2016-09-01T16:09:00:000Z", "temperature": 21.3, "dewPoint": 12.3, "percipitation": 1.5 } ] class MeasurementIn(BaseModel): timestamp: datetime temperature: Optional[float] dewPoint: Optional[float] percipitation: Optional[float] @app.post("/measurements") async def create_measurement(m: MeasurementIn, response: Response): measurements.append(m) The above code is working but it is also accepting datetime in other formats. I want to strictly restrict it to UTC ISO Format. I have tried to change the timestamp to timestamp: datetime.utcnow().isoformat() but it is not working. -
how can i connect my google sql postgres to my django application?
I have create my google postgres instance on cloud sql service, and i couldn't connect it with my django application, in the link below they give sqlalchemy configuration, but nothing about the database host [cloud.google](https://cloud.google.com/sql/docs/postgres/connect-admin-proxy#debianubuntu ) This is my database credentials # GCP DATABASE CREDENTIALS DB_NAME=db_name DB_HOST= *** DB_PORT=5432 DB_USER=db_user DB_PASSWORD=password Not sure about the DB_HOST, i tried the public ip address of my db and it not working i got this error This is my Django settings : DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ.get("DB_NAME"), "USER": os.environ.get("DB_USER"), "PASSWORD": os.environ.get("DB_PASSWORD"), "HOST": os.environ.get("DB_HOST"), "PORT": os.environ.get("DB_PORT") # default postgres port } } -
How I can create fields into a model in dependence of another one?
I'm learning Django and I'm working in a test project. So in my models.py I have this (I know that is wrong but I don't know how to do that): from django.db import models class Diagram(models.Model): name = models.CharField(max_length=100) img = models.ImageField(upload_to='img/diagrams/', help_text="Size required: height = 1050px, width = 1506px.", max_length=None) def __str__(self): return self.name class DiagramReferences(Diagram): quantity_of_references = models.IntegerField() for i in range(quantity_of_references): title = models.CharField(max_length=50) coords = models.CharField(max_length=50) So I want to make a relation between both models, the first: Diagram contains the name of the Diagram and the respective image. In the other I want to select the first which was already created and assign him how many references it has and create a field for each reference. -
How to fix heroku h10 error for my deployed app
This is the error my heroku logs show anytime I run my app 2022-11-09T16:52:49.620009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-11-09T16:52:49.620009+00:00 app[web.1]: mod = importlib.import_module(module) 2022-11-09T16:52:49.620009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module 2022-11-09T16:52:49.620010+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 1030, in _gcd_import 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 1007, in _find_and_load 2022-11-09T16:52:49.620010+00:00 app[web.1]: File "", line 984, in _find_and_load_unlocked 2022-11-09T16:52:49.620011+00:00 app[web.1]: ModuleNotFoundError: No module named 'dlcfogbomoso.wsgi' 2022-11-09T16:52:49.620081+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-11-09T16:52:49.644507+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [10] [INFO] Booting worker with pid: 10 2022-11-09T16:52:49.647154+00:00 app[web.1]: [2022-11-09 16:52:49 +0000] [10] [ERROR] Exception in worker process 2022-11-09T16:52:49.647155+00:00 app[web.1]: Traceback (most recent call last): 2022-11-09T16:52:49.647156+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-11-09T16:52:49.647156+00:00 app[web.1]: worker.init_process() 2022-11-09T16:52:49.647156+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-11-09T16:52:49.647156+00:00 app[web.1]: self.load_wsgi() 2022-11-09T16:52:49.647157+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-11-09T16:52:49.647157+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-11-09T16:52:49.647157+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-11-09T16:52:49.647157+00:00 app[web.1]: self.callable = self.load() 2022-11-09T16:52:49.647158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-11-09T16:52:49.647158+00:00 app[web.1]: return self.load_wsgiapp() 2022-11-09T16:52:49.647158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-11-09T16:52:49.647158+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-11-09T16:52:49.647159+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-11-09T16:52:49.647159+00:00 app[web.1]: mod = importlib.import_module(module) 2022-11-09T16:52:49.647159+00:00 app[web.1]: File … -
create a django serializer to create three model instance at once
{ "product_name": "CRVRVgfhghg", "product_price": "0.01", "product_location": "KIKUYU,KENYA", "product_description": "VFVFVFVFVFVF", "product_category_name": "livestock", "product_farmer_name": "james", "product_category_data": { "product_category_name": "livestock", "product_category_description": "livestock one" }, "product_product_file_data": { "product_file_name": "ok" } } i have three tables: product_category,product and product_product_files...what i want is to populate all the three tables at once using one view and url pattern... is there a way i can do this using serializers?? -
How can I refactor my code to clear off - "local variable 'data' referenced before assignment"
My code returns is intended to return queryset based on selected dates or months however these two are almost similar yet only one works. Here is my both forms.py class DateInput(forms.DateInput): input_type = 'date' class MonthInput(forms.DateTimeInput): input_type = 'month' class DateRangeInputForm(forms.Form): start = forms.DateField(widget=DateInput()) end = forms.DateField(widget=DateInput()) class MonthRangeInputForm(forms.Form): start = forms.DateField(widget=MonthInput()) end = forms.DateField(widget=MonthInput()) This is the query view that works. def milk_records_range_per_day(self, request): if request.method == "POST": form = forms.DateRangeInputForm(request.POST) if form.is_valid(): data = (models.Milk.objects.filter(milking_date__date__range=( form.cleaned_data['start'], form.cleaned_data['end'])) .annotate(date=functions.TruncDate("milking_date")) .values("date") .annotate(amt=Sum('amount_in_kgs'))) labels = [c['date'].strftime("%d-%m-%Y") for c in data] values = [x['amt'] for x in data] ....... Though this one throws a reference error : local variable 'data' referenced before assignment def milk_records_range_per_month(self, request): if request.method == "POST": form = forms.MonthRangeInputForm(request.POST) if form.is_valid(): data = (models.Milk.objects.filter(milking_date__month__range=( form.cleaned_data['start'],form.cleaned_data['end'])) .annotate(month=functions.TruncMonth("milking_date")) .values("month") .annotate(amt=Sum('amount_in_kgs'))) labels = [c['month'].strftime("%m-%Y") for c in data] values = [x['amt'] for x in data] ..... Model: class Milk(models.Model): amount_in_kgs = models.PositiveIntegerField(validators=[MinValueValidator(0), MaxValueValidator(50)]) milking_date = models.DateTimeField(auto_now_add=True) ... -
APIView PUT request being handled as a GET request
I'm building an APIView to handle a PUT request for a model with choicefields as input. Originally, I created a GET and PUT definition for my APIView class, however when my build is deployed, my PUT request is being received as a GET request! On my dev deployment, the request is received as a PUT request every time. When I move it to a production deployment however, the only times I can get the request to properly send a PUT request is by using Postman. When I try any other way the request is received as a GET request. Removing the definition of GET from my APIView does not help, it simply returns a 405 method not allowed. I've looked around and don't seem to see any other people with this issue. What could cause a request to be misinterpreted like this? Where would be a good place to start looking? Can I force the use of PUT at this endpoint? In the meantime I'm going to try moving from APIView to one of the specific generics mixins to see if this resolves my issue. -
How to allow boolean True on just one model in table in Django?
I've got a model where I would like there to be able to have one set as the 'app default'. In this model I added a field named is_app_default in order to help accommodate this. class TreeLevel(models.Model): id = models.BigAutoField(primary_key=True) short_description = models.CharField(max_length=200) long_description = models.TextField() is_app_default = models.BooleanField(default=False) class Meta: verbose_name = "Tree Level" verbose_name_plural = "Tree Levels" class Layer(models.Model): id = models.BigAutoField(primary_key=True) tree_levels = models.ManyToManyField(TreeLevel) description = models.TextField() class Meta: verbose_name = "Layer" verbose_name_plural = "Layers" The Layer model links to TreeLevel with an m2m. Ultimately I would like the is_app_default TreeLevel automatically added to every Layer m2m relationship - which is why there can only be one TreeLevel with is_app_default set as True. My potential solution(s): Users with admin may be creating new TreeLevel objects - so I need to make sure they aren't setting that Boolean in any new models. I think I can override the save() method on TreeLevel to check the DB to see if another with that boolean as True exists - if so? Don't save the 'new' one and return an error. But I think this hits the database - causing unnecessary queries potentially? Then additionally, I would also need to override … -
how to define the environment variable DJANGO_SETTINGS_MODULE?
I am trying to chainedForeignKey using https://django-smart selects.readthedocs.io/en/latest/installation.htmland i got following error : ` django.core.exceptions.ImproperlyConfigured: Requested setting USE_DJANGO_JQUERY, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. ` your text``from django.db import models your textfrom smart_selects.db_fields import ChainedForeignKey Create your models here. your textclass City(models.Model): your textname = models.CharField(max_length = 25, null = True) your textclass Area(models.Model): your textname = models.CharField(max_length = 25, null = True) your textcity = models.ForeignKey(City, on_delete = models.CASCADE) your textclass Store(models.Model): your textstore = models.CharField(max_length = 50) your textcity = models.ForeignKey(City, on_delete = models.CASCADE) your textarea = ChainedForeignKey(Area, chained_field='city', chained_model_field= 'city') -
select instances in manaytomany field using django rest
I'm trying to build a friend add system using Django Rest And these are my codes #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) pic = models.ImageField(upload_to="img", blank=True, null=True) friends = models.ManyToManyField('Friend', related_name = "my_friends" , blank=True , null=True) def __str__(self): return self.user.username class Friend(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE) def __str__(self): return self.profile.user.username #serializers.py class FriendSerializer(serializers.ModelSerializer): class Meta: model = Friend fields = ('profile',) class ProfileSerializer(serializers.ModelSerializer): friend = FriendSerializer(many=True, read_only=False) class Meta: model = Profile depth = 3 #this is return foreinkey name instead of id fields = "__all__" def update(self, instance, validated_data): friends_data = validated_data.pop('friend') instance = super(ProfileSerializer, self).update(instance, validated_data) for friend_data in friends_data: friend_qs = Friend.objects.filter(profile = friend_data['profile']) if friend_qs.exists(): friend = friend_qs.first() else: friend = Friend.objects.create(**friend_data) instance.friend.add(friend) return instance #views.py class UserProfile(RetrieveUpdateDestroyAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class UserFriends(RetrieveUpdateDestroyAPIView): queryset = Friend.objects.all() serializer_class = FriendSerializer #urls.py urlpatterns = [ path('' , ArticleList.as_view() , name = 'list'), #we used as_view() cause we used class based views path('<int:pk>' , ArticleDetail.as_view() , name = 'detail'), path('users/' , UserList.as_view() , name = 'user-list'), path('users/<int:pk>' , UserDetail.as_view() , name = 'user-detail'), path('profile/<int:pk>' , UserProfile.as_view() , name = 'user-profile'), ] My intention is to send a json like this -> … -
How to filter queryset from inside the serializer?
I want to always apply a filter to a serializer (filter the queryset). lets say I have: class Company(models.Model): name = models.CharField(max_length=90, unique=True) city = models.CharField(max_length=90,) active = models.BooleanField(default=True) class CompanySerializer(serializers.ModelSerializer): class Meta: model=Company fields=['id', 'name', 'city'] so when I call the serializer for a list filtered by city (or any other fields added in my real code) as shown below it returns Companies from that city and only "active=True" query_set = Company.objects.filter(city=request.POST(city) ) srl = serializers.CompanySerializer(query_set, many=True) return Response(srl.data) because I may want to call the serializer from other parts of the code. and I want to keep the records for reference but never show to any client. I have tryed to modify the queryset from from init but it does not work. I actually print() the modified queryset to make sure it was filtered and it prints the filtered queryset, I do: def __init__(self, instance=None, data=empty, **kwargs): instance.filter(active=False) self.instance = instance print(self.instace) #this prints the filtered queryset OK but it sends the response without the "active=False" filter. -
SEO in django template project
I'm new in django, I'm working on a djanog project and i want to render dynamic meta tags foe SEO and titles for every page in it, but i don't know how can it can help please I want it to be something like this: <title>Veb-studiya bilan aloqa - Eson</title> <meta name="description" content="Veb-studiya Eson - bu professional veb-studiya. Biz o&#039;z ishimizni sevamiz va sizning internet tarmog&#039;idagi biznesingizni rivojlantiriramiz. " /> <meta name="robots" content="index, follow" /> <meta name="googlebot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" /> <meta name="bingbot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" /> <link rel="canonical" href="https://eson.uz/aloqalar/" /> <meta property="og:locale" content="uz_UZ" /> <meta property="og:locale:alternate" content="ru_RU" /> <meta property="og:type" content="article" /> <meta property="og:title" content="Veb-studiya bilan aloqa - Eson" /> <meta property="og:description" content="Veb-studiya Eson - bu professional veb-studiya. Biz o&#039;z ishimizni sevamiz va sizning internet tarmog&#039;idagi biznesingizni rivojlantiriramiz. " /> <meta property="og:url" content="https://eson.uz/aloqalar/" /> <meta property="og:site_name" content="Eson" /> <meta property="article:publisher" content="https://www.facebook.com/netsonuz" /> <meta property="article:modified_time" content="2022-01-10T07:20:26+00:00" /> <meta name="twitter:card" content="summary_large_image" /> <script type="application/ld+json" class="yoast-schema-graph">{"@context":"https://schema.org", -
Python: Basic OCR / Image to Text library
I have a very simple use case for OCR. .PNG Image then extract the text from the image. Then print to console. I'm after a lite weight library. I am trying to avoid any system level dependency's. Pytesseract is great, but deployment is a bit annoying for such a simple use case. I have tried quite a few of them. They seem to be designed for more complex use cases. Note: White text is not necessarily suitable for OCR. I will change the image format to suit the OCR Library.