Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add custom command to existing django app
I have installed a thirdpartyapp. After installing my ./manage.py --help has an entry like this, $ ./manage.py --help ... [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd2 ... Now I have created thirdparty_cmd1_extra by extending thirdparty_cmd1. I have put it in my application directory. So it looks like $ ./manage.py --help ... [myapp] thirdparty_cmd1_extra [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd2 ... What I want is this, $ ./manage.py --help ... [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd1_extra thirdparty_cmd2 ... -
Query Django ORM three tables with totals
I have three tables CATEGORIES, TIPODESPESA and EXPENSE. I would like to perform a simpler and faster query to return the total expenses grouped by TYPODESPESA and by CATEGORY. The expected result is the one below: enter image description here What I would like is a result in which the totals are grouped first by CATEGORY, then by TYPE EXPENSE and then show the EXPENSES. However, for me to be able to do this, I perform the following queries below and I'm trying to simplify and make it faster, but I'm still learning a few things. If you can help with the query. registros = CategoriaDespesa.objects.filter( tipodespesas__tipodespesa_movimentodespesa__data__lte=data_final, tipodespesas__tipodespesa_movimentodespesa__data__gte=data_inicio, ) \ .order_by('description') categorias_valores = CategoriaDespesa.objects.filter( tipodespesas__tipodespesa_movimentodespesa__data__lte=data_final, tipodespesas__tipodespesa_movimentodespesa__data__gte=data_inicio, tipodespesas__tipodespesa_movimentodespesa__company=company.company) \ .values('id').annotate(total=Coalesce(Sum( F("tipodespesas__tipodespesa_movimentodespesa__valor"), output_field=FloatField()), 0.00)) tipos_valores = TipoDespesa.objects.filter( tipodespesa_movimentodespesa__data__lte=data_final, tipodespesa_movimentodespesa__data__gte=data_inicio, tipodespesa_movimentodespesa__company=company.company).values('id') \ .annotate(total=Coalesce(Sum(F("tipodespesa_movimentodespesa__valor"), output_field=FloatField()), 0.00)) The classes I'm using are: class CategoriaDespesa(models.Model): description = models.CharField(max_length=200, help_text='Insira a descrição') active = models.BooleanField(default=True, help_text='Esta ativo?', choices=CHOICES) user_created = models.ForeignKey(User, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class TipoDespesa(models.Model): category = models.ForeignKey( CategoriaDespesa, on_delete=models.CASCADE, related_name="tipodespesas") description = models.CharField(max_length=200, help_text='Insira a descrição') active = models.BooleanField(default=True, help_text='Esta ativo?', choices=CHOICES) user_created = models.ForeignKey(User, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Despesa(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="companies_movimentodespesa") tipodespesa … -
Django project - where to put the script?
I am new to python. I am learning django. I made a script that finds certain words on different sites. I give a list of words and a list of sites. As a result, after crawling sites through selenium, I get the result using pandas in the form of a csv file. I want to visualize my project, make a simple web page that will have two windows. In the first window, the user enters a list of words. In the second window - enters a list of sites. Task: check if these words are on these sites. Display the result during the calculation in the form of a table, each time updating it. In the format - link -- found words What should be the structure of my django project? If I understand correctly, then you first need to write the forms in forms.py. What to do next? Where should I put my original script? Thanks this is an example of what I want to see on my page Sorry for the primitive drawing:) -
database viewer for server?
We have a few proprietary tools that store data in rather standard database, using those tools is a pain in the ass. (A common example is a part number database - with some details, and for example a link to a PDF manufactuer data sheet) Getting access to that tool is an issue. For me - 99% of the time - If I could open a giant txt dump of the database and search it using EMACS or VI - I can find what I need. What I'm looking for is a simple (Apache or IIS server) application that I can do that with HTML against the database. Needs to be able to: (A django thing would be great, we already have a django instance) a) Key point - Display and SEARCH only - no data entry. b) Existing well known database with a standard connector. c) Few canned SQL statements would generate the tables to display d) Dimensions are not small full database is 10K (rows) 200+ columns(attributes) e) A KEYWORD search is required - per line: Example Goal find a 0602 resistor that is 220 ohms. I would type "resistor" "film" "0602" and "220" - and click search. … -
Django save child from parent
I have this code: class Model1(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model1s" ordering = ('sioticket',) def def save(self, *args, **kwargs): super(Model1, self).save(*args, **kwargs) class Model2(models.Model): name = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True) cpm = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model2s" ordering = ('sioticket',) def save(self, *args, **kwargs): vartype = self.name.type cpm = vartype return super(Model2, self).save(*args, **kwargs) I need to ejecute save() of Model2 from save() of Model 1. Or, from save() of Model1, do: tipo = self.name.type cpm = tipo But the problem is that, in parents I don't know if is it possible to access to save() of its childs classes or how to change values of its childs classes from save's parents. Also I have to say, that, if I create a new Model1 and Model2 works fine, but if I update type from Model1, it don't replicate to "cmp" of Model2. I've tried this: class Model1(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model1s" ordering = ('sioticket',) def def save(self, *args, **kwargs): super(Model1, self).save(*args, **kwargs) children = self.objects.all() for child in children: if child._meta.verbose_name_plural=="Model2s": child.save() class Model2(models.Model): name = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True) cpm = models.CharField(max_length=50) class Meta: verbose_name_plural … -
Django - Pagination test
When moving a test from a separate class to a class with other tests, it starts showing 4 posts on the second page instead of 3. If range is changed to 12 it shows 2 posts. Please suggest what is the problem. def test_correct_page_context_guest_client(self): posts = [Post(text=f'Тестовый текст {i}', group=self.group0, author=self.user0) for i in range( 13)] Post.objects.bulk_create(posts) pages = (reverse('posts:posts_list'), reverse('posts:group_list', kwargs={'slug': f'{self.group0.slug}'}), reverse('posts:profile', kwargs={'username': f'{self.user0.username}'})) for page in pages: for page_number in range(2): with self.subTest(page=page): response = self.guest_client0.get( page, {'page': page_number+1}) self.assertEqual(len(response.context['page_obj']), POSTS_COUNT[page_number]) If the test is left in a separate class PaginatorViewsTest(TestCase): then everything works as it should, but this is the task of the reviewer -
can only concatenate str (not "NoneType") to str BeautifulSoup
hi every body i make in my project a search on google with beautifulsoup and i recive this message can only concatenate str (not "NoneType") to str when i try to seach this is search.py from django.shortcuts import render, redirect import requests from bs4 import BeautifulSoup # done def google(s): USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36' headers = {"user-agent": USER_AGENT} r=None links = [] text = [] r = requests.get("https://www.google.com/search?q=" + s, headers=headers) soup = BeautifulSoup(r.content, "html.parser") for g in soup.find_all('div', class_='yuRUbf'): a = g.find('a') t = g.find('h3') links.append(a.get('href')) text.append(t.text) return links, text and this is views.py from django.shortcuts import render, redirect from netsurfers.search import google from bs4 import BeautifulSoup def home(request): return render(request,'home.html') def results(request): if request.method == "POST": result = request.POST.get('search') google_link,google_text = google(result) google_data = zip(google_link,google_text) if result == '': return redirect('home') else: return render(request,'results.html',{'google': google_data}) and this is urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home,name='home'), path('results/',views.results,name='Result') ] and this is template home <form method='post' action="{% url 'Result' %}" class="d-flex" role="search"> {% csrf_token %} <input class="form-control me-2 " type="search" placeholder="ابحث وشارك بحثك مع الاخرين" aria-label="Search" style="width:22rem;"> … -
How can I put data from api to django
I have stored some data in python and now I want to display it in django how can I do that? animeUrl = "https://api.jikan.moe/v4/top/anime" animeResponse = requests.get(animeUrl).json() def topAnime(): for idx, video in enumerate(animeResponse['data']): # z [data] wyciaga mi nastepujace rzeczy ktorze sa pod spodem animeUrl = video['url'] title = video['title'] status = video['status'] type = video['type'] images = video['images']['jpg']['image_url'] #if status == "Currently Airing": print (idx+1,":",animeUrl, ":", status, ":", title, ":", type, ":", images) topAnime() this is my stored data and now I want to display it on website, how can I do that? I'm newbie in django I'm looking for some suggestions I have tried using templates but it didn't worked -
extends and block not working in Django Templates
I'm learning how to use Django templates but I cant get extends and block to work. Here is my code. template.html <!DOCTYPE html> <html> <body> {% block theTitle %} {% endblock %} </body> </html> textComponent.html {% extends 'templates/template.html' %} {% block theTitle %} <div>what is going on?</div> {% endblock %} Here is how the files are organised: _templates __template.html __textComponent.html -
Understanding session with fastApi dependency
I am new to Python and was studying FastApi and SQL model. Reference link: https://sqlmodel.tiangolo.com/tutorial/fastapi/session-with-dependency/#the-with-block Here, they have something like this def create_hero(*, session: Session = Depends(get_session), hero: HeroCreate): db_hero = Hero.from_orm(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero Here I am unable to understand this part session.add(db_hero) session.commit() session.refresh(db_hero) What is it doing and how is it working? Couldn't understand this In fact, you could think that all that block of code inside of the create_hero() function is still inside a with block for the session, because this is more or less what's happening behind the scenes. But now, the with block is not explicitly in the function, but in the dependency above: -
Django per-model authorization permissions
Im facing a problem in Django with authorization permissions (a bit new to Django). I have a teacher, student and manager models. When a teacher sends a request to my API they should get different permissions than a student (ie, a student will see all of his own test grades, while a teacher can see all of its own class's students, and a manager can see everything). My questions are as follows: How do I make all of my models valid system users? I've tried adding models.OneToOneField(User, on_delete=models.CASCADE) But this requires creating a user, and then assigning it to the teacher. What I want is for the actual teacher "instance" to be the used user. How do I check which "type" is my user ? if they are a teacher, student or manager? do I need to go over all 3 tables every time a user sends a request, and figure out which they belong to ? doesnt sound right. I thought about creating a global 'user' table with a "type" column, but then I wont be able to add specific columns to my models (ie a student should have an avg grade while a teacher shouldn't) . Would appreciate … -
Showing admin page of previous project in django
While running server of new project getting the admin page of the previous project how to get the admin page of current project? I tried to add"^" in the urls.py file but it is not working at all -
DJANGO: QueryDict obj has no attribute 'status_code'
I am will be shy a bit. That's my first question here and my English isn't greate to speak or write fluently. So I made CreateAdvert CBV(CreateView) and override the 'post' method for it. I need to update QueryDict and append field 'user' to it. But when I am trying to return the context, it says the problem on the title. Views: class CreateAdvert(CreateView): form_class = CreateAdvert template_name = 'marketapp/createadvert.html' context_object_name = 'advert' def post(self, request): #Because I don't want to give QueryDict 'user' field right from the form, I override the #post method here. user = User.objects.filter(email=self.request.user)[0].id context = self.request.POST.copy() context['user'] = user return context Forms: class CreateAdvert(forms.ModelForm): class Meta: model = Advertisment fields = ['category', 'title', 'description', 'image', ] I have tried to cover context with HttpRequest(). It didn't give me a lot of result. but I tried. -
Save FK on post in django
Hi I am having trouble with saving a fk in Infringer table on post. I am trying to save the customer ID when I add a record. For troubleshoot purposes I added a few print lines and this the out put. As you can see below the correct customer ID is present but the customer is None so its not being saved into the record. The other fields save fine. PLEASE HELP! I am a beginner. customer in forms.py is 2 forms.py instance was saved with the customer None customer in views.py is 2 Successfully saved the infringer in views.py with its customer None views.py @login_required(login_url='login') def createInfringer(request): customer=request.user.customer form = InfringerForm(customer=customer) if request.method == 'POST': customer=request.user.customer.id form = InfringerForm(customer, request.POST) if form.is_valid(): saved_instance = form.save(customer) print (f'customer in views.py is {customer}') print (f'Successfully saved the infringer in views.py with its customer {saved_instance.customer}') return redirect('infringer-list') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringerForm(ModelForm): class Meta: model = Infringer fields = ['name', 'brand_name','status'] def __init__(self, customer, *args, **kwargs): super(InfringerForm,self).__init__(*args, **kwargs) self.fields['status'].queryset = Status.objects.filter(customer=customer) def save(self, customer, *args, **kwargs): instance = super(InfringerForm, self).save( *args, **kwargs) if customer: print (f'customer in forms.py is {customer}') self.customer = customer instance.save() print (f' … -
Can we set only a specific type of user as a foreign key in a model's field
I have a model called CustomUser which holds two types of user, teachers and students. The model has a regd_as field which stores the type of user. The model looks as follows: class CustomUser(AbstractBaseUser, PermissionsMixin): REGD_AS_CHOICES = ( ('TCH', 'TEACHER'), ('STU', 'STUDENT'), ) id = models.UUIDField(primary_key = True, editable = False, default = uuid.uuid4) email = models.EmailField(unique=True) date_joined = models.DateTimeField(auto_now_add = True) regd_as = models.CharField(max_length= 10, choices= REGD_AS_CHOICES, null=True) is_staff = models.BooleanField(default=False) is_active = models.Boolea Now I want to have a model that would store a referal code generated only for users who are teachers. The model looks as follows: class ReferalCode(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) teacher_user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, related_name='teacher_user_referal', null=True) referal_code = models.CharField(max_length=100, unique=True,null=True, blank=True) Question Is there a way to set only teachers from the **CustomUser** model as the foreignkey to teacher_user directly? Currently I am using signals to store only teachers as the user in ReferalCode model. -
Fetching data from database django
Im trying to run a query for a database containing past year scores of gcse and alevel exams, using data entered through a form on the website. the entered form data creates a search id, searches the subsequent record in the database and returns it. the query is working for everything besides physics papers in the gcse section. the same method i used works for alevels papers for bott math and physics. any help would be much appreciated from genericpath import exists from multiprocessing.forkserver import write_signed from pickletools import read_string1 from turtle import write_docstringdict from django.shortcuts import render[[physics database](https://i.stack.imgur.com/qzHrU.png)](https://i.stack.imgur.com/Dg4j7.png) from django.http import HttpResponse from .models import ThresholdData1, ThresholdData_O, Sat_Curves, ThresholdData_OP from .forms import ThresholdForm1, SatForm, ThresholdFormO def alevel(request): out_data= { 'grade': "", 'form': ThresholdForm1, 'A': "", 'B': "", 'C': "", 'D': "", 'E': "", "U": "", "exist": True, "search_string": "", } if request.method== "POST": form= ThresholdForm1(request.POST) if form.is_valid(): subject= form.cleaned_data['subject'] variant= str(form.cleaned_data['variant']) month= form.cleaned_data['month'] year= str(form.cleaned_data['year']) marks= form.cleaned_data['marks'] year1= year[2:4] subject= subject.lower() if subject=="math": s_code= "9709" elif subject=="physics": s_code= "9702" search_string= f"{s_code}/{variant}/{month}/{year1}" if ThresholdData1.objects.filter(searchID=search_string).exists() and marks is None: out_data['search_string']= search_string data= ThresholdData1.objects.get(searchID=search_string) out_data['A']= data.a out_data['B']= data.b out_data['C']= data.c out_data['D']= data.d out_data['E']= data.e return render(request, 'alevel.html', out_data) elif ThresholdData1.objects.filter(searchID=search_string).exists(): data= ThresholdData1.objects.get(searchID=search_string) … -
Django 4 amounts and prices with dollar sign
Do you know why django's templates display prices and amounts starting with a dollar sign ? like ... $ 12.096,00 Do you know how avoid this behaviour ? Do you know how display the sign of base_currency ? Thank you I've tried change settings parameters, but nothing works -
Django - How to split my objects between days dynamically
I have a list of days and exercises that are created based on a form input. When I try to load the exercises on the template, all exercises repeat on every day. However, I want them to be split to 6 exercises on every day. I can do it by using split, and even make my own filters, but it doesn't work dynamically. And since the number of days and exercises can vary depending on the form input, I need a dynamically way to figure it out. <form> <div> <table class="table"> <thead> <tr> {% for week in weeks %} <th></th> <th colspan="3">{{week}}</th> {% endfor %} </tr> </thead> <tbody> {% for day in days %} <tr> {% for week in weeks %} <td></td> <td colspan="2">{{day}}</td> <td><input type="text" class="form-control" /></td> {% endfor %} </tr> <tr> <td>Exercise</td> {%for week in weeks %} <td>Set</td> <td>Weight</td> <td>Reps</td> {% endfor %} </tr> {% for exercise in exercises %} <tr> <td rowspan="3">{{exercise}}</td> {%for week in weeks %} <td>1</td> <td><input type="text" class="form-control" value="" /></td> <td><input type="text" class="form-control" value="" /></td> {% endfor %} </tr> <tr> {%for week in weeks %} <td>2</td> <td><input type="text" class="form-control" value="" /></td> <td><input type="text" class="form-control" value="" /></td> {% endfor %} </tr> <tr> {%for week in … -
Django rest framwork POST request gives error of forbidden
I first want to say that yes, I have looked for answers far and wide. This is a very common error. It's a headache and hopefully, there is just a small mistake I've overlooked. Registering a user works, while logging in a user gives: Forbidden: /api/login [17/Nov/2022 19:37:51] "POST /api/login HTTP/1.1" 403 32 From what I'm reading it's all about permissions, but I don't know how to fix it. I'm following this tutorial: https://www.youtube.com/watch?v=PUzgZrS_piQ In settings.py I have for instance: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'posts', 'users', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ] AUTH_USER_MODEL = 'users.User' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True In Views.py I have: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from .serializers import UserSerializer from .models import User #Create your views here. class RegisterView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') return Response(user) Models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): name = models.CharField(max_length=255) email = models.CharField(max_length=255, … -
Encoding error while loading .json django
I have a json file with data from django which I have imported using the command python -Xutf8 ./manage.py dumpdata > data.json And I tried to upload with command python manage.py loaddata data.json gives me an error like File "Z:\Project\Заказы\Murtaza_Filter\backend\manage.py", line 22, in <module> main() File "Z:\Project\Заказы\Murtaza_Filter\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\loaddata.py", line 102, in handle self.loaddata(fixture_labels) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\loaddata.py", line 163, in loaddata self.load_label(fixture_label) File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\loaddata.py", line 251, in load_label for obj in objects: File "C:\Users\zufar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\serializers\json.py", line 67, in Deserializer stream_or_string = stream_or_string.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte how can i fix this? -
Image Events on Froala Django Editor
I'm using the Froala Django Editor in some forms in my Django REST Framework backend, such as this # resources/forms.py from django import forms from froala_editor.widgets import FroalaEditor from .models import Resource class ResourceForm(forms.ModelForm): class Meta: model = Resource fields = '__all__' widgets = { 'content': FroalaEditor( options={ 'heightMin': 256 } ) } When I try to upload an image (or a video, or any file, but one thing at a time) in the Froala editor I get an error: In the console I have: GET https://{some-id}.cloudfront.net/uploads/froala_editor/images/Nights.of.Cabiria.jpg [HTTP/2 403 Forbidden 15ms] The error above made me wonder that perhaps the image is being uploaded correctly, but the Froala editor can't get it after uploading in order to display it. The application is being hosted in AWS and the uploaded files stored in S3 buckets. And in fact, I checked in the S3 dashboard, and the images are there, so they have uploaded correctly. Even though I'm using all default FROALA_EDITOR_OPTIONS. I'm aware there are specific options for S3 storage (I've tried them) but I'm not using them and it is uploading fine. Still looking at that error, I remembered that in other models in the project I have ImageFields, for … -
django KeyError: 'some-ForeignKey-field-in-model'
I am very badly stuck on this error for days, and I am unable to understand what it is trying to tell me as it is only 2 words. The error is coming when I am trying to insert data into the DB table using python manage.py shell > from app_name.models import Usermanagement > from app_name.models import Inquery i = Inquery( inqueryid=6, inquerynumber="INQ765758499", sourceairportid=Airport(airportid=1), destinationairportid=Airport(airportid=21), stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1), branchid=1, transactiontype="AGENT", businesstype="Self", hodate="2020-11-18", totalshipmentunits=56, unitid=100, grossweight=100, volumemetricweight=100, remark="test", dateofcreation="2018-11-20 00:00:00", dateofmodification="2018-11-20 00:00:00", createdby = Usermanagement(userid=0), modifiedby = Usermanagement(userid=0)) #error KeyError: 'createdby' #traceback File C:\Python310\lib\site-packages\django\db\models\base.py:768, in Model.save(self, force_insert, force_update, using, update_fields) 757 def save( 758 self, force_insert=False, force_update=False, using=None, update_fields=None 759 ): 760 """ 761 Save the current instance. Override this in a subclass if you want to 762 control the saving process. (...) 766 non-SQL backends), respectively. Normally, they should not be set. 767 """ --> 768 self._prepare_related_fields_for_save(operation_name="save") 770 using = using or router.db_for_write(self.__class__, instance=self) 771 if force_insert and (force_update or update_fields): File C:\Python310\lib\site-packages\django\db\models\base.py:1092, in Model._prepare_related_fields_for_save(self, operation_name, fields) 1087 # If the relationship's pk/to_field was changed, clear the 1088 # cached relationship. 1089 if getattr(obj, field.target_field.attname) != getattr( 1090 self, field.attname 1091 ): -> 1092 field.delete_cached_value(self) 1093 # GenericForeignKeys are private. … -
Django only want to get first row of a queryset
i want to display the first entry of a queryset. i try some answers here but it does´tn work on my code example. here is my code: class FeatureFilmAdmin(admin.ModelAdmin): inlines = [ QuoteAndEffortSetInLine, ProjectCompanySetInLine, VendorVFXSetInLine, VendorSetInLine, StaffListSetInLine, ] list_display = ["title", "program_length", "get_production_company_name"] def get_production_company_name(self, Featurefilm): return FeatureFilm.objects.filter(pk=Featurefilm.id).values( "projectcompanyset__production_company__name" ) so i actually want to display the production_company, from the first table of ProjectCompanySet in the admin as list_display. so i actually want to display the production_company, from the first table of ProjectCompanySet in the admin as list_display. but with the code above, it will show me all production_company, if there are multiple ProjectcompanySet. What is displayed so far is also not the production_company name but the str function and not the data field itself. Here I would need help please. here are the models of my problem: class CompanyOrBranch(CompanyBaseModel): name = models.CharField( "Firma oder Niederlassung", max_length=60, blank=False, ) class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" verbose_name_plural = "Kinofilme" class ProjectCompanySet(models.Model): feature = models.ForeignKey( FeatureFilm, on_delete=models.CASCADE, null=True, blank=True, ) production_company = models.ForeignKey( CompanyOrBranch, related_name="production_company", verbose_name="Produktionsfirma", on_delete=models.SET_NULL, blank=True, null=True, ) here is the output of my admin list: -
GetStream (Django) follow doesn't copy activities to the feed
For some reason, neither 'follow' nor 'follow_many' methods can not copy the activities from the targeting feed. I know about the following rules and that's why I double-checked: activities in the target feed were added directly (the target feed doesn't follow any others). That's why I can't find out why the following target feed with activity_copy_limit doesn't copy the specified number of activities. I prepared a quick demo here: from stream_django import feed_manager my_all_feed = feed_manager.get_feed('all', '13344f63-7a47-4e42-bfd0-e1cb7ebc76ad') # this is user's feed (it follows public) activities = len(my_all_feed.get()['results']) # this equals 5 at this point public_feed = feed_manager.get_feed('public', 'all') # this is public feed (general one) public_activities = len(public_feed.get()['results']) # it has 25 activities my_all_feed.unfollow('public', 'all') # I am unfollowing public feed (just to be clean here) activities = len(my_all_feed.get()['results']) # this gives me 0, because I am not keeping history my_all_feed.follow('public', 'all', activity_copy_limit=100) # I am following public feed again (should copy all 25 activities for sure) activities = len(my_all_feed.get()['results']) # and this gives me 5 again, out of 25 I've followed each step in the explorer, so I am sure those results are accurate. And again, the public feed doesn't follow any other feeds, all the activities are … -
I'd like to get feedback on the crypto trading bots architecture(django, celery) [closed]
I want to make crypto trading bots using python, django and celery. But I have no idea how to design architecture. So If you don't mind, Please let me know how to do it. (Sorry for my poor English skills. If there's anything you don't understand, comment me anytime) Requirements Get all of crypto's price every second from openAPI Buy/Sell crypto by comparing between user's average buy price and current price User can see their balance's state by dashboard(django) If the current price exceeds the threshold and the trade process(requirements 2) is executed, the process of receiving crypto price from openAPI(requirements 1) will be delayed. So I planned to separate a process of getting crypto prices from openAPI and storing them in DB. And if the current price exceeds the threshold, the process generates events and delivers them to other processes through a message queue. Also, getting all of the user's average buy price from openAPI every second(requirements 2) can exceed API call limit. So I planned to store user's balance info in DB and synchronize everyday and when buy/sell events occur. I draw architecture with my ideas. I use django for dashboard and celery beat for scheduling, worker for …