Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multi-Table Django Join
Relatively new to Django. I'm building a light CRM in Django. The MYSQL database I built uses associative entities to help deal with many-to-many relationships. I'm trying to use the associative entity "contactdeal" to connect "deals" with "contacts". See models and views below. class Account1(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) biztype = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'account' class Contact1(models.Model): contact_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) account_id = models.ForeignKey(Account1, models.DO_NOTHING, db_column='account_id', blank=False, null=False) contact_notes = models.TextField(blank=True, null=True) contact_email = models.CharField(max_length=255, blank=True, null=True) contact_phone = models.CharField(max_length=255, blank=True, null=True) contact_status = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'contact' class Contactdeal(models.Model): contactdeal_id = models.AutoField(primary_key=True) contactdeal_deal_fk = models.ForeignKey('Deal', models.DO_NOTHING, db_column='contactdeal_deal_fk', blank=True, null=True) contactdeal_contact_fk = models.ForeignKey(Contact1, models.DO_NOTHING, related_name='contactdeal_contact_fk', db_column='contactdeal_contact_fk', blank=True, null=True) class Meta: managed = False db_table = 'contactdeal' class Deal(models.Model): deal_id = models.AutoField(primary_key=True) deal_name = models.CharField(max_length=255, blank=True, null=True) est_value = models.DecimalField(max_digits=13, decimal_places=2, blank=True, null=True) deal_notes … -
How to combine and load data in django like this?
this is my models class model1(models.Model): name = models.charField() class model2(models.Model): model1 = models.Foriegnkey(model1) id = models.IntegerField(primarykey=True) title = models.charFiled() I wanted some thing like this {"model_name1":[{"id":1,"title":"title1"},{"id":2,"title":"title2"}], "model_name2":[{"id":3,"title":"title1"},{"id":4,"title":"title2"}],} how to achieve this in django, the effiecient way -
unable to resolv didn't return an HttpResponse object. It returned None instead
If no input in search bar it returns me the folowing The view wish.views.create_wish didn't return an HttpResponse object. It returned None instead. def create_wish(request): if request.method == 'POST': form = WishForm(request.POST) if form.is_valid(): wish = form.save(commit=False) wish.author = request.user wish.save() my_items = Wish.objects.filter(author=request.user) all_items = Wish.objects.filter(~Q(author=request.user)) messages.success(request, ( "Your location that you want to " "visit has been added to List !")) return render(request, "wish/wish.html", {'all_items': all_items, 'my_items': my_items}) else: my_items = Wish.objects.filter(author=request.user) all_items = Wish.objects.filter(~Q(author=request.user)) return render(request, "wish/wish.html", {'all_items': all_items, 'my_items': my_items}) I just want to go back to the page with a message " please enter a place" -
Django Api url conflicting whenever i apply the url of the app into the urlpatterns and i don't know the way forword here
So, whenever i add this path('api/', include('api.urls')) into the parent urls i get a bunch of errors in the terminal and if i remove it from the urlpatterns i get page not found wheni reload the localhost on my browser, and on the terminal page it shows "Broken pipe from ('127.0.0.1', 8441)" and i'm really really confused right now. Api urls from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register('users', views.UserViewSet, basename='user') urlpatterns = router.urls Parent Urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/', include('api.urls')) ] Errors C:\Users\Administrator\Desktop\CRUD\songcrud\api\views.py changed, reloading. Performing system checks... System check identified no issues (0 silenced). November 07, 2022 - 01:32:32 Django version 4.1.3, using settings 'songcrud.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [07/Nov/2022 01:32:47] "GET / HTTP/1.1" 404 2170 Not Found: /favicon.ico [07/Nov/2022 01:32:47,092] - Broken pipe from ('127.0.0.1', 8441) C:\Users\Administrator\Desktop\CRUD\songcrud\songcrud\urls.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Administrator\Desktop\CRUD\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, … -
CrateDB as timeseries database for Django
I am trying to use CrateDB as timeseries database for Django. I am deploying both services on docker for development. I started by deploying the following versions: Django: 4.1.3 CrateDB: 5.1.0 However, I was getting compatibility error: django.db.utils.NotSupportedError: PostgreSQL 11 or later is required (found 10.5). I have downgraded the Django version to 3.0 where I don't get that error, however now I get this one: System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.InternalError_: Unknown function: pg_catalog.pg_table_is_visible(c.oid) CONTEXT: io.crate.exceptions.SQLExceptions.esToCrateException(SQLExceptions.java:164) io.crate.exceptions.SQLExceptions.prepareForClientTransmission(SQLExceptions.java:151) io.crate.protocols.postgres.Messages.sendErrorResponse(Messages.java:190) io.crate.protocols.postgres.PostgresWireProtocol.handleSingleQuery(PostgresWireProtocol.java:795) io.crate.protocols.postgres.PostgresWireProtocol.lambda$handleSimpleQuery$3(PostgresWireProtocol.java:748) java.base/java.util.concurrent.CompletableFuture.uniComposeStage(CompletableFuture.java:1187) java.base/java.util.concurrent.CompletableFuture.thenCompose(CompletableFuture.java:2309) io.crate.protocols.postgres.PostgresWireProtocol.handleSimpleQuery(PostgresWireProtocol.java:748) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchMessage(PostgresWireProtocol.java:335) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchState(PostgresWireProtocol.java:325) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:293) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:277) io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:336) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:308) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in … -
Dajngo Channels - synchronousonlyoperation is thrown when using SessionMiddlewareStack
I am trying to implement anonymous chat using Django Channels for websocket connection. However, i keep getting the SynchronousOnlyOperation exception when using SessionMiddlewareStack for authentication. Python version: 3.8 Django Version: 4.1 Channels version: 3.0.5 Consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import * class ChatConsumer(AsyncWebsocketConsumer): @database_sync_to_async def add_user_to_room_pool(self): former = Pool(username=self.user, room_name=self.get_room()) former.save() @database_sync_to_async def remove_user_from_room_pool(self): former = Pool.objects.filter(username=self.user, room_name=self.get_room()) former.delete() async def connect(self): self.room_id = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_id self.user = self.scope['session']['Anonymous-Name'] await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.add_user_to_room_pool() await self.accept() async def disconnect(self, close_code): await self.remove_user_from_room_pool() await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.create_message(message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, } ) @database_sync_to_async def get_room(self): return Room.objects.get(name=self.room_id) @database_sync_to_async def get_user(self): return Hikka.objects.get(user=self.scope['user'].id) @database_sync_to_async def create_message(self, text): former = Message(message_author=self.user, message_room=self.get_room(), message_text=text) former.save() async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) I've tried removing all cached session data from both Django and web-browser, but that didn't help. I've seen custom implementation of the Middleware, that uses token authentication, but that's not what i need. What i need is to be able to use self.scope['session'] in order … -
File upload button
I would like to have a file upload button for a models.ImageField. However, I don't want it to render with choose file:no file chosen. Instead, I would like a file upload button that pops up a select file button. Is this possible? -
Hi need a solution
I have deployed to post g res p g admin4 and deleted db. s q lite from Django. and set my allowed host =['*'] Am getting server [500]. if any help will be appreciated need a solution after deleting s q .lite d b from Django project and used allowed host to * . am getting 500 server request. LOOKING FOR SOLUTION AM NEW TO DJANGO -
How to add field variables from the HomePage to a stream StructBlock
Hi i have a doubt around how can i show info from the model page onto a block, specifically, a structblock. On my homepage model i have multiple charfields, where i store the link of the social media of the website, and i wish to know how can i print these links inside the template of a structblock on my streams, additionally i wish to know if this is possible too for an img, this is what i've tried so far: home/models.py class HomePage(Page): template = "home/home_page.html" landing_page_template = "home/home_page.html" social_media_display = BooleanField(blank=True, default=True) facebook_link = CharField(max_length=200, default="#") instagram_link = CharField(max_length=200, default="#") twitter_link = CharField(max_length=200, default="#") youtube_link = CharField(max_length=200, default="#") logo_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=False, on_delete=models.SET_NULL, related_name="+" ) Streams/blocks.py class FooterPlus(blocks.StructBlock): tlf = blocks.CharBlock(required=True, max_length=20, label="Tlf", default="+58") email = blocks.CharBlock(required=True, max_length=20, label="Email", default="") class Meta: template = "streams/parts/footer_plus.html" icon = "plus" label = "Footer plus" footer_plus.html <a href="{{self.facebook_link}}" class="list-group-item list-group-item-action"></a> -
how to get the foreignkey attribute value
I'm trying to print out the email related to a specific OrderItem for a Customer, even tho the email exists, it returns "None" instead, what part of my logic is wrong? #Models class Customer(models.Model): email = models.EmailField(max_length=150) class Order(models.Model): customer = models.ForeignKey(Customer) class OrderItem(models.Model): #View def test(): try: customer_email = OrderItem.objects.get(order__customer__email=['email']) except OrderItem.DoesNotExist: customer_email = None print(customer_email) -
Use Django Rest API to verify emails for new users in Flutter
We have made the email verification API thru Django, how do I implement it in Flutter? There are many tutorials using Firebase, but not many using Django. Thanks! I am expecting to use Django to send a verification email when a new user register an account -
Is it possible to send data from one form to multiple models in django using a normal form instead of multiple ModelForm?
I know it sounds weird, but I'm struggling a lot to show multiple tables with an inline, which populates three models with foreign keys, so I'm trying to find easier solutions than creating a script with JavaScript (which I don't know how to do) or a very complicated solution. My idea is to create a normal form with all of the fields and use it to fill all the models. class Order(models.Model): customer = models.ForeignKey("Customer", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ("-created",) def get_absolute_url(self): return reverse("sales:order-update", kwargs={"pk": self.pk}) def __str__(self): return "Order {}".format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) product = models.ForeignKey( Product, related_name="order_items", on_delete=models.CASCADE ) quantity = models.PositiveIntegerField(default=1) def __str__(self): return "{}".format(self.id) def get_cost(self): return self.price * self.quantity class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=15, null=True) email = models.EmailField() address_line_1 = models.CharField(max_length=250) address_line_2 = models.CharField(max_length=60, null=True) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) state = models.CharField(max_length=100, null=True) country = models.CharField(max_length=100, default="Mexico") def __str__(self): return f"{self.first_name} {self.last_name}" def get_absolute_url(self): return reverse("sales:modalcustomercreation") I only tried the first solution in [this stackoverflow question](https://stackoverflow.com/questions/5720287/django-how-to-make-a-form-for-a-models-foreign-keys) but It doesn't worked. -
ReactNative, Apollo and Django: upload files
I decided to learn such a technology as GraphQL. For this, I came up with an application (I develop it on ReactNative), a python backend (django-graphene). How the client chose Apollo. I set everything up, everything works, I even did a part already. And here I needed to upload a profile photo. The problem is that I haven't found a way to do this. I used to use the REST API and the client was axios. So I just took the FormData and passed it. Accordingly, the backend accepted and saved as usual. And here I don't even know where to start. I found the apollo-upload-client package, but I didn't find how to integrate it into ReactNative (more precisely, there is a description there, but I didn't understand how to use it correctly). I do it like this: const fileSubstitute = { uri: uriFromCameraRoll, name: "a.jpg", type: "image/jpeg", }; I found graphene-file-upload for the backend, it seems to see my files, but I don't know how to save them (by the way, I can transfer the file without apollo-upload-client). I really like GraphQL, but uploading files is a big deal. If I don't solve it, I will be forced abandon … -
how can I implement AJAX when i need to return a stored procedure function result in my views.py?
Im trying to implement ajax with a django app, specially with a view where I call a stored procedure to return a result -
Django, different result between `all()` method and `all().values()` method
I am facing this problem, where i can't access the url of some image using values() method, but it still can be accessed if it is a queryset object rather than a pythonic list: class MyModel(models.Model): img = models.ImageField(upload_to='media') # the image is stored in aws, hence it will produce a url def __str__(self): return f"{self.img.url}" this is example model, now let's try printing that on the shell: >>models.MyModel.objects.all() <QuerySet[{'img':'https://aws/bucketlist.com/some_img.png'}]> however with values() method: >>models.MyModel.objects.all().values() <QuerySet[{'img':'media/some_img.png'}]> ``` as you can see with `values()` i get the local path rather than the url to the aws cloud note that aws storage is set correctly in django. settings.py: DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = "/media" AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = "ap-southeast-2" AWS_S3_ADDRESSING_STYLE = "virtual" however, images are appearing on AWS and it seem to be fine on the cloud side. -
Alternatif to CSRF in Django
I run an Django app inside an iframe which is with php hosted on another server. All works except the POST request, I got error in Firefox only: Request failed with status code 403 > CSRF verification failed > CSRF cookie not set Previously i had Sameside warning which i solved by allowing Samesite secure in php script: PHP: ini_set('session.cookie_httponly',1); ini_set('session.use_only_cookies',1); $cookieParams = session_get_cookie_params(); $cookieParams[samesite] = "None"; $cookieParams[secure] = true; session_set_cookie_params($cookieParams); session_start(); Warning gone but sill cookie not passing over iframe, but present in Chrome. So i think i could skip the cookie then send it via Axios because i use Axios to send the request: JS: axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; const config = { headers: { 'method':'POST', 'accept': '*/*', 'content-type': 'application/json;charset=UTF-8', withCredentials: true, 'X-CSRFTOKEN': window.csrf_token, //csrfmiddlewaretoken: window.csrf_token } }; axios.post(url, datas, config).then((res) => {.... Settings.py: CSRF_TRUSTED_ORIGINS = ['https://myPhpsite.com', 'myPhpsite.com'] CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' CORS_ALLOW_CREDENTIALS = True After tying many things i'm thinking to disable the csrf by commenting 'django.middleware.csrf.CsrfViewMiddleware',. If I do it, is it an alternatif to csrf in order to get protected like csrf provide? -
How to design a database to make correction documents for sales invoices
How (simplified) to design a database/models to make correction documents for sales invoices? class Product(models.Model): title = models.CharField(max_length=50) class Invoice(models.Model): title = models.CharField(max_length=50) class InvoiceItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=5, decimal_places=2) class InvoiceCorrectionNote(models.Model): document = models.ForeignKey(Invoice, on_delete=models.CASCADE) class InvoiceCorrectionItem(models.Model): item = models.ForeignKey(InvoiceItem, on_delete=models.CASCADE) document = models.ForeignKey(InvoiceCorrectionNote, on_delete=models.CASCADE) original_quantity = models.DecimalField(max_digits=5, decimal_places=2) quantity_after_correction = models.DecimalField(max_digits=5, decimal_places=2) -
Attempting to read pk from url in django, but getting error NoReverseMatch at /
I am attempting to insert a link into my navbar (header.html - which is included in my base.html) which leads to the users profile. In order to provide the profile of the user who is currently logged in, I am attempting to use a primary key via the url. However, I am receiving the following error message: Reverse for 'url' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['profiles/show/(?P[0-9]+)/\Z'] I have a Profile model defined (shown below) with a OneToOne Relationship to my User model. I am wondering if I am trying to parse in the wrong pk reference in my header.html file. If so I think the issue will be on line 17 "Show Profile", but may also be in my view file? Something is definitely going wrong with my primary key, but am new to Django and cant work out what it is! Model: class Profile(models.Model): # Get access to create profile by default MALE = 'M' FEMALE = 'F' OTHER = 'O' UNSPECIFIED = "U" GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), (UNSPECIFIED, 'Prefer not to say'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20) bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, … -
Django's RSS framework having a AmbiguousTimeError:
I am on an old system using Django 1.8 and pytz 2013.9. We're using RSS and stumbled on a AmbiguousTimeError because of the following date: 2022-11-06 01:55:41.107437. It is an ambiguous time and turns out to haven at django.utils.timezone.make_aware: timezone.localize(value, is_dst=None) Since it's an ambiguous time and the source code is explicitly passing no DST, it can't figure out the date (shouldn't the framework figure out whether DST is applied or not through the timezone object?) This make_aware function is, in turn, also called from Django's RSS framework in django.contrib.syndication.Feed.get_feed. The timezone is: <DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD> How can I deal with this? The issue lies at the source code. I tried upgrading the package and it doesn't help. I am not able to upgrade Django (large upgrade process pending). -
Django get which models are children of this model
I want to know what models are children of a model. As I know like below if we have ownerModel which is parent of childModel1 and check1Model: import uuid from django.db import models class ownerModel(models.Model): ownerId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True) class check1Model(models.Model): checkId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True) owner=models.ForeignKey(ownerModel,on_delete=models.CASCADE) class childModel1(models.Model): childId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True) check2=models.ForeignKey(ownerModel,on_delete=models.CASCADE) then we can get what models are children of ownerModel with a code like this: class myView(views.APIView): def get(self, request, format=None): for f in ownerModel._meta.get_fields(): if 'field' in f.__dict__.keys(): print('***childModels***') print(f.__dict__) print() return Response({'0000'}, status=status.HTTP_200_OK) I mean by checking if the field key is in __dict__.keys() in items of ownerModel._meta.get_fields() ofc so like here we get extended info about children models: ***childModels*** {'field': <django.db.models.fields.related.ForeignKey: owner>, 'model': <class 'Users.models.ownerModel'>, 'related_name': None, 'related_query_name': None, 'limit_choices_to': {}, 'parent_link': False, 'on_delete': <function CASCADE at 0x00000286550848B0>, 'symmetrical': False, 'multiple': True, 'field_name': 'ownerId', 'related_model': <class 'Users.models.check1Model'>, 'hidden': False} ***childModels*** {'field': <django.db.models.fields.related.ForeignKey: check2>, 'model': <class 'Users.models.ownerModel'>, 'related_name': None, 'related_query_name': None, 'limit_choices_to': {}, 'parent_link': False, 'on_delete': <function CASCADE at 0x00000286550848B0>, 'symmetrical': False, 'multiple': True, 'field_name': 'ownerId', 'related_model': <class 'Users.models.childModel1'>, 'hidden': False} so I find these 2 conditions necessary to get child models info: in child models … -
Django query from multiple table base on FK
hi i am new in django coding i have 3 tables(models) in my different Django app , i try to make a simple report in htmpl page , so need to retrive specific data for each item base on foreign key. by below code i can accress machine stored table in Html page by making a loop , but i want to fetch data from other table and filter them , `{% for m in machines %} {{m.title}} {{}}. //i** need to access the ordertitle field in tb_order base on machine id. ??** {{ }}. // **access ordertitle in tb_order base on status field ??** {%end for %}` here is a **view.py ** `def allmachinesLOGO(request): machines=Machine.objects.all() context ={'machines':machines} return render(request,'pline/machineslogos.html',context)` **Models : ** class tb_order(models.Model): ordertitle= models.CharField(max_length=200) customer=models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) mould=models.ForeignKey(Mould, null=True, on_delete=models.SET_NULL, blank=True) status=models.CharField(choices=status_choices, default="0", max_length=20) accept=models.BooleanField machine=models.ForeignKey(Machine,null=True, on_delete=models.SET_NULL, blank=True) id =models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False, unique=True) class Machine(models.Model): title = models.CharField(max_length=200) machine_model = models.CharField(max_length=200, null=True, blank=True) description = models.CharField(max_length=600, null=True, blank=True) featured_image=models.ImageField(default="defaultmachine.webp", blank=True, null=True) id=models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False) advice a solution access ordertitle in tb_order base on status field ?? //** i need to access the ordertitle field in tb_order base on machine id. ??** -
Pass request user's username to Serializer from Viewset in Django Rest Framework
I want to pass the username of the logged in user from ListCreateAPIView to ModelSerializer to use object with same PrimaryKey from Clients model as a default, but i don't understand how to do it correctly. In views.py: class CartAPIList(generics.ListCreateAPIView): queryset = Clientcarts.objects.all() serializer_class = CartSerializer permission_classes = (IsAuthenticatedOrReadOnly, ) In serializers.py: class CartSerializer(serializers.ModelSerializer): client_id = serializers.HiddenField(default=Clients.objects.get(pk="username")) class Meta: model = Clientcarts fields = '__all__' Can you guys help me? -
how to select some value from multiple table in Django?
I want to to select some students from table A where students username and class code are not inside table B. So it will show all student that not inside the student class list yet. the query was like SELECT students from TableA WHERE username NOT IN tableB AND classcode = CODE models.py class modelStudentclassss m(models.Model): classcode = models.CharField(max_length=200, null=False, blank=False) username = models.CharField(max_length=200, null=False, blank=False) class modelUser(models.Model): username = models.CharField(max_length=200, null=False, blank=False) views.py studentclass = modelStudentclass.objects.all() studentdata = modelUser.objects.exclude(studentusername = studentclass.username).filter(role="student", classcode=classcode) -
Django TestCase doesn't rollback DB when atomic transaction fails
I need help with writing a unit test that tests atomic transactions I'm simply writing code that transfers money from a sender account to a receiver account by decreasing the amount of money from the sender and adding it to the receiver. I want to run the code in an atomic transaction because I want it to either all succeed or all fail. I want to write a test case that verifies that if the deposit function fails, the withdrawal should also be rolled back and the balance of the sender should stay the same. The problem is that the test case fails as it shows that the sender balance is decreased although it should be rolled back. Any help? here's a small snippet of what I want to achieve import pytest from cards.models import Card, Account from unittest.mock import patch def perform_atomic(txn, sender_account, receiver_account, amount): try: with transaction.atomic(): sender_account.balance -= 1000 sender_account.save() receiver_account.deposit(amount) except Exception as error: txn.status = Transaction.TRANSACTION_STATUS_FAILED txn.save() logger.error(f"Failed Action. Reason[{error}]", exc_info=True) raise error # Test case @patch.object(Account, "deposit") def test_atomicity_when_deposit_fails(self, deposit_mock): deposit_mock.side_effect = ValidationError("deposit failed") self.sender_account.balance = 300.0 self.sender_account.save() # Balance before attempting to transfer before_sender_balance = self.sender_account.balance with pytest.raises(ValidationError, match="deposit failed"): perform_atomic(self.transaction, self.sender_account, self.receiver_account, … -
Django custom form - cleaned_data has incorrect values for IntegerField
In my Django app (v. 3.1), I've added a custom form to trigger a data export that, among other things, can collect two integer values that represent years in a date range. When the form is submitted, no matter what values the user has set in the number fields, the values that appear in the form's cleaned_data attribute are the values that were set as initial for those fields on the definition of the form class. For example, the initial value of the field should be 2022 - but no matter what value the user sets in the input, the value in form.cleaned_data for the field is 2022. A ChoiceField in the form works as expected, and I'm pretty inexperienced with Django - so I can't quite figure out what I've done wrong here. Here's a slightly simplified version of the code... observation/forms.py: from django import forms import datetime export_formats = [ 'csv', 'xls', 'xlsx', ] export_format_choices = [(f, f) for f in export_formats] min_year = 1950 class ExportForm(forms.Form): current_year = datetime.datetime.now().year export_format = forms.ChoiceField(required=True, label='Format', choices=export_format_choices) year_from = forms.IntegerField(required=False, disabled=True, min_value=min_year, max_value=current_year, initial=current_year) year_through = forms.IntegerField(required=False, disabled=True, min_value=min_year, max_value=current_year, initial=current_year) def __init__(self, *args, **kwargs): super(ExportForm, self).__init__(*args) admin.py def export_view(self, …