Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django: model ForeignKey from a ForeignKey
I want to do something like this en Django: Model1 defines several types. Model2 define a name and select one type. Model3 copy the name and types definited in Model2, and defines other variable. I've tried this, but it doesn't work: class Model1(models.Model): types = models.CharField(max_length=50) class Model2(models.Model): name = models.CharField(max_length=50) types = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True) class Model3(models.Model): name = models.ForeignKey(Model2, on_delete=models.CASCADE,related_name='name') types = models.ForeignKey(Model2, on_delete=models.CASCADE,related_name='types') other = models.CharField(max_length=50) This doesn't work. ¿any idea or alternative? Thanks!! -
Django - Annotate queryset with result of function
I am trying to take a queryset and annotate it so that the value of the new field is the result of a function that requires the object being annotated. In this case I am taking a queryset of cars and annotating it with the distance of the car which is calculated by a function. The main issue I am having is getting the annotations to be unique to each car rather than a bulk annotation, I have tried most of the approaches mentioned elsewhere on here but none seem to be working. The closest I have come so far is by using an approach using Unions, this got the annotations in, however my next step is to order this Queryset so I need to have the ability to do that without losing the annotation. For context: car is a Car object, distances is a dictionary of distances. Unannotated is initially set to a queryset of cars which may already have annotation applied from a previous function. The Union solution I found is: for car in unannotated: annotated = unannotated.filter(id=car.id).annotate(distance=Value(get_distance_of_car_from_distances(distances, car))) clean = clean.union(annotated) However as stated previously, this caused issues with the ordering step further on. I have also … -
How to fix no outer ring when creating a project in Django (vscode)?
I have this problem when creating a project in Django (vs code) that only a package <nameoftheproject> gets created and not the outer container (with the same name as the package) that was supposed to be created with the code below. Is this a bug that it is not there or it doesn't appear in the project dir in vscode anymore(course I am doing is from 2018, maybe it doesn't appear anymore)? I could go without it and build an easy application, but I couldn't deploy it using Git and Haroku. This is a source code I used in the terminal to start a project: mkdir vidly cd vidly pipenv install django==2.1 django-admin startproject <nameoftheproject . code . And this is the result enter image description here Is that okay? And if not how do I fix it? Thanks! I tried creating a project in global environment (instead of pipenv). Didn't work. Using different Django version didn't work either. -
django username regex [closed]
django username input allow some symbols with forms.py 'pattern': '[A-z0-9]+[^_]+' not allow _testuser, __testuser, not allow 2 line __ allow test_user, testuser, 'pattern': '[A-z0-9]+[^_]+' i like configure as telegram username -
I write view for my blog and i want after user left a comment web page redirect to that post but i have this problem
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. return redirect('post_detail', slug=post.slug) This is my comment view: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) tags = Tag.objects.all() tagsList = [] for tag in post.tags.get_queryset(): tagsList.append(tag.name) profile = Profile.objects.get(user=request.user) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.profile = profile new_comment.post = post new_comment.save() return redirect('post_detail', slug=post.slug) else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags}) Is there anything i missed in redirect function? -
How can I set up a proxy layer for SFTP using Django-storages?
I'm attempting to come up with a solution to my current issue. I have a Django application that enables users to upload files to a remote server with SFTP. This operates without a hitch. I'm having trouble telling the application to download those files from the server after they have been uploaded. I took time to investigate on this subject, but I didn't find much. Although I did find this thread and it was useful, I'm still lacking the final element and how to tie everything together. I created a middleware in my application based on the thread mentioned above, and I made sure to update the middleware in my settings. I'm not sure if the middleware needs to be called somewhere else in the application or some other element needs to be added on top it. Any help is appreciated, thanks. middleware.py import mimetypes from storages.backends.sftpstorage import SFTPStorage from django.http import HttpResponse class SFTPMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): SFS = SFTPStorage() response = self.get_response(request) path = request.get_full_path() if SFS.exists(path): file = SFS._read(path) type, encoding = mimetypes.guess_type(path) response = HttpResponse(file, content_type=type) response['Content-Disposition'] = u'attachment; filename="{filename}"'.format(filename=path) return response settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", … -
Django + FastAPI
Can i run FastAPI server when i put in terminal python manage.py runserver. I want -> when django server is already running he also run server for fastapi, so then i can do something like that in browser ('api/' -> give me FastAPI), but when ('django/'-> give me django -> root page my project). In general, I want to make access to the api through some path, as well as a full-fledged Django site that will use this api for its purposes, with templates, etc. And so that the user can switch between them at any time -
Python can't find MySQL ... why not?
Here is the complete traceback: (MacOS) Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib' Referenced from: '/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so' Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/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 "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): …