Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
os.getcwd() raise Exception with django dev server
I have a django project running inside docker, and the service is up with the command of python manage.py runserver, with file autoreload open, and using threadings. My code invokes shutil.make_archive() which will then invoke os.getcwd(), and from time to time, os.getcwd() will raise FileNotFoundError, by searching more information, now I realized that the error might be caused by the path is no more there because the path is deleted by somewhere else after I enter the path. The error only raised sometimes and I couldn't find a stable way to reproduce it, once it happens, I can fix the problem by making any code changes to trigger file autoreload or restart the docker service, looks like make sure the process restarts will do the help, otherwise the error keeps raising. When things going properly, os.getcwd() will return my django project root dir path. And I'm 100% sure my code does nothing related with dir manipulation like os.chdir(). So in a nutshell, the django server works fine, suddenly os.getcwd() starts to raise error until I restart the process. My question is, what could be the root cause? is it possible that python manage.py runserver might cause any issue? Python: v3.8.6 … -
Using and supplying binaries for Yuglify or other filters with Django Compressor?
We've got Django-Compressor working nicely with compressor.filters.jsmin.rJSMinFilter which is installed by default and given by the default setting COMPRESS_FILTERS = {'css': ['compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.rCSSMinFilter'], 'js': ['compressor.filters.jsmin.rJSMinFilter']}, and we want to add compressor.filters.yuglify.YUglifyJSFilter to this, but unlike rJSMinFilter it isn't installed by default, and we don't know how to supply COMPRESS_YUGLIFY_BINARY. If we go to Yuglify's GH page we see the repo but don't know what file(s) to use or where to place them within our Django project. The examples show how npm install yuglify, but we don't know what npm is or how to use it. Probably a really stupid question but how can we supply it? We need this done in a way that we don't have to individually install things on different machines. Is it possible to include the Yuglify file(s) somewhere in our Django project, so things work as nicely as they did with rJSMinFilter, which was installed by default? -
I need to Delete any object from my DRF / django connected database through angular 13
I am getting the id which i have to delete but the last line of service.ts that is of delete method is not getting executed... the files and code snippets I used are : - COMPONENT.HTML <li *ngFor="let source of sources$ | async | filter: filterTerm"> <div class="card"> <div class="card-body"> <h5 class="card-title">{{source.name}}</h5> <p>URL:- <a href ='{{source.url}}'>{{source.url}}</a></p> <a class="btn btn-primary" href='fetch/{{source.id}}' role="button">fetch</a> <button class="btn btn-primary" (click)="deleteSource(source.id)">delete </button> <br> </div> </div> </li> I tried to console the id geeting from html and the Id i am getting is correct. //component.ts export class SourcesComponent implements OnInit { filterTerm!: string; sources$ !: Observable<sources[]>; // deletedSource !: sources; constructor(private sourcesService: SourcesService) { } // prepareDeleteSource(deleteSource: sources){ // this.deletedSource = deleteSource; // } ngOnInit(): void { this.Source(); } Source(){ this.sources$ = this.sourcesService.Sources() } deleteSource(id : string){ console.log(id) this.sourcesService.deleteSource(id); } //service.ts export class SourcesService { API_URL = 'http://127.0.0.1:8000/sourceapi'; constructor(private http: HttpClient) { } // let csrf = this._cookieService.get("csrftoken"); // if (typeof(csrf) === 'undefined') { // csrf = ''; // } /** GET sources from the server */ Sources() : Observable<sources[]> { return this.http.get<sources[]>(this.API_URL,); } /** POST: add a new source to the server */ addSource(source : sources[]): Observable<sources[]>{ return this.http.post<sources[]> (this.API_URL, source); //console.log(user); } deleteSource(id: string): Observable<number>{ … -
Faceting with Django Rest Framwork / Django Filter
Dear fellow overflowers, I’m currently building an API based on Django Rest Framework with Django Filter. Search, filtering and sorting works reasonably well, though I was wondering about filter facets. Imagine there’s a “Person” model and you’d like to allow users to filter by the first letter peoples’ names. You don’t want users to run into a “no results” situation, so you only want to suggest the letters that match at least one person. What is a good way to provide a list of choices (the facets) for each filter? Does it make sense to use a different endpoint that provides choices only? To me, it would feel right to declare facets inside the FilterSet subclass, because it’s the place where anything filter-related happens. Looking forward to your comments! Julian PS: Typically, I use ElasticSearch in situations like this, but I wonder if there’s an idiomatic solution in plain DRF/DF. # models.py from django.db import models class Person(models.Model): name = models.CharField(max_length=200) # filters from django_filters import rest_framework as filters from django.db.models.functions import Substr def get_first_letter_choices(): # Create choices letters = Person.objects \ .all() \ .annotate(first_letter=Substr('name', 1, 1)) \ .values_list("first_letter", flat=True) \ .distinct() return [(letter, letter, ) for letter in letters] … -
Cannot assign "'10000'": "Jobs.client_id" must be a "Clients" instance
I have two tables, Jobs and Clients. class Jobs(models.Model): client_id = models.ForeignKey(Clients,db_column='client_id',on_delete=models.CASCADE) class Clients(models.Model): created = models.DateTimeField() modified = models.DateTimeField(auto_now=True) I have Jobs data in json format. jobs_data = { 'client_id':'10000', .... } When I want to save this data into Jobs table I get the ValueError: Cannot assign "'10000'": "Jobs.client_id" must be a "Clients" instance. To save the table I have tried jobs_obj = Jobs.objects.create(**v['Job']) How can I fix this problem ? -
django.core.exceptions.ImproperlyConfigured: Set the CRYPTO_KEY environment variable How do I fix it ?I can't start the project
After I run python manage.py runserver gives this error. The Output in: Traceback (most recent call last): File "C:\new-folder\venv\Lib\site-packages\environ\environ.py", line 273, in get_value value = self.ENVIRON[var] ~~~~~~~~~~~~^^^^^ File "<frozen os>", line 678, in __getitem__ KeyError: 'CRYPTO_KEY' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\new-folder\manage.py", line 21, in <module> main() File "C:\new-folder\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\new-folder\venv\Lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\new-folder\venv\Lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\new-folder\venv\Lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\new-folder\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\new-folder\venv\Lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\new-folder\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "C:\new-folder\venv\Lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\new-folder\venv\Lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\new-folder\venv\Lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File … -
How to paginate the filtered results in django
views.py def do_paginator(get_records_by_date,request): page = request.GET.get('page', 1) paginator = Paginator(get_records_by_date, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return users def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) new_records_check_box_status = request.POST.get("new_records", None) print(new_records_check_box_status) error_records_check_box_status = request.POST.get("error_records", None) print(error_records_check_box_status) drop_down_status = request.POST.get("field",None) print(drop_down_status) global get_records_by_date if new_records_check_box_status is None and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) get_records_by_date = do_paginator(get_records_by_date,request) elif new_records_check_box_status and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(new_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) get_records_by_date = do_paginator(get_records_by_date, request) elif error_records_check_box_status and new_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(error_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) get_records_by_date = do_paginator(get_records_by_date, request) else: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(Q(new_records__gt=0)|Q(error_records__gt=0)) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) get_records_by_date = do_paginator(get_records_by_date,request) # print(get_records_by_date) else: roles = Scrapper.objects.all() page = request.GET.get('page', 1) paginator = Paginator(roles, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, "home.html",{"users": users}) return render(request, "home.html", {"users": get_records_by_date}) home.html <!DOCTYPE html> <html> <body> <style> h2 {text-align: center;} </style> <h1>Facilgo Completed Jobs</h1> <div class="container"> <div class="row"> <div class="col-md-12"> <h2>Summary Details</h2> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%"> <thead> <tr> <th>scrapper_id</th> <th>scrapper_jobs_log_id</th> <th>external_job_source_id</th> <th>start_time</th> … -
Does rows exists in pivot table
Is there a cleaner way to check does all providers for item exists in pivot table? eg. I have few items, if one of them has all given providers then method should return True otherwise False for item in items: exists_count = 0 for provider in providers: if ItemProviderConn.objects.filter( item_id=item.pk, provider_id=provider.pk, ): exists_count += 1 else: break if exists_count == len(providers): return True return False -
The difference between create() method and create_user() in Django
I created the user model myself and I don't use Django's default model. To create a user, if I use the create() method, the date field will set value that field, but if I use the create_user() method, I have to give a value to the date field. Why does this happen? class UserManager(BaseUserManager): def create_user(self, email, f_name, l_name, phone, create, password): user = self.model(email=self.normalize_email(email), f_name=f_name, l_name=l_name, phone=phone, create=create, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, f_name, l_name, phone, create, password): user = self.create_user(email, f_name, l_name, phone, create, password) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): f_name = models.CharField(max_length=50) l_name = models.CharField(max_length=50, blank=True, null=True, ) email = models.EmailField(unique=True, blank=True, null=True) phone = models.BigIntegerField(blank=True, null=True, ) data = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) permission = models.ManyToManyField(Permission, related_name='users') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone', 'f_name', 'l_name', 'create'] objects = UserManager() -
Django, additional fields by product category
Please help. I'm trying to write an online store in Django. I want additional fields of product characteristics to appear depending on the product category. For example: if you select the "coffee" category in the admin panel when creating a product card, then a block with additional fields would appear: processing_method, geography, special, sour, roasting. If you select the category "tea" - there are other additional fields. I tried using fieldsets in admin.py - I realized that this option is not suitable. I stopped at creating a field in models.py - characteristics = models.JSONField(), read the documentation and did not understand how to implement my case. The meaning of the ideas is in the dynamic formation of the card (additional fields) when choosing a category I will be glad to any link with a similar example or a solution to a similar problem or guidance on the right way to solve this problem. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): ROASTING_CHOICES = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5) ) … -
You do not have permission to perform this action Even if i dont put any permession class on the view
my setting.py authentication setting for drf REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } my views which having issu @api_view(['POST']) @permission_classes([IsAuthenticated]) def createAddress(request): data = request.data try: address = AddressSerializer(data=data) if address.is_valid(): address.save() return Response(address.data) else: return Response(address.errors, status=status.HTTP_400_BAD_REQUEST) except Exception: message = {'detail': 'Address is not valid'} return Response(message, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) @permission_classes([IsAuthenticated]) def getAddress(request): print(request) address = Address.objects.all() serializer = AddressSerializer(address, many=True) return Response(serializer.data) When i hit createAddress with Autherization in the header and the Token as well in that works fine but when i hit getAddress then i get the error Even if i comment the permission class on the getAddress i still get the issue -
React + Django csv handle
I'm working on a Data Mining app with React and Django, I kind of understand how to send the file to Django, but how do I read the file, apply an algorithm and return the process data to react for showing it? The objective of the app is to read a differente csv file each time, so, I don't need to create models, don't even need to store the data, just handle the information. I've seen a lot of tutorials, but everyone make use of a database, is there a method to process the file without saving anything, just processing and return the process data for create graphs and stuff? how an I do that? This is my attempt with a react component for sending the file to django, but now, whats next? how do I read it in django? and how do I send the process data back to react? import { useState } from "react"; function DragDropFiles(){ const [selectedFile, setSelectedFile] = useState(); const [isFilePicked, setIsFilePicked] = useState(false); const changeHandler = (event) => { setSelectedFile(event.target.files[0]); setIsFilePicked(true); } const handleSubmission = async () =>{ const formData = new FormData(); formData.append('File', selectedFile); let newData = await fetch( base_url, { method: 'POST', … -
Django: Object not getting serialized as Object but instead shows Foreign Key [closed]
I've been trying to display an object "pfam" within another object "domains". But the results I'm getting shows pfam_id just as a foreign key. I've tried printing the details of queryset and queryset[0].pfam gets me a pfam object so I know my models isn't wrong. I'm thinking its something to do with the serializers but I'm not too sure what went wrong. Models.py imports .. class pFam(models.Model): domain_id = models.CharField(max_length=256,null=False,blank=False,unique=True) domain_description = models.CharField(max_length=256,null=False,blank=False) class Domains(models.Model): pfam = models.ForeignKey(pFam,on_delete=models.CASCADE) description = models.CharField(max_length=256,null=False,blank=False) start = models.IntegerField(null=False,blank=False) stop = models.IntegerField(null=False,blank=False) Serializer.py imports .. class PfamSerializer(serializers.ModelSerializer): class Meta: model = pFam fields = ['domain_id','domain_description'] class DomainSerializer(serializers.ModelSerializer): pfam_id = PfamSerializer class Meta: model = Domains fields = ['pfam_id','description','start','stop'] api.py imports .. class ProteinDetail(mixins.RetrieveModelMixin, generics.ListAPIView): serializer_class = DomainSerializer queryset = Domains.objects.all() def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) urls.py imports .. urlpatterns = [ path('api/protein/<int:pk>', api.ProteinDetail.as_view(), name='protein_api'), ] This is the result I'm getting, but instead of showing pfam_id as a foreign key I want it to show the contents of pfam. Im not sure why my PfamSerializer isn't working in this scenario. [1]: https://i.stack.imgur.com/LfAOC.png -
Django Authorization Token returns AnonymousUser
I'm trying to get the user from a request. My reactjs/postman client sends the token in the header as follow: 'Authorization' : 'Token token_string' For some reason, when I using self.request.user in the view (GET request) I'm getting AnonymousUser. The token is valid, using the following code I'm getting the correct user, not AnonymousUser: from rest_framework.authtoken.models import Token from django.shortcuts import get_object_or_404 user = get_object_or_404(Token, pk=token_string).user Here is my setting.py MIDDLEWARE: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] Here is my User model: class User(django.contrib.auth.models.User): avatar = models.URLField(max_length=255, blank=True) date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=256) Note: when I'm calling the request using the browser after logging in to Django admin I'm getting the user properly. -
How to i merge this two JS work together and calculate time
I am making Time tracking app. Here i have already did time starting and stop event and stored that total timing data. But i need to implement further that idle time tracking without any movement of mouse, keyboard or any thing else. That time store data and final result should be like this :::::: Total time today : 6 hr 30 min idel time today : 1hr 30 min Or Working time today: 5hr 00 min. But i don't know how to get this. This is my Vue.js Script :: <script> var NavbarApp = { data() { return { seconds: {{ active_entry_seconds }}, trackingTime: false, showTrackingModal: false, timer: null, entryID: 0, startTime: '{{ start_time }}' } }, delimiters: ['[[',']]'], methods: { startTimer() { fetch('/dashboard/projects/api/start_timer/',{ method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) =>{ return response.json() }) .then((result) =>{ this.startTime = new Date() this.trackingTime = true this.timer = setInterval(() => { this.seconds = (new Date()- this.startTime) / 1000 }, 1000) }) }, stopTimer(){ fetch('/dashboard/projects/api/stop_timer/',{ method: 'POST', headers: { 'Content-Type':'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) =>{ return response.json() }) .then((result) =>{ this.entryID = result.entryID this.showTrackingModal = true this.trackingTime = false window.clearTimeout(this.timer) }) }, discardTimer(){ fetch('/dashboard/projects/api/discard_timer/',{ … -
Multi-table inheritance and two many to many via through model not working in admin inline
I'm trying to create navigation menu from the django admin as per user's requirement. The Model look like this: class MenuItem(models.Model): title = models.CharField(max_length=200, help_text='Title of the item') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=False) def __str__(self): return self.title class Page(MenuItem): """ To display non-hierarchical pages such as about us, or some page in menu """ slug = models.SlugField(max_length=200, unique=True, help_text='End of url') content = HTMLField(help_text='Contents of the page') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) class Category(MenuItem): """ For hierarchical display eg. in navigation menu use Category and Articles. """ slug = models.SlugField(max_length=200, unique=True, help_text='End of url') class Meta: verbose_name_plural = 'categories' Page and Category can be different types of menu items, so, I used inheritance. Now I want to bind the MenuItem to a Menu, hence I added two more models below. class Menu(models.Model): title = models.CharField(max_length=200, unique=True, help_text='Name of the menu.') is_published = models.BooleanField(default=False) item = models.ManyToManyField(MenuItem, through='MenuLevel', through_fields=['menu', 'menu_item']) def __str__(self): return self.title class MenuLevel(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='items') level = models.IntegerField(default=0) parent = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='parent', null=True, blank=True) I need the parent key to menu item to traverse through the menu items from parent to children and level to sort the … -
Django admin search box: searching by field names
I'm trying to customize django admin search box for models so I can search for multiple fields at once Here is what I have: class Person(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=200) class SearchMixin(admin.ModelAdmin): def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(TargetedSearchFieldMixin, self).get_search_results( request, queryset, search_term) search_words = search_term.split() if search_words: q_objects = [Q(**{field + '__icontains': word}) for field in self.search_fields for word in search_words] queryset |= self.model.objects.filter(reduce(or_, q_objects)) return queryset, use_distinct This will work for person model if we give input like this: jack +1558844663 Will search for people with phone number +1558844663 and name jack I want to change the method to accept inputs with field names like this: name=jack&phone=+1558844663 -
DJANGO form from models - select options from ajax jquery
I can't find in DJANGO docs solutions. I have a form with two select fields (Foreign key). Django automatically create options from models, but i want second field is filled with ajax, depending on what we choose in the first field. For now I do in document ready $('#id').find('option').remove().end() but it's not elegant at all ;) How to set DJANGO form not to fetch data for a specific field automatically? -
how to increase amount if date and time greater than 24 hours in Django?
**My booking views.py file. ** def booking(request): context = { 'amount': 100 } ** my booking.html** <p>Amount = RS {{amount}} </p> **I want to increase this amount.** I want to increase the above mention amount when user select data and time greater than 24 hours. if your do so then the amount increase automatically. -
Calling WebSocket Class Function from view is not working in Django Rest Framework
I wanted to call a function from the consumer file function receive. I'm using that method. but this is not working. this is a consumer.py class ChatConsumer(AsyncWebsocketConsumer): def getUser(self, userId): ... Some Code def saveMessage(self, message_obj): ... Some Code async def connect(self): ... Some Code async def receive(self, text_data, type='receive'): ... Some Code async def chat_message(self, event, type='chat_message'): ... Some Code async def disconnect(self, close_code): ... Some Code this is a serializers.py class CreateChatMessageView(APIView): cls_consumers = consumers.ChatConsumer() channel_layer = get_channel_layer() message_obj.save() chat_message_serializer = CreateChatMessageResponseSerializer(message_obj) async_to_sync(channel_layer.group_send)( str(message_obj.chat_room.id), { 'type': 'receive', 'message': chat_message_serializer.data } ) print("Ok") ... Some Code -
How to consume messages from Kafka consumer to Django app in new docker container?
The Django server is going stuck if Kafka-comsumer starts. What should I do? I want to run this consumer as a sidecar container. Can anyone help me? consumer = KafkaConsumer("my-topic", bootstrap_servers=\['{}:{}'.format(HOST, PORT)\],auto_offset_reset="earliest", value_deserializer=lambda x: ReadHelper().json_deserializer(x), group_id="my_consumer_group" ) for msg in consumer: print(msg) -
How To Automatically Create Objects Of Django Model While Creation Another Model Objects
I Want To Create Object For "ProductOut" Model When "CusOrder" Model Is Being Created Here Is My Code class CusOrder(models.Model): cus_name = models.CharField(max_length=100) cus_number = models.CharField(max_length=11) product = models.ManyToManyField(Product) qty = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) def __str__(self): return self.cus_name def save(self,*args,**kwrgs): ProductOut.objects.create( refrence=self.cus_number, stock_out = self.qty, sell_price = self.sell_price, product = self.product.P_name ) super(CusOrder,self).save(*args,**kwrgs) class ProductOut(models.Model): refrence = models.ManyToManyField(CusOrder) stock_out = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) product = models.ForeignKey(Product,on_delete=models.CASCADE) def __str__(self): return self.refrence.cus_number But I am Getting a ValueError which Is '"<CusOrder: Asif>" needs to have a value for field "id" before this many-to-many relationship can be used.' When I want to save a CusOrder Object here Is My Whole class Catagory(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class Product(models.Model): P_name = models.CharField(max_length=30) stock_in = models.IntegerField(default=0) unit_price = models.IntegerField(default=0) cata = models.ForeignKey(Catagory, on_delete=models.CASCADE) def __str__(self): return self.P_name class CusOrder(models.Model): cus_name = models.CharField(max_length=100) cus_number = models.CharField(max_length=11) product = models.ManyToManyField(Product) qty = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) def __str__(self): return self.cus_name def save(self,*args,**kwrgs): ProductOut.objects.create( refrence=self.cus_number, stock_out = self.qty, sell_price = self.sell_price, product = self.product.P_name ) super(CusOrder,self).save(*args,**kwrgs) class ProductOut(models.Model): refrence = models.ManyToManyField(CusOrder) stock_out = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) product = models.ForeignKey(Product,on_delete=models.CASCADE) def __str__(self): return self.refrence.cus_number class ReturnedProduct(models.Model): cus_number = models.ForeignKey(CusOrder,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) qty … -
How to create custom Response in drf generic ListAPIView
I'm showing reviews of each products, so If a product don't have a review yet then i want to show a response like there 'No reviews yet" class ShowReviews(generics.ListAPIView): serializer_class = ReviewSerializer filter_backends = [filters.DjangoFilterBackend, OrderingFilter] filterset_class = ReviewFilter ordering_fields = ['rating', 'id'] lookup_field='product_slug' def get_queryset(self): slug = self.kwargs['product_slug'] return ReviewRatings.objects.filter(product__slug=slug, is_active=True) And please share the link if anything mentioned about this in docs because I'm unable to find any solutions. -
killing docker container from docker desktop
Created an django app and dockerize it and then before I stopped the container I removed the app and then I could not remove the container yet Can you help me please to remove docker container once I clicked remove button it says that removing container from docker -
Long Processing within Django ModelAdmin Form
I have a custom form in a admin.ModelAdmin where I use to upload some CSV data with a file upload. Sometimes, processing this CSV file takes longer than the HTTP Worker timeouts will allow, forcing me to split up the CSV file into smaller chunks that will not trip the worker timeouts. I need to find a way to avoid splitting up the CSV into separate chunks to upload one at a time. I was researching how I might resolve this issue, and I am having a hard time finding any resources I might be able to learn from, like a tutorial. What are some common patterns and best practices when I need to do something long-running (>30s) in Django Admin? I am looking for pointers, guides, and tutorials. Thank you!