Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO form from models - select options from ajax jquery
I can't find in DJANGO docs solutions. I have a form with two select fields (Foreign key). Django automatically create options from models, but i want second field is filled with ajax, depending on what we choose in the first field. For now I do in document ready $('#id').find('option').remove().end() but it's not elegant at all ;) How to set DJANGO form not to fetch data for a specific field automatically? -
how to increase amount if date and time greater than 24 hours in Django?
**My booking views.py file. ** def booking(request): context = { 'amount': 100 } ** my booking.html** <p>Amount = RS {{amount}} </p> **I want to increase this amount.** I want to increase the above mention amount when user select data and time greater than 24 hours. if your do so then the amount increase automatically. -
Calling WebSocket Class Function from view is not working in Django Rest Framework
I wanted to call a function from the consumer file function receive. I'm using that method. but this is not working. this is a consumer.py class ChatConsumer(AsyncWebsocketConsumer): def getUser(self, userId): ... Some Code def saveMessage(self, message_obj): ... Some Code async def connect(self): ... Some Code async def receive(self, text_data, type='receive'): ... Some Code async def chat_message(self, event, type='chat_message'): ... Some Code async def disconnect(self, close_code): ... Some Code this is a serializers.py class CreateChatMessageView(APIView): cls_consumers = consumers.ChatConsumer() channel_layer = get_channel_layer() message_obj.save() chat_message_serializer = CreateChatMessageResponseSerializer(message_obj) async_to_sync(channel_layer.group_send)( str(message_obj.chat_room.id), { 'type': 'receive', 'message': chat_message_serializer.data } ) print("Ok") ... Some Code -
How to consume messages from Kafka consumer to Django app in new docker container?
The Django server is going stuck if Kafka-comsumer starts. What should I do? I want to run this consumer as a sidecar container. Can anyone help me? consumer = KafkaConsumer("my-topic", bootstrap_servers=\['{}:{}'.format(HOST, PORT)\],auto_offset_reset="earliest", value_deserializer=lambda x: ReadHelper().json_deserializer(x), group_id="my_consumer_group" ) for msg in consumer: print(msg) -
How To Automatically Create Objects Of Django Model While Creation Another Model Objects
I Want To Create Object For "ProductOut" Model When "CusOrder" Model Is Being Created Here Is My Code class CusOrder(models.Model): cus_name = models.CharField(max_length=100) cus_number = models.CharField(max_length=11) product = models.ManyToManyField(Product) qty = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) def __str__(self): return self.cus_name def save(self,*args,**kwrgs): ProductOut.objects.create( refrence=self.cus_number, stock_out = self.qty, sell_price = self.sell_price, product = self.product.P_name ) super(CusOrder,self).save(*args,**kwrgs) class ProductOut(models.Model): refrence = models.ManyToManyField(CusOrder) stock_out = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) product = models.ForeignKey(Product,on_delete=models.CASCADE) def __str__(self): return self.refrence.cus_number But I am Getting a ValueError which Is '"<CusOrder: Asif>" needs to have a value for field "id" before this many-to-many relationship can be used.' When I want to save a CusOrder Object here Is My Whole class Catagory(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class Product(models.Model): P_name = models.CharField(max_length=30) stock_in = models.IntegerField(default=0) unit_price = models.IntegerField(default=0) cata = models.ForeignKey(Catagory, on_delete=models.CASCADE) def __str__(self): return self.P_name class CusOrder(models.Model): cus_name = models.CharField(max_length=100) cus_number = models.CharField(max_length=11) product = models.ManyToManyField(Product) qty = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) def __str__(self): return self.cus_name def save(self,*args,**kwrgs): ProductOut.objects.create( refrence=self.cus_number, stock_out = self.qty, sell_price = self.sell_price, product = self.product.P_name ) super(CusOrder,self).save(*args,**kwrgs) class ProductOut(models.Model): refrence = models.ManyToManyField(CusOrder) stock_out = models.IntegerField(default=0) sell_price = models.IntegerField(default=0) product = models.ForeignKey(Product,on_delete=models.CASCADE) def __str__(self): return self.refrence.cus_number class ReturnedProduct(models.Model): cus_number = models.ForeignKey(CusOrder,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) qty … -
How to create custom Response in drf generic ListAPIView
I'm showing reviews of each products, so If a product don't have a review yet then i want to show a response like there 'No reviews yet" class ShowReviews(generics.ListAPIView): serializer_class = ReviewSerializer filter_backends = [filters.DjangoFilterBackend, OrderingFilter] filterset_class = ReviewFilter ordering_fields = ['rating', 'id'] lookup_field='product_slug' def get_queryset(self): slug = self.kwargs['product_slug'] return ReviewRatings.objects.filter(product__slug=slug, is_active=True) And please share the link if anything mentioned about this in docs because I'm unable to find any solutions. -
killing docker container from docker desktop
Created an django app and dockerize it and then before I stopped the container I removed the app and then I could not remove the container yet Can you help me please to remove docker container once I clicked remove button it says that removing container from docker -
Long Processing within Django ModelAdmin Form
I have a custom form in a admin.ModelAdmin where I use to upload some CSV data with a file upload. Sometimes, processing this CSV file takes longer than the HTTP Worker timeouts will allow, forcing me to split up the CSV file into smaller chunks that will not trip the worker timeouts. I need to find a way to avoid splitting up the CSV into separate chunks to upload one at a time. I was researching how I might resolve this issue, and I am having a hard time finding any resources I might be able to learn from, like a tutorial. What are some common patterns and best practices when I need to do something long-running (>30s) in Django Admin? I am looking for pointers, guides, and tutorials. Thank you! -
How to include the start date and end date while filtering in django
views.py if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) check_box_status = request.POST.get("new_records", None) print(check_box_status) drop_down_status = request.POST.get("field") print(drop_down_status) if check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)) The following code get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)) is unable to include the t_date. Is there any solution to include the t_date. -
Object created in view isn't rendering in template
I'm creating a new object in a view through an external function. This is the code: def index(request): sousei = suii_scratch(SOUSEI_URL) s_jikan = sousei[0] s_suii = sousei[1] sousei_obj = Sousei.objects.create(jikan=s_jikan, suii=s_suii) #print(sousei_obj) context = { sousei_obj : 'sousei', } return render(request, 'index.html', context) The external function is returning two values, that are being catched in s_jikan and s_suii variables. These variables are then used to create a new object (the model has only this two fields). If I uncomment the print statement, I get printed the __str__ method of the model with the newly obtained data from the external function. Also, if I check the admin, the new record in the database is beign saved correctly. Until here seems everything is working fine, but when passing the created object to the template I can't get it rendered. This is template code: {% if sousei %} <p>{{sousei.jikan}}</p> <p>{{sousei.suii}}</p> {% else %} <p>No data.</p> {% endif %} But I keep getting there is no data. What am I missing? -
How to create a class that can handle request data
I will have a input data that look like this (will be POST by postman) { "COMMAND_ID":"56789", "CARRIER_ID":"HF2202109W061", "CURR_GRP":"", "CURR_DEV":"", "CURR_LOC":"FAKE1-1", "DEST_GRP":"", "DEST_DEV":"", "DEST_LOC":"FAKE2-1", "MOVE_PRIORITY":"50" } and my views.py look like this class PalletMoveAPI(APIView): authentication_classes = [SessionAuthentication , BasicAuthentication] permission_classes = [IsAuthenticated,] def post(self,request,format=None,*args,**kwargs): try: inputdata = request.data testdata= { "DATAID":"", "CommandID":inputdata["COMMAND_ID"], "Priority":inputdata["MOVE_PRIORITY"], "Replace":0, "VehicleID":"", "CarrierID1":inputdata["CARRIER_ID"], "WCount1":inputdata["WAFER_QTY"], "SourcePort1":inputdata["CURR_LOC"], "DestPort1":inputdata["DEST_LOC"], "CarrierID2":"", "WCount2":"", "SourcePort2":"", "DestPort2":"" } pallet_move = requests.post('http://10.13.10.43:10000/api/command/send',json= testdata) if pallet_move.status_code in [HTTPStatus.OK,HTTPStatus.CREATED]: event = Post_successed() return JsonResponse({"code":event.code,"detail":event.description},status=event.status,safe=False) except Exception as e: event = Error(str(e)) return JsonResponse({"code":event.code,"detail":event.description},status=event.status,safe=False) how can i create a class or function to handle to include the request part. like i wan to make that part reusable. a class that can take in request data and then return as the 'testdata' format shown above -
DRF CreateModelMixin with additional fields
I'm using GenericAPIView with the CreateModelMixin to create a model instance. I need my serializer to add additional fields that aren't defined by the user. My Serializer.create method is already set up for this, but I don't know how to pass fields through to the CreateModelMixin.create method. Here's a minimal version of what I have: class Foo(mixins.CreateModelMixin, generics.GenericAPIView): permission_classes = [IsAuthenticated] def get_serializer_class(self): return FooSerializer def post(self, request): return self.create( request, requester=request.user # Additional field ) This doesn't work - the requester field isn't passed to FooSerializer.save, so FooSerializer throws an error when it attempts to access requester in FooSerializer.create. Before, I was using APIView and calling the serializer directly, so I could simply: serializer = FooSerializer(data=request.data) if serializer.is_valid(): foo = serializer.save(requester=request.user) Is there any way to achieve this with the GenericAPIView? I want to embrace DRF's DRY-ness and avoid calling serializers in every endpoint method. -
Why do I keep getting 403 error in Django after using csrftoken in Ajax POST call?
I am doing an Ajax POST request to get news articles. I have put a csrftoken in the headers, but I still keep getting a 403 error. I have looked online and have tried many solutions, but I keep getting a 403 error. Why is this? $('#search-articles').on('submit', function(event) { event.preventDefault(); document.getElementById("loading").style.display = "block"; document.getElementById("search-bar").style.display = "none"; document.getElementById("articles").style.display = "none"; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $.ajax({ url: "{% url 'stocks_sites:get_news_articles' %}", type: "POST", data: { "q": document.getElementById("search-articles").value, csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val() }, headers: { "X-CSRFToken": getCookie("csrftoken"), // don't forget to include the 'getCookie' function }, success: function(response) { document.getElementById("loading").style.display = "none"; document.getElementById("search-bar").style.display = "block"; document.getElementById("articles").style.display = "block"; $("#search-bar").html(response[0]); $("#articles").html(response[1]); } }) }) -
Django, pandas, excel: uploading files, parsing them with pandas in Django
I have a big command-line script for parsing data in Excel (with pandas) and I want to wrap it with Django. I've tried both uploading files thru request.FILES and pandas, but get stuck on uploading file and, for example, saving it (not necessarily but just to check the upload for now). Haven't had any problems with other apps on Django which didn't require uploading and parsing anything external and thought that would be much easier..:) I've also tried Redirecting, doesn't really work, the only redirect which is actually happening is action in the form tag.. Here are the code snippets: views.py: def uploads(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['document'] excel_file.save() return render(request, 'index.html') else: form = DocumentForm() return render(request, 'index.html', {'form': form}) models.py class Document(models.Model): document = models.FileField(upload_to="files/") forms.py: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) index.html: <form action="{% url 'reports'%}" method="post" enctype="multipart/form-data" > {% csrf_token %} <span> Upload .xlsx file <input type="file" name="document" /> </span> <button type="submit"> SUBMIT </button> </form> -
How to use objects.create to add a file field from dataframe.to_csv?
I have used this code to try to add a dataframe.to_csv to a django db FileField, but it only works when I dont specify its path, so anyone know how to overcome this, I must specify its path and name it. Thats my code df = pd.DataFrame(profile_names, columns=['username', 'followers', 'tweets', 'hashtags', 'MostRecent']) Scrape.objects.create( user=request.user.profile, name=keyword, csvfile=df.to_csv(f'./static/assets_new/CSV/{request.user} - {keyword}.csv') ) Im trying to add a csv file to django db filefield, but nothing gets added instead -
Django query working locally but not in production
I have created a query in django that I am passing in an ID and receiving and object back from my model. On my local machine it works as expected. When I am trying to use it in my staging environment it is not returning any data but I have confirmed that the data exists in my database and have printed out all of the requests to make sure I am passing the information properly. When printing out my query I receive "<SoftDeletableQuerySet []>" in my AWS logs. I've tried logging everything, I've confirmed that the data exists. I've recreated everything so that it is the same in production as it is in my local environment. At this point I am not sure how to troubleshoot this anymore. code below for reference class GetStripeCustomer(rest_framework.generics.ListCreateAPIView): permission_classes = () serializer_class = serializers.StripeSerializer def get_queryset(self, *args, **kwargs): print('getting user stripe info', self) print('self.request', self.request) print('self.request.user', self.request.user) print('user_id', self.request.user.id) # print('user_id', self,request.user['id']) user = models.Stripe.objects.all().filter(user_id=self.request.user.id) print('user', user) for customer in user: print('customer', customer) # if (self.request.user.id == None): print('this should have the user', models.Stripe.objects.all().filter(user_id=self.request.user.id)) # return models.Stripe.objects.all() # else: return models.Stripe.objects.all().filter(user_id=self.request.user.id) -
AttributeError: 'function' object has no attribute 'split_contents'
im trying to set swagger in my django restAPI by this guide: https://krakensystems.co/blog/2017/swagger-integration-with-django-rest-framework but i get an error : `AttributeError: 'function' object has no attribute 'split_contents' can anyone help me? in my pycharm the import is not beeing used so idk how that make sense from rest_framework.documentation import include_docs_urls schema_view = get_swagger_view(title="Swagger Docs") url(r'^docs/', schema_view) try install swagger -
Django file structure with react
I am new to Django and react. I am following the guide below and I have run into an issue. I think my file structure is the issue. The Guide I am following The file structure in the guide is ├── manage.py ├── mysite │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── myapp <----- a normal Django app │ ├── __init__.py │ ├── models.py │ ├── urls.py │ └── views.py ├── assets <----- our front-end project source │ ├── javascript │ └── styles ├── static <----- our front-end project outputs (and other Django static files) │ ├── css │ ├── images │ └── js └── templates <----- our Django template files └── myapp and my file structure is: |myproject ├── manage.py ├── .gitignore ├── package-lock.json ├── package.json ├── webpack.config.js │ ├── node_modules │ ├── ..... ├── myproject │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── myapp │ ├── __init__.py │ ├── models.py │ ├── urls.py │ └── views.py ├── js │ ├── index.js ├── static │ ├── css │ ├── images │ ├── js | ├── index-bundle.js └── templates ├── myapp ├── hello_webpack.html I have followed the guide step by … -
Django How to call a function inside template with credential arguments?
I have a function which gets all email addresses from a mail server. Currently I have 3 variables stored in my .env file (host, email and password) for each mail server (I have 3 different) and then writing the function FOR EACH MAILSERVER. On the template, I have 3 buttons that get emails from the 3 mail servers, each button different function. This was done in testing but now I'd like to have the 3 buttons in my Django template to call just ONE function with different credentials (stored on my .env file). Is there any way to call one function with different parameters from my django template? -
Django Custom Commands: Will writing to SQLite DB with a custom command while the server is running fail due to File Lock?
I would like to keep the django server running as I call some custom commands that will read / write to the sqlite DB. However I'm nervous that this may conflict due to the main server locking the database file. Is this cause for concern ? I can't use PostgreSQL or MySQL. I tried this and it didn't throw any errors, however I would like to know if this is something that can occur. -
Why is Django test cases checking actual DB and raising IntegrityError instead of just running in-memory?
When I run my tests with the DB empty (the actual application DB), everything goes fine. But when the DB has data, Django raises an IntegrityError for basically every test. The stact trace looks like the following (but for every test): ====================================================================== ERROR: test_api_get_detail (core.projects.tests.test_project_api.ProjectConfidentialPrivateAPITests) Getting confidential object via API (GET) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/ramonkcom/Desktop/management/management-backend/venv/lib/python3.10/site-packages/django/test/testcases.py", line 299, in _setup_and_call self._post_teardown() File "/Users/ramonkcom/Desktop/management/management-backend/venv/lib/python3.10/site-packages/django/test/testcases.py", line 1199, in _post_teardown self._fixture_teardown() File "/Users/ramonkcom/Desktop/management/management-backend/venv/lib/python3.10/site-packages/django/test/testcases.py", line 1461, in _fixture_teardown connections[db_name].check_constraints() File "/Users/ramonkcom/Desktop/management/management-backend/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 383, in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'custom_fields_customfield' with primary key '1' has an invalid foreign key: custom_fields_customfield.definition_id contains a value '1' that does not have a corresponding value in custom_fields_customfielddefinition.id. At first I thought this was a problem with my fixtures. But they work just fine to set up the application basic data. The DB seems to be the key issue: if it has data, the tests crash, if it's empty, the tests work. The most weird part is that the error being raised doesn't match with reality, and by that I mean: the CustomFieldDefinition object with pk=1 exists in the DB. Anyway, it shouldn't matter, since I expect Django to build an in-memory DB … -
Django: Force create index on ForeignKey fields when db's `supports_foreign_keys=False`
I'm trying to use Django (v4.1.3) with Planet Scale's DB which is MySQL compliant with the relevent exception of not supporting foreign keys. For this, they provide a Django DB driver which subs class the MySQL DB feature class from django.db.backends.mysql.features import \ DatabaseFeatures as MysqlBaseDatabaseFeatures class DatabaseFeatures(MysqlBaseDatabaseFeatures): supports_foreign_keys = False Given this, when I generate migrations and apply them on my local MySQL server, I don't see any foreign keys being created as expected. However, I also don't see keys being created but I still want the keys. For example with the MySQL driver, when I run SHOW CREATE app_user_groups (from django.contrib.auth package) I see the following key: CREATE TABLE `auth_group_permissions` ( ... KEY `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` (`permission_id`), ) But with the Planet Scale driver (supports_foreign_keys = False), Django doesn't create an key/index. I know in my models, I can explicitly define keys but I don't find this ideal. In addition, I don't have control over models from other Django apps like django.contrib.auth and many other 3rd party ones. What can I do to make Django create keys on django.db.models.ForeignKey despite support for foreign keys being off. -
Understanding permissions in Django
I trying to understand permissions in Django. In the points below I wrote what I was able to find on this issue and how I understand it. Maybe someone will be able to tell me if I am thinking correctly or if it works in a different way. I will be grateful for additional articles on this topic. Thanks! 1. APIView with built-in permissions Django has some built-in permissions that we can use in APIView through permission_classes. class OrderView(APIView): permission_classes = [permissions.IsAuthenticated] We can add the following built-in permissions to permission_classes, because they don’t have has_object_permission: AllowAny, IsAuthenticated, IsAuthenticatedOrReadOnly, IsAdminUser, DjangoModelPermissions, DjangoModelPermissionsOrAnonReadOnly 2. APIView with custom permissions Let’s say that we want to use the custom permission from the point 1 in APIView. Can we use permission_classes in that case? class OrderView(APIView): permission_classes = [permissions.IsAuthenticatedAndOwner] I don’t know which object will be sent to has_object_permission and how to do it. Is it a good way? def has_object_permission(self, request, view, obj): # <-- obj return obj.user == request.user 3. APIView with check_permissions and check_object_permissions. I am a little confused about the methods. If I understood correctly these methods are used to call has_permission and has_object_permission from APIView? Is there a different … -
Django: Using F expression of an IntegerField to annotate a DateField
I have a model like this: class RentDue(models.Model): balance = DecimalField() day_due = IntegerField() # e.g. 1-5, representing the 1st through 5th of the month I want to be able to annotate a queryset using the integer from day_due to create a new attribute rent_due_date so that I can filter on the next month's due date like this: from datetime import date, timedelta # create RentDue instances -- one due on the 1st another on the 3rd rent_due_first = RentDue.objects.create(day_due=1) rent_due_third = RentDue.objects.create(day_due=3) # query for all RentDue on the 1st or earlier RentDue.objects.annotate( rent_due_date=date(2022, 12, F('day_due')) ).filter( rent_due_date__lte=date(2022, 12, 1) ) # -> returns [rent_due_first] # query for all RentDue on the 3rd or earlier RentDue.objects.annotate( rent_due_date=date(2022, 12, F('day_due')) ).filter( rent_due_date__lte=date(2022, 12, 3) ) # -> returns [rent_due_first, rent_due_third] However, passing in the F expression to date raises TypeError: an integer is required (got type F) I've tried using ExpressionWrapper as laid out in this answer as well as TruncDate but I'm getting some weird errors I don't quite get. A possible solution would be to annotate the entire queryset with DateField of next_month (hard-coded to date(2022, 12, 1) and then being able to use that in an F … -
How to display a list of children objects on detail view for Django Admin?
I have two models: Setting and SettingsGroup. When someone clicks on a specific SettingsGroup in the Django Admin and the edit/detail page appears I'd like for the child Setting objects to be displayed but as a list not a form. I know that Django has InlineModelAdmin but this displays the children as editable forms. My concern isn't with the child objects being editable from the parent object but rather the amount of space it consumes. I'd rather have a list with either a link to the appropriate child record or that changes a particular object to be inline editable. Here is my Setting model: class Setting(models.Model): key = models.CharField(max_length=255, blank=False) value = models.TextField(blank=True) group = models.ForeignKey('SettingsGroup', blank=True, on_delete=models.SET_NULL, null=True) def __str__(self): return str(self.key) And the SettingsGroup model: class SettingsGroup(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) def __str__(self): return str(self.name) The method I don't want to use (or need to find a different way to use) is InlineModelAdmin which appears in my admin.py currently as: class SettingsGroupInline(admin.StackedInlin): model = Setting fk_name = 'group' @admin.register(SettingsGroup) class SettingsGroupAdmin(admin.ModelAdmin): inlines = [ SettingGroupsInline, ] Here is an example of how I'd like it to work: There is a MySettings object, an instance of the …