Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overwrite Django ImageField to accept absolute URIs as well as files
What ImageField does under the hood , is that is stores the image path as string in the db. I would like to overwrite the field in such a way, that it can accept either a binary image file or absoulte URI path and return the path as string and store it as char in the db. Which method would have to be overwritten to achieve this operation ? thanks -
HTML Email not sending when debug=false in django
I am making a website in which once the user registers for an event they are sent an email for the same confirming that they have registered for the event. Now, the thing is I can send the html mail when DEBUG=True but I am not able to send the html mail when DEBUG=False in Django, neither I am able to detect why is it failing. Attaching code snippet. Thanks for your help! settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = env('EMAIL_USE_TLS') == 'True' EMAIL_HOST = env('EMAIL_HOST') #smtp.gmail.com EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = env('EMAIL_PORT') #587 views.py try: EventRegistration(event=event_obj, first_name=first_name, last_name=last_name, roll_number=roll_number, phone_number=phone_number, email=email, year_of_study=year_of_study, department=department).save() subject = f"Registration Successfull For {event_name}" html_message = render_to_string("mail related/Register Confirmation.html", context={'image': event_obj.banner_image, 'name': event_name, 'date': event_obj.event_date}) plain_message = strip_tags(html_message) from_email = settings.EMAIL_HOST_USER to_list = [email] send_mail(subject, plain_message, from_email, to_list, html_message=html_message) messages.info(request, 'Successfully registered') except e: messages.warning(request, 'Failed to Register') return render(request, 'main/register.html', context) except Exception: return redirect('events' -
How can I perform calculations from the queryset of one model add them to the fields of another model?
Good day! I have two Django table models. And even the result of the query after the filter operation with the model table. One of these tables contains data that is populated using a Django form. Another table can be filled only with data obtained after performing calculations with data from the first table. How can I fill in a row or add a second table? I need to perform calculations with the last row from the first table and send the results to the second table. This is something reminiscent of processing data in two DataFrame . How can I add a table of values to the model after performing calculations on the data from the last row from another table model? class Model_1(models.Model): name_1 = models.IntegerField() name_2 = models.IntegerField() name_3 = models.IntegerField() name_4 = models.IntegerField() class Model_2(models.Model): name_5 = models.IntegerField() name_6 = models.IntegerField() queryset = Model_1.objects.all() values_m1 = queryst.name_1 * queryst.name_2 / queryst.name_3 - queryst.name_4 queryset = Model_2.objects.all() values_m2 = queryst.name_5 = values_m1 -
Unexpected keyword arguments
I have gone through many posts on SO and other places but I am unable to find a solution to the same problem. I am getting the following error TypeError: Basetable() got unexpected keyword arguments: 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents' I have the following JSON Data jsonToUse = { "CompanyId": "320193", "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": "-6", "unitRef": "usd", "value": "39789000000" }, { "decimals": "-6", "unitRef": "usd", "value": "50224000000" }, { "decimals": "-6", "unitRef": "usd", "value": "25913000000" }, { "decimals": "-6", "unitRef": "usd", "value": "35929000000" } ] } Model: class Basetable(models.Model): basetable_id = models.AutoField(primary_key=True) CompanyId = models.IntegerField() class Cashcashequivalentsrestrictedcashandrestrictedcashequivalents(models.Model): cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id = models.AutoField( primary_key=True) unitRef = models.CharField(max_length=100) value = models.CharField(max_length=100) decimals = models.IntegerField() basetable_id = models.ForeignKey(Basetable, on_delete=models.CASCADE) Serializer: class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer(serializers.ModelSerializer): class Meta: model = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents fields = ['decimals', 'unitRef', 'value'] class CashFlowSerializer(serializers.ModelSerializer): CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer( many=True) class Meta: model = Basetable fields = "__all__" View: .....#TRIMMED GET SYNTAX..... check = CashFlowSerializer(data=jsonToUse) if (check.is_valid(raise_exception=True)): print("ready to send to db") check.save() return JsonResponse(jsonToUse, safe=False) I want to save the data in the database for the provided JSON -
Nested serializers change JSON field to array of strings from array of models
Right now, I'm developing a social media app where each user creates an account and must fill out a form specifying their basic info and I am storing that information using Django models. I have two fields "Personality traits" and "Interests" where each user can have multiple interests and personality traits, to model this I'm using a foreign key relationship. My models.py looks like this: class ListingAccount(models.Model): first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) email = models.EmailField(max_length=254, null=True) date_of_birth = models.DateField(max_length=8, null=True) occupation = models.CharField(max_length=30, null=True) age_range = models.CharField(max_length=7, null=True) tell_us_about_yourself = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) # unsure if needed class PersonalTrait(models.Model): trait = models.CharField(max_length=200, null = True) listing_account = models.ForeignKey(ListingAccount, related_name='personal_traits', on_delete=models.CASCADE, null=True) class Interest(models.Model): interest = models.CharField(max_length=200, null=True) listing_account = models.ForeignKey(ListingAccount, related_name='interests', on_delete=models.CASCADE, null=True) My serializers.py looks like this: class PersonalTraitsSerializer(serializers.ModelSerializer): class Meta: model = PersonalTrait fields = ['trait'] class InterestsSerializer(serializers.ModelSerializer): class Meta: model = Interest fields = ['interest'] class ListingAccountSerializer(serializers.ModelSerializer): personal_traits = PersonalTraitsSerializer(many=True) interests = InterestsSerializer(many=True) class Meta: model = ListingAccount fields = ['id', 'first_name', 'last_name', 'email', 'date_of_birth', 'occupation', 'age_range', 'tell_us_about_yourself', 'created', 'personal_traits', 'interests'] def create(self, validated_data): interests_data = validated_data.pop('interests') personal_traits_data = validated_data.pop('personal_traits') listing_account = ListingAccount.objects.create(**validated_data) Interest.objects.create(listing_account = listing_account, **interests_data) PersonalTrait.objects.create(listing_account = listing_account, **personal_traits_data) for interest_data … -
Missing fields after migration in Django project
I am interested in learning python and Django and I've started this course. I am having difficulties in migrating the models in the project. Following the course, on chapter "Models". I've inserted the given code in the boards/models.py file as instructed. The code: from django.db import models from django.contrib.auth.models import User class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics') starter = models.ForeignKey(User, related_name='topics') class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='posts') updated_by = models.ForeignKey(User, null=True, related_name='+')` Following the instructions to the "Migrating the Models" chapter and running this command: "python manage.py makemigrations" I should receive the following message: Migrations for 'boards': boards/migrations/0001_initial.py - Create model Board - Create model Post - Create model Topic - Add field topic to post - Add field updated_by to post Instead, I get the following errors: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Desktop\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "D:\Desktop\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "D:\Desktop\myproject\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Desktop\myproject\venv\lib\site-packages\django\apps\registry.py", line 114, … -
Field with default value appears as optional in schema
Describe the bug My code has the following model with a boolean field, published, with a default value of false class PublishableModel(models.Model): """Fields used to determine if and when something is published.""" published = models.BooleanField(default=False) publish_date = models.DateTimeField(blank=True, null=True) However, the schema that drf-spectacular produces shows published as optional. For example: /** * * @type {boolean} * @memberof Article */ published?: boolean; Expected behavior: Since there is a default value - all response types should appear in the required section of the model for methods that return an Article but optional for methods that are creating an Article. Is there a way to distinguish between request and response values being required in the schema? -
Django freezer app - Checking a time delta
I am working on a project for organizing a freezer. Therefore I added a model called 'ShoppingItem'. It has an 'best before' date. Now I want to check three things via a function: Is the food expired? Is the food fine? Or is the food 'critical' (3 days before expiring) This is my whole models.py It includes the model itself and two functions. enter image description here enter image description here I tried on the expired function but can't come up with a solution -
PostgreSQL full text search giving different results for different database version
I am trying to use Postgres full text search with my Django project in order to search for products in my database. The shop_products table has a GIN index field search_vector. I also currently have two databases, with one being the production server that is hosted on AWS RDS (PostgreSQL 14.3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 7.3.1 20180712 (Red Hat 7.3.1-12), 64-bit) and the other being my local development database (Version PostgreSQL 14.2, compiled by Visual C++ build 1914, 64-bit). The issue I am having is that some search results work normally on the development server but not on the production server. For example, when I am looking for products with the word 'extreme' in them using the following query SELECT * FROM shop_products WHERE search_vector @@ websearch_to_tsquery('extreme'); Both of the databases have the exact same indexing where 'extreme' is stored as 'extrem' in the database, and searching for 'extrem' in both databases returns the same results. So is the reason for this the different PostgreSQL versions or is something else possible affecting the search results? -
connecting react native with django, fetching data
I just try to connect the native react app with the django backend. So in Django I installed the django.cors.headers. And i did the configuration in settings. I am using android studio. And I am using the emulator. And that works fine. And I have the settings for the cors in django: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ "http://localhost:8081", "http://localhost:19006", "http://localhost:19002", "http://192.168.1.69:19000", ] and react native useEffect(() => { fetch("http://127.0.0.1:8000/animalGroups/group/", { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", }, }) .then((res) => res.json()) .then((jsonres) => setAnimalGroup(jsonres)) .catch((error) => console.error(error)); }, []); and this are the messages in react native: Opening on Android... › Opening exp://192.168.1.69:19000 on MY_ANDROID › Press ? │ show all commands › Reloading apps Android Bundling complete But I still get this errors: Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue So what I have to change? Thank you -
PyCharm Django test ModuleNotFoundError
Project tree: |___sb_website | |___article | | |__...py | |___home | | |__...py | |___sb_website | | |__dev_settings.py | | |__...py | |__manage.py | |__...py My django project development settings are dev_settings.py. I want to run my tests against these settings. When I use a Python configuration in PyCharm with these parameters test --settings=sb_website.dev_settings, script path ..\sb_website\manage.py I get the following Error: ERROR: sb_website.article (unittest.loader._FailedTest) ImportError: Failed to import test module: sb_website.article. Same for sb_website.home and sb_website.sb_website If use a Django Test configuration in PyCharm modules are imported and tests run fine. I'd like to learn the root cause of my problem as it is not the first time I faced this. What I tried: changed all imports to explicit imports, e.g. *.models to home.models -
How does Django's HttpResponse status differ from status_code?
I am trying to set up some custom errors views in a Django application, but I am encountering something I don't quite understand regarding the way HttpResponse works. When I return HttpResponse(status=500) Django does not render the 500.html template. However, when I return using status_code HttpResponse(status_code=500), it works. Here are the steps to my problem: Set up handler500 = views.handler500 Build handler500 view: def handler500(request): return render(request, '500.html', status=500) Try and replicate a 500 error: def cart(request): return HttpResponse(status=500) I am trying to prevent having to refactor hundreds of views in the existing codebase from status=500 to status_code=500. I am worried about breaking something. More importantly, I'm trying to understand the difference between the two. When I read the Django source code for response.py, it seems that they convert status to status_code anyway within class HttpResponseBase. Any and all advice is greatly appreciated. -
django first word of a char field
My model in django has a character field with maximum length 500 character. I'm working with a PostgreSQL database: class Chat(models.Model): message = models.CharField(max_length=500) username = models.CharField(max_length=255) date = models.DateTimeField(auto_now_add=True) @property def first_word(self): return self.message.split(" ")[0] I'm interested to evaluate first word of each message and do some aggregation. First word of each message could vary in length thus I can't use Left, Right or Substr database functions: queryset = Chat.objects.annotate(command=F("first_word")).values("command") .annotate(counts=Count("command")) .order_by("-counts") Obviously my queryset is not working because I can't call model methods in database query. However is there a way I can do this by using some other database functions? -
HTTP response headers in python django-graphene
In our project, we are using bearer tokens for normal programmatic access, but would like to implement basic auth along side for use in graphiql. In order to do this, in the case where neither Bearer or Basic are specified, I want to return www-authenticate response header to cause the browser to request the userid/password for basic auth. Any suggestions how to do this? -
Stock chart transfer between server/website
I'm coding a private webapp that can pick some data from a source (yfinance, panda, ...) and generate a time series. Basically, I want to be able to click on any of the Dow Jones stocks with an HTML btn or whatever, which will send a request to my backend server to generate such chart using python, R or any alternative. Two possibilities: I generate the chart and figures on the client's side, by sending the data from the server to the client on a JSON format (which seems really unproductive). Or, I make all computations on backend, following an HTTP request from the client, generate the chart and send it to the client (my computer). The question is, can I send such chart, from the server to the client without uploading it as a png and transmit the link through AJAX etc. May I get the output of a python function and send it ? To summarize: Can a .png file might be sent from a server to an online webapp, any ideas ? Thanks for your comments, this is a technical question and this might be useful for future requests. Also, I plan to code everything using Django … -
How to filter queryset so all elements in list are matched (at a specific key) in a list of dicts JSONfield?
I have a jsonfield thats an array of dicts all with the same structure. I want to filter that checks whether a given record has all values in a list of params at a specific key, somewhere in the list. (jsonfield) array = [{'dict_field': 1..}, {'dict_field': 2}, {'dict_field': 3}] filter = [1,2,3] return queryset.filter('array__dict_field__contains' = filter) (1 result) filter2 = [1,2,4] return queryset.filter('array__dict_field__contains' = filter2) (0 results; as it doesn't satisfy all filters) I'm using the filter __contains as a placeholder but unfortunately its not contains - what should it be? Thanks I tried array__dict_field__in (example schema above) but it doesn't seem to be working. It doesn't error out but doesn't match any records. The PSQL query it generates is as follows: SELECT * FROM "table" WHERE ("table"."array" -> dict_field) IN (2) This returns an error when I run it in PSQL also; it says column role doesn't exist. I thought it was because role has no quotes on it, but I added them and it persists. Perhaps its because my data is an array of dicts (as opposed to dict) as so: [{"role": 2, "years_experience": 3}, {"role": 3, "years_experience": 5}] Importantly in my case, I can only show a … -
How i can get type of backend in models.py? [Django, social auth]
enter image description here enter image description here My username field is email. The telegram platform does not provide for the presence of email. So, I want to install a stub when logging in via telegram. For this way i need type of used backend. I can't find this information online -
Redirect to the main page if authenticated
I got some problems with redirecting. When I already logged in, and try go to "/accounts/login", it still goes to this link, and if I change in url.py path for example "accounts/logins", the redirect is working, but if not authenticated it says me that: UnboundLocalError: local variable 'context' referenced before assignment AND "/accounts/login" is still available views.py def loginPage(request): if request.user.is_authenticated: return redirect("index") if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'registration/login.html', context) url.py urlpatterns = [ path('login/', views.loginPage, name='loginPage'), path('logout/', views.logoutUser, name='logoutUser'), path('register/', views.registerPage, name='registerPage'), ] -
Django annotating Count/Sum different results
I got the following models: class Event(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True) name = models.CharField(max_length=255) minute = models.IntegerField() player_name = models.CharField(max_length=255, null=True, default=None) extra_player_name = models.CharField(max_length=255, null=True, default=None) period = models.CharField(max_length=255) team:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='events') match:Match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='events') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Match(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True, null=False) competition:Competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name='matches') season:Season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='season_matches', null=True, default=None) home:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_matches') away:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='away_matches') minute = models.IntegerField(default=None, null=True) period = models.CharField(max_length=25, default=None, null=True) datetime = models.DateTimeField() status = models.IntegerField() opta_match = models.OneToOneField(OptaMatch, on_delete=models.CASCADE, related_name='match', default=None, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class OptaMatch(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) statsperform_id = models.CharField(max_length=255, unique=True) opta_id = models.IntegerField(unique=True) coverage_level = models.IntegerField(default=None, null=True, blank=True) home:OptaTeam = models.ForeignKey(OptaTeam, on_delete=models.CASCADE, related_name="home_opta_matches") away:OptaTeam = models.ForeignKey(OptaTeam, on_delete=models.CASCADE, related_name="away_opta_matches") competition:OptaCompetition = models.ForeignKey(OptaCompetition, on_delete=models.CASCADE, related_name="matches") season:OptaSeason = models.ForeignKey(OptaSeason, on_delete=models.CASCADE, related_name="matches") status = models.CharField(max_length=255, default=None, null=True, blank=True) date = models.DateField(blank=False, null=False) time = models.TimeField(blank=True, null=True, default=None) datetime = models.DateTimeField(blank=True, null=True, default=None) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class OptaEvent(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) opta_id = models.BigIntegerField(unique=True) type_id = models.IntegerField() type_name = models.CharField(max_length=255) period = models.IntegerField(null=True, blank=True, … -
React, data fetched from module (django) isn't being displayed
What's up some guys... I'm having trouble displaying my data, which I fetch from my django modules. Fetching the data seems to work fine, however it won't render and display. Would very much appreciate any help. Right now only the containers and stuff is getting displayed, none of the data from the module. Here is my react component: NewsItemPage.js import "bootstrap/dist/css/bootstrap.min.css"; import React, {Component, useEffect, useState} from "react"; import {useParams} from "react-router-dom"; import {Card, Col, Container, Row} from "react-bootstrap"; import sheet from "./Images/metal-sheet.jpg"; import "./css/newsItem.css"; import {BoxArrowUpRight, Textarea} from "react-bootstrap-icons"; import {Link} from "react-router-dom"; function withParams(NewsItemPage){ return props => <NewsItemPage {...props} params={useParams()}/> } class NewsItemPage extends Component{ state={ item: {}, loading: true } async componentDidMount(){ let {id} = this.props.params; try { const res = await fetch(`http://localhost:8000/api/news/${id}`); const item = await res.json(); this.setState({ item: item, loading: false }) }catch(e){ console.log(e); } } render() { if(this.state.loading){ return <h1 className="text-center">Vänligen vänta...</h1> } console.log(this.state.item); return( this.state.item ? <Container fluid className="news-wrapper "> <Row fluid className="news-page-col"> <Col className="news-page-col text-center mt-5 mb-5"> <h1>{this.state.item.title}</h1> <hr className="divider"/> </Col> </Row> <Row fluid className="gap-5 justify-content-center mt-5"> <Col> <img src={this.state.item.image} alt="image"/> </Col> </Row> <h4>{this.state.item.date}</h4> <Row> <Col> <Textarea>{this.state.item.description}</Textarea> </Col> </Row> </Container> : <h1>Här finns inget ännu...</h1> ); } } export default withParams(NewsItemPage); And … -
Django import-export - Import model with child from excel
I have two models: Project and Activity. When registering a project, one or more associated activities can be added. How can I import projects from xlsx, which include at least one activity?. I'm using the third party library django-import-export I configure the project resource to export all the activities of each project in one cell separated by /, but I need the opposite, import all the activities of each project. I think that I must first save the Project for obtain the id, next extract the info from cell and finally save each activity associated, but I don't know how to do that. My simplified models are: class Project(models.Model): reg_date= models.DateField( default=date.today) name = models.CharField( max_length=100, unique=True) def __str__(self): return self.name class Activity(models.Model): schedule= models.ForeignKey( Project, on_delete=models.CASCADE) date = models.DateField() description = models.TextField(max_length=1000) class Meta: unique_together = ('schedule', 'date', 'description') class ProjectResource(resources.ModelResource): activities = Field() class Meta: model = Project import_id_fields = ['name'] exclude = ('id',) skip_unchanged = True report_skipped = True fields = ('reg_date', 'name', 'activities') def dehydrate_activities(self, obj): if obj.id: return "/".join([ '({0} - {1})'.format(activity.date, activity.description) for activity in obj.projectactivity_set.all() ]) def skip_row(self, instance, original, row, import_validation_errors=None): if original.name: return True return False An example of exported file … -
Django View, foreign key field is killing performance
MyObjects definition: class MyObjects(models.Model): field_a = models.TextField() field_b = models.TextField() ...more irrelevant text/int fields foreign_key_field = models.ForeignKey(AnotherModel, null=True, on_delete=models.SET_NULL) View definition: @api_view(["GET"]) @permission_classes([IsAuthenticated]) def my_endpoint(request): objs = MyObjects.objects.filter(is_active=True) ...irrelevant logic my_dict = defaultdict(int) for my_obj in objs: ...bunch of irrelevant logic my_dict[str(my_obj.foreign_key_field)] += 1 ...bunch of irrelevant logic return Response(my_dict, status=status.HTTP_200_OK) I do some calculations in my view that are irrelevant and my view takes around 3 seconds for 5000 objects if my_dict[str(my_obj.foreign_key_field)] += 1 is commented out. However, when that line uncommented, my view takes 20seconds. It must be because this field is a foreign key field as none of my other fields are foreign keys. That specific line is the only line referencing that field. How am I able to improve performance on this? I am surprised that just adding this line decreases my performance by that much, as objects is only around 5k and the foreign key table is around 50 objects. No other operations are touching this dictionary because that specific line, so it's not a cascading affect. If I comment out all logic besides that specific line @api_view(["GET"]) @permission_classes([IsAuthenticated]) def my_endpoint(request): objs = MyObjects.objects.filter(is_active=True) my_dict = defaultdict(int) for my_obj in objs: my_dict[str(my_obj.foreign_key_field)] += 1 return … -
Django not loading fixtures when there is post_save signal
I am testing a registration function in my Django app. When users register, a default user_type is designated to the user. I am using a post_save signal to process this. I have a Profile model to be connected with the User and under the Profile model, is a field user_type which is from another model. class UserType(models.Model): name = models.CharField(max_length=50, blank=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.ForeignKey(UserType, on_delete=models.SET_NULL, null=True, blank=True) To automatically assign a default user_type, I have a signal: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: user_type = UserType.objects.get(pk=1) Profile.objects.create( user=instance, user_type=user_type) I made a fixture of my User, Profile, and UserType models and in my APITestCase, I placed the fixture. class TestUserManagement(APITestCase): fixtures = ['fixtures/initial'] When I run the test, the fixtures does not seem to load to the test database. File "/usr/src/app/fixtures/signals.py", line 15, in create_user_profile user_type = UserType.objects.get(pk=1) ... {model}.UserType.DoesNotExist: Problem installing fixture '/usr/src/app/fixtures/initial.json': UserType matching query does not exist. -
Django Python HTMX - Pagination is not working on multiple tables in one template
I try to build a search which shows four tables with four different models. On that multiple tables I have a problem with my infinite scroll. The output doesn't pay attention on the "paginate_by=5" variable so it just show every result. In addition to that, the pagination only use the first item of the get_template_names. So when I scroll down, it fills the tables with the order table. My views.py: **class searchView(ListView): ordering = ['-id'] template_name = 'search_items.html' paginate_by = 5 model = Rooms def get_template_names(self): if self.request.htmx: return ['single-rows/search_orders_single_row.html', 'single-rows/search_products_single_row.html', 'single-rows/search_rooms_single_row.html', 'single-rows/search_suppliers_single_row.html'] return 'search_items.html' def get_context_data(self, **kwargs): searchedItem = self.request.GET.get('searchedItem',default="") context = super(searchView, self).get_context_data(**kwargs) context['all_orders'] = Orders.objects.all() context['all_products'] = Products.objects.all() context['all_suppliers'] = Suppliers.objects.all() context['rooms'] = Rooms.objects.filter(Q(room__contains=searchedItem) | Q(cabinetNumber__contains=searchedItem) | Q(shelf__contains=searchedItem)) #filtered_rooms get the results from the search in the database context['products'] = Products.objects.filter(Q(designation__contains=searchedItem) | Q(category__contains=searchedItem)) context['orders'] = Orders.objects.filter(Q(product__contains=searchedItem) | Q(supplier__contains=searchedItem)) context['suppliers'] = Suppliers.objects.filter(Q(s_name__contains = searchedItem)) context['searchedItem'] = searchedItem return context** my search-template: <div class="col-6 col-s-6 table"> {% if searchedItem %} <h1>Suchergebnisse für: {{ searchedItem }} </h1> {% if rooms or products or orders or suppliers %} {% if rooms %} <p>Suchergebnisse in "Räume"</p> <table class="content"> <thead> <tr> <th>Raum</th> <th>Schranknummer</th> <th>Regalfach</th> <th>Aktion</th> </tr> </thead> <tbody> {% include 'single-rows/search_rooms_single_row.html' %} </tbody> … -
Managing python path and version for Django using mod_wsgi
I've joined the unhappy ranks of people who have tried to set up a Django website served by Apache (on Amazon-linux EC2). I have successfully configured Apache and compiled mod_wsgi against Python3.4 using a virtualenv (at /home/ec2-user/web-dev) largely following instructions at https://gist.github.com/tanuka72/79ae58b16be4ac3fafe0 and the mod_wsgi docs). However, I get an Internal Server Error when loading the Django test app. Looking at the logs, it seems that multiple versions of Python are somehow being called during the processing (see the change from /home/ec2-user/web-dev/lib64/python3.4 to /usr/lib64/python3.7). Also it seems that mod_wsgi cannot be imported (whilst 'import mod_wsgi' works fine from a python prompt in the ec2 terminal). [Thu Jan 19 15:19:27.329376 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] mod_wsgi (pid=9955): Failed to exec Python script file '/var/www/test/test_site/test_site/wsgi.py'. [Thu Jan 19 15:19:27.329445 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] mod_wsgi (pid=9955): Exception occurred processing WSGI script '/var/www/test/test_site/test_site/wsgi.py'. [Thu Jan 19 15:19:27.330049 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] Traceback (most recent call last): [Thu Jan 19 15:19:27.330088 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] File "/var/www/test/test_site/test_site/wsgi.py", line 25, in <module> [Thu Jan 19 15:19:27.330093 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] application = get_wsgi_application() [Thu Jan 19 15:19:27.330108 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] File "/home/ec2-user/web-dev/lib64/python3.4/site-packages/django/core/wsgi.py", line 12, …