Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My app 127.0.0.1:8000 is not loading in browsee
I created a todo notes app from geek for geeks and tried to run it, compilation wasn't wrong but the final app link 127.0.0.1:8000 isn't running in browser I tried it in various browser it's still same -
OperationalError at /admin/store/product/ , no such column: store_product.product_name"
I try to create an simple e-commerce site , the model is registered , I did makemigrations and migrate as well , it runs the server and also the model shows on admin panel , but whenever I try to click that it shows the error " OperationalError at /admin/store/product/ no such column: store_product.product_name" but if I click on "+add" button of the side it works , and in order to saving the product information it throws also same error .... I did makemigrations , migrate , sqlflush and syncdb .. but none of this works ... help me -
Django Code Repetition due to Multiple objects in JSON
I have the following code which works as expected i.e saves data to the db as I would like it to, however, there is a lot of code repetition and I am unable to find a way to shorten the code I have about 30 serializers (pasting 3 to shorten the code) class FirstOne(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = FirstOne fields = ['decimals', 'unitRef', 'value', 'period'] class SecondOne(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = SecondOne fields = ['decimals', 'unitRef', 'value', 'period'] class ThirdOne(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = ThirdOne fields = ['decimals', 'unitRef', 'value', 'period'] class CashFlowSerializer(serializers.ModelSerializer): FirstItemInJson = FirstOne(many=True) SecondItemInJson = SecondOne(many=True) ThirdItemInJson = ThirdOne(many=True) class Meta: model = Basetable fields = "__all__" def create(self, validated_data): itemOneData = validated_data.pop('FirstItemInJson') itemTwoData = validated_data.pop('SecondItemInJson') itemThreeData = validated_data.pop('ThirdItemInJson') cashflow = Basetable.objects.create(**validated_data) for data in itemOneData: period_data = data.pop("period") dataObj = FirstItemModelClass.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( firstItem_id=dataObj, **period_data) for data in itemTwoData: period_data = data.pop("period") dataObj = SecondItemModelClass.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( secondItem_id=dataObj, **period_data) for data in itemThreeData: period_data = data.pop("period") dataObj = ThirdItemModelClass.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( thirdItem_id=dataObj, **period_data) JSON: (trimmed to keep it shorter) jsonToUse = { "CompanyId": "320193", "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": … -
How to access form object before and after saving in django-bootstrap-modal-forms
I have following code in my view of adding a new Item. Some fields are filled via user some fields are filled in the background. If form is valid then user is redirected to a url with a parameter (slug) from added object. How can I convert this code to django-bootstrap-modal-forms way? def category_view(request, slug, *args, **kwargs): ... if request.POST: form = CreateItemForm(request.POST) if form.is_valid(): if not request.user.is_authenticated: raise PermissionDenied() obj = form.save(commit=False) obj.created_country = Constants.country_code obj.created_by = request.user obj.save() return redirect('category:item_detail', slug=obj.slug) -
Catch-all field for unserialisable data of serializer
I have a route where meta-data can be POSTed. If known fields are POSTed, I would like to store them in a structured manner in my DB, only storing unknown fields or fields that fail validation in a JSONField. Let's assume my model to be: # models.py from django.db import models class MetaData(models.Model): shipping_address_zip_code = models.CharField(max_length=5, blank=True, null=True) ... unparseable_info = models.JSONField(blank=True, null=True) I would like to use the built-in serialisation logic to validate whether a zip_code is valid (5 letters or less). If it is, I would proceed normally and store it in the shipping_address_zip_code field. If it fails validation however, I would like to store it as a key-value-pair in the unparseable_info field and still return a success message to the client calling the route. I have many more fields and am looking for a generic solution, but only including one field here probably helps in illustrating my problem. -
Real time data Python
I want to observe data changes in real time in python to create a program that show list of online friends (i.e. every time a friend become online or offline I want update a list). I have a function that make an infinite loop to receive the presence a from am XMPP server. I can’t understand how can update Every time i receive new data. while True: response = sock.recv(1024) -
How to convert POST PascalCase json to snake_case in Django Rest Framework?
I have a DRF API endpoint that accepts python snake_case payloads: { "sample_id": "", "notes": "", "patient_id": "", "dob": "", "scan_model": { "current_time_left": "", "scan_state": null, "timer_configuration": { "timer_interval": null, "timer_length": "", "warning_span": "", "window_of_opportunity": "" } } How to get the endpoint to accept a json with keys in PascalCase like this: { "SampleId": null, "Notes": null, "PateintId": "testid", "DateOfBirth": "05/11/1995", "ScanModel": { "Id": 1, "CurrentTimeLeft": "00:00:00", "ScanState": 6, "TimerConfiguration": { "TimerInterval": 200, "TimerLength": "00:15:00", "WarningSpan": "00:02:00", "WindowOfOpportunity": "00:05:00" } } I am using Django 4.1, DRF 3.14 and python 3.11 Thanks! -
How to let user download a file after the process is completed in Django?
I am a beginner in Django. I am trying to let user download a file after the specific process is completed. Here is view.py. The download button is shown after the process is completed. Users can download the file named WS_file_name+'.xlsx' by clicking the download button. from django.shortcuts import render from django.http import HttpResponse def index(request): if request.method == 'POST': student = StudentForm(request.POST, request.FILES) if student.is_valid(): handle_uploaded_file(request.FILES['file']) firstname= student.cleaned_data.get("firstname") lastname= student.cleaned_data.get("lastname") ### Processing ### WS_file_name = lastname + firstname + newfile Toollist_Raw = pd.read_excel(Toollist_path+Toollist_file_name) WS_file = xlsxwriter.Workbook(WS_file_name+'.xlsx') WS_file.close() file_source = WS_Path + WS_file_name+'.xlsx' Toollist_Raw.to_excel(file_source, sheet_name='CALM_Toollist',index=False) ### Process had completed, users can click download button to download the file ### context= {'username': firstname, 'version':lastname,} return render(request, 'template_Download.html', context) else: student = StudentForm() return render(request,"template_Form.html",{'form':student}) ##### Download Functions ##### import os from django.http import FileResponse def download_file(request): # Define Django project base directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Define file name filename = WS_file_name+'.xlsx' # Define the full file path filepath = BASE_DIR + '/Capital_Report_Website/Download_Files/Baseline_Cleanup_Toollist_vs_CALM_Download/' + filename +'.xlsx' return FileResponse(open(filepath, 'rb'), as_attachment=True) The below code is template_Form.html. This page is to let user fill in the information which is used to process the file. <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p … -
im want when user click profile pass to profile.html
i want to user when click profile pass user to profile.html but problem i don't solve hem --------- path path('home', views.home, name="home"), path('profile/<int:id>', views.profile_views, name="profile_views") -------- models class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) music = models.CharField(max_length=50) skils = models.CharField(max_length=50) search = models.CharField(max_length=50) posts = models.CharField(max_length=50) boi = models.TextField() img = models.ImageField(upload_to="profile-img") def __str__(self): #return self.user or 'User' return str(self.id) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) ------- views def home(request, id): pro_id = profile.objects.get(id=id) context = {'pro_id' : pro_id} return render(request, 'main-frond.html') def profile_views(request, id): ff = profile.objects.get(id=id) context = {'ff' : ff} return render(request, 'profile.html', context) ------ html <br> <a href="{% url 'profile_views' pro_id.id %}">profile</a> <br> <hr> {{request.user}} <hr> <a href="{% url 'login' %}" id="login-register" style="float: right;">Login</a> <a href="{% url 'register' %}" id="login-register">Register</a> where's the problem i want to user when click profile pass user to profile.html but problem i don't solve hem -
Error in pytest with django response codes
I am using pytest to test my django rest framework API and am gettin gan error on the following test: def test_client_gets_invalid_when_submitting_invlaid_data(self): client = APIClient() response = client.post(path="/user/register/", data={}) assert response.status_code is 400 traceback in pytest is as follows: > assert response.status_code is 400 E assert 400 is 400 E + where 400 = <Response status_code=400, "application/json">.status_code core\tests\test_views.py:26: AssertionError I dont understand how this error can be happening when 400 is literally equal to 400? -
Can I intersect two Queryset of same table but with different query?
minimum_likes_queryset = PostInLanguages.objects.annotate(likes=Count('like_model', distinct=True)).filter(likes__gte=minimum_likes) recouched_posts_ids = PostInLanguages.objects.values('parent_post_language_id').annotate(recouch_count=Count('parent_post_language_id')).filter(recouch_count__gte=minimum_recouch, is_post_language=False).order_by().values_list('parent_post_language_id', flat=True) recouched_post_queryset = PostInLanguages.objects.filter(id__in=recouched_posts_ids) this is the query SELECT "api_postinlanguages"."id", "api_postinlanguages"."post_in_language_uuid", "api_postinlanguages"."post_id", "api_postinlanguages"."language_id", "api_postinlanguages"."is_post_language", "api_postinlanguages"."parent_post_language_id", "api_postinlanguages"."description", "api_postinlanguages"."created_on", COUNT(DISTINCT "api_postlanguagelike"."id") AS "likes" FROM "api_postinlanguages" LEFT OUTER JOIN "api_postlanguagelike" ON ("api_postinlanguages"."id" = "api_postlanguagelike"."post_language_id") GROUP BY "api_postinlanguages"."id" HAVING COUNT(DISTINCT "api_postlanguagelike"."id") >= 1 SELECT "api_postinlanguages"."id", "api_postinlanguages"."post_in_language_uuid", "api_postinlanguages"."post_id", "api_postinlanguages"."language_id", "api_postinlanguages"."is_post_language", "api_postinlanguages"."parent_post_language_id", "api_postinlanguages"."description", "api_postinlanguages"."created_on" FROM "api_postinlanguages" WHERE "api_postinlanguages"."id" IN (SELECT U0."parent_post_language_id" FROM "api_postinlanguages" U0 WHERE NOT U0."is_post_language" GROUP BY U0."parent_post_language_id" HAVING COUNT(U0."parent_post_language_id") >= 1) this is the exception An exception occurred: column "api_postinlanguages.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT COUNT(*) FROM (SELECT "api_postinlanguages"."id" AS "... ^ -
How are clean_<fieldname>() methods defined/generated in django Forms?
I'm currently trying to understand how forms validation works in Django (version 3.2.4). In order to achieve that I'm reading the framework's source code. But despite searching for it I didn't find where (nor how) are the clean_<fieldname>() methods generated. The only thing I found is where it's used (django/forms/forms.py::BaseFormL392). Where are these methods defined? -
Django Joins Query to Get Objects based on the other table
I have the three Django models as following: Product Model (Has product related information) Channel Model (Has channel information like Location and Everything) ProductChannelListing (Which product available in which channel) I want to make a query on products with the channel ID and get all the products which are marked available in that channel. -
Error in using the passed data from redirect into the function we are redirecting to the new view in Django App?
I am passing a variable using redirect in Django but when I am trying to print the variable into another view using request.GET it is showing as - <QueryDict: {}> in request.GET which means there is no dictionary passed - Here is my code - def add_prompt(request): email='abc@gmail.com' return redirect('/content/',{'email_id':email}) Here is the code for the content function - def content(request): print(request.GET) return render(request,'abd/content.html') Output on the console - <QueryDict: {}> If I use request.GET.get('email_id') - Output - None -
Slack bot api requests and my server requests are not running at a time
I created a slack bot app using Django. In this app, the bot will ask some questions to the users within a given schedule(periodically) from the database. The bot will wait for the reply of the users. This is how I am calling the slack API to ask the questions concurrently, at a time. I used async and await in the function. async def post_async_message(channel, message): """ broadcast message in the given channel asynchronously """ try: response = await Async_Client.chat_postMessage( channel=channel, text=message ) if response['ok']: await asyncio.sleep(Wait_For_Answer) except SlackApiError as e: raise CustomError(f"Error occurred: {e}", e.response) This is the function from where the post_async_message function has been called. async def post_standup_message(standup_id): participants = await models.get_participants(standup_id) questions = await models.get_standup_questions(standup_id) async def ask_question(user_id): # send standup question to the user async for question in questions: try: await views.post_async_message(user_id, question.Question) except CustomError as e: print(e) tasks = [ask_question(participant.Slack_User_Id) async for participant in participants] for completed_task in asyncio.as_completed(tasks): await completed_task asyncio.run(post_standup_message(49)) Everything is doing good. But one thing that I notice is that during the asking of the questions by the bot if I call any API at the same time, the server is unable to execute the API. But when the execution … -
Django server error 500 except for admin page
I'm getting a Server Error (500) when accessing any of the urls of my Django project, except for the /admin. I can access the admin page, and perform crud operations to my models as in development. However, Server Error (500) appears when trying to access any of my urlpatterns. If I type a different url (not present in the urls.py), I get a different error: Not Found The requested resource was not found on this server. I'm using docker-compose with nginx and wsgi and now testing on local machine. Why there are those diferences with the urls and what kind of error it can be? I'm just getting this logs in the terminal when server error message: suii-app-1 | [pid: 14|app: 0|req: 8/18] 172.18.0.1 () {56 vars in 1083 bytes} [Fri Jan 27 20:08:17 2023] GET / => generated 145 bytes in 91 msecs (HTTP/1.1 500) 7 headers in 240 bytes (1 switches on core 0) suii-proxy-1 | 172.18.0.1 - - [27/Jan/2023:11:08:17 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" "-" -
SetPasswordForm: clean only if new_password1 or new_password2 field is set
I need to validate updatePasswordForm only if new_password1 or new_password2 are not empty. I want to make the password fields optional, these are only for update the password. The view not only has the updatePasswordForm form. I'm using the next approach: .forms class UpdatePasswordForm(SetPasswordForm): class Meta: model = Account fields = ("new_password1","new_password2") def __init__(self, *args, **kwargs): super(SetAdminPasswordForm, self).__init__(*args, **kwargs) self.fields['new_password1'].required = False self.fields['new_password2'].required = False .view (CBV): class AdminProfileUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = AdminProfile form_class = AdminProfileForm second_form_class = AccountForm third_forms_class = ModulesForm fourth_form_class = UpdatePasswordForm login_url = '/login/' redirect_field_name = 'redirect_to' def handle_no_permission(self): return HttpResponseRedirect(reverse_lazy('login')) def test_func(self): return is_admin_check(self.request.user) def get_context_data(self, **kwargs): context = super(AdminProfileUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['form'] = AdminProfileForm(self.request.POST, instance=self.object) context['form2'] = self.second_form_class(self.request.POST, instance=self.object.account, prefix='account') context['form3'] = self.third_forms_class(self.request.POST, instance=self.object.modules, prefix='modules') context['form4'] = self.fourth_form_class(self.object.account, self.request.POST, prefix='password') else: context['form'] = AdminProfileForm(instance=self.object) if 'form2' not in context: context['form2'] = self.second_form_class(instance=self.object.account,prefix='account') if 'form3' not in context: context['form3'] = self.third_forms_class(instance=self.object.modules, prefix='modules') if 'form4' not in context: context['form4'] = self.fourth_form_class(user=self.object.account, prefix='password') return context def post(self, request, *args, **kwargs): self.object = self.get_object() current_profile = self.object form_class = self.get_form_class() form_profile = self.get_form(form_class) form2 = self.second_form_class(request.POST, instance=current_profile.account, prefix='account') form3 = self.third_forms_class(request.POST, instance=current_profile.modules, prefix='modules') form4 = self.fourth_form_class(self.object.account, request.POST, prefix='password') new_password1 = form4.data.get('password-new_password1') new_password2 = form4.data.get('password-new_password2') if form_profile.is_valid() … -
How to pass one MethodField data to another MethodFiels in django
I have a SerializerMethod field like below cal = models.SerializerMethodField('__getcal__') def __getcal__(self, obj): return obj*20 Now i want those data to be passed in another SerializerMethod and do some other calculation. something like this cal2 = models.SerializerMethodField('__getcaltwo__') def __getcaltwo__(self, obj): x = self.__getcal__(obj) return x*100 how can i achive this? -
DEBUG = TRUE in settings.py and "no urls are configured". However, they ARE configured
My urls are configured, yet it is displaying the standard success page for django. My app is listed in installed apps with the comma after it. My urls in both my src and application are configured, yet the program won't display. If you can help out I would appreciate it, bless. (https://i.stack.imgur.com/ZWskJ.png)(https://i.stack.imgur.com/yfJzX.png)(https://i.stack.imgur.com/fWaMk.png)(https://i.stack.imgur.com/SxVkk.png)(https://i.stack.imgur.com/CkFIF.png)(https://i.stack.imgur.com/3jMXW.png) I just have no clue why it will not portray my program. -
Django Model Mixin: Adding loggers to model save() and delete() using Mixins
I would like all my models to inherit from a single "loggingMixin" class. The problem is that, instead of using the save() defined in the LoggingMixin, the standard save() is used. (none of the print statements in the loggingmixin are executed and my traceback always referenced the object.save() from my views and not the error raised in the loggingmixin. all other logs works as they should and i can save and delete objects. but nothing gets logged. thanks in advance for the help! import logging logger = logging.getLogger(__name__) ## this file defines a mixin to logg all saves, updates, deletes and errors class LoggingMixin: def save(self, *args, **kwargs): try: print("---------------------------------------------------------------1") if hasattr(self.pk): print("---------------------------------------------------------------2") if self.pk is None: # Object is new print("---------------------------------------------------------------3") super(LoggingMixin, self).save(*args, **kwargs) logger.info(f"{self._meta.db_table} object saved: " + str(str(self).split('\n')[1])) else: # Object is being updated print("---------------------------------------------------------------4") super(LoggingMixin, self).save(*args, **kwargs) logger.info(f"{self._meta.db_table} object updated: " + str(str(self).split('\n')[1])) else: # Object is being updated print("---------------------------------------------------------------5") super(LoggingMixin, self).save(*args, **kwargs) logger.info(f"{self._meta.db_table} object updated: " + str(str(self).split('\n')[1])) # error when saving except Exception as e: print("-------------------------------------------------------------6") logger.error(f"Error saving {self._meta.db_table} object: " + str(str(self).split('\n')[1]) + f"Error: {e}") raise e def delete(self, *args, **kwargs): # delete log try: super(LoggingMixin, self).delete(*args, **kwargs) logger.info(f"{self._meta.db_table} object deleted. ID: {str(self.pk)}") … -
Mod_wsgi error (Getting error message in error_log)
Getting error message in error_log [Wed May 17 16:02:05.624941 2017] [:error] [pid 28655] [remote 10.10.10.48:148] mod_wsgi (pid=28655): Exception occurred processing WSGI script '/usr/share/ipa/wsgi.py'. [Wed May 17 16:02:05.625006 2017] [:error] [pid 28655] [remote 10.10.10.48:148] Traceback (most recent call last): ###wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AdminPanel.settings') application = get_wsgi_application() ###xyz.conf <VirtualHost *:80> ServerAdmin admin@xyz.com ServerName xyz.com ServerAlias www.xyz.com DocumentRoot /home/abc/Disk1/andew/xyz/xyz ErrorLog /home/abc/Disk1/andew/xyz/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static/admin/ /home/abc/Disk1/andew/xyz/xyz/static/admin/ <Directory "/home/abc/Disk1/andew/xyz/xyz/static/admin"> Require all granted </Directory> Alias /static/ /home/abc/Disk1/andew/xyz/xyz/static/ <Directory /home/abc/Disk1/andew/xyz/xyz/static> Require all granted </Directory> Alias /media/ /home/abc/Disk1/andew/xyz/xyz/media/ <Directory /home/abc/Disk1/andew/xyz/xyz/media> Require all granted </Directory> <Directory /home/abc/Disk1/andew/xyz/xyz/AdminPanel> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess xyz.com python-path=/home/abc/Disk1/andew/xyz/xyz python-home=/home/abc/Disk1/andew/xyz/xyz/env WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup xyz.com WSGIScriptAlias / /home/abc/Disk1/andew/xyz/xyz/AdminPanel/wsgi.py </VirtualHost> -
Search results doesn't show in the template (Django)
I am very new to Django and I am creating a very simple project. However, the "search" part of my project is having some issues. Every time I try to search, it redirect me to the search template but not showing the data from the database. No error message. Here's my code... models.py class Userprofile(models.Model): use_id = models.IntegerField() first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) position = models.CharField(max_length = 50) email = models.CharField(max_length= 100) password = models.CharField(max_length= 100) def __str__(self): return self.first_name account_list.html This is the template where the search bar is located <div class="search"> <form method="post" action="{% url 'account_search' %}" autocomplete="off"> <br> {% csrf_token %} <input type="text" name="acc_search" placeholder="Search Account"> <input type="submit" name="submit" value="Search" style="width: 24%"></p> </form> </div> <hr> views.py def account_search(request): if request.method == "POST": account_search = request.POST.get('acc_search') accounts = Userprofile.objects.filter(use_id__contains=account_search) | Userprofile.objects.filter(first_name__contains=account_search) | Userprofile.objects.filter(last_name__contains=account_search) | Userprofile.objects.filter(position__contains=account_search) | Userprofile.objects.filter(email__contains=account_search) return render(request, 'core/account_search.html', {'account_search': account_search, 'accounts':accounts}) else: return render(request, 'core/account_search.html', {}) account_search.html ` {% if account_search %} <div class="main-right"> <div class="h-1"> <h1>'{{ account_search }}' in Accounts</h1> </div> <table rules="all" style="border: 1px"> <thead> <td>Personnel's ID</td> <td>Name</td> <td>Position</td> <td>Email</td> <td>Action</td> </thead> <tbody> {% for userprofile in userprofiles %} <tr> <td>{{ userprofile.use_id }}</td> <td>{{ userprofile.first_name }} {{ userprofile.last_name }}</td> … -
How do I add StackedInlines to another model when the model for the inlines has a foreignkey in it
I have created models for a an election project. I want the polling agent to collect and submit results from different parties. I want to add the VoteInline to the ElectionResult models so that the PollingAgent can fill in the result of the different party's and the votes scored. I have created the following models and admin but I am getting the following error. How do I solve this? class Election(models.Model): election_category = models.CharField(max_length=255) start_date = models.DateTimeField() end_date = models.DateTimeField() class PoliticalParty(models.Model): name = models.CharField(max_length=200) election = models.ForeignKey(Election, on_delete=models.CASCADE) class Candidate(models.Model): fullname = models.CharField(max_length=120) party = models.ForeignKey(PoliticalParty, on_delete=models.CASCADE) bio = models.TextField(blank=True, null=True) class PollingAgent(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) election = models.ForeignKey(Election, on_delete=models.CASCADE) fullname = models.CharField(max_length=120) phone = models.IntegerField() email = models.EmailField() class Vote(models.Model): party = models.ForeignKey(Candidate, on_delete=models.CASCADE) votes= models.IntegerField() class ElectionResult(models.Model): polling_agent = models.ForeignKey(PollingAgent, on_delete=models.CASCADE) votes = models.ForeignKey(Vote, on_delete=models.CASCADE) uploaded_on = models.DateTimeField(auto_now_add=True) class VoteInline(admin.StackedInline): model = Vote extra = 0 admin.site.register(Vote) @admin.register(ElectionResult) class ElectionResultAdmin(admin.ModelAdmin): inlines = [ VoteInline, ] ERRORS: <class 'dashboard.admin.VoteInline'>: (admin.E202) fk_name 'party' is not a ForeignKey to 'dashboard.ElectionResult'. -
How to Filter + select json inside Jsonfield in django-rest-framwork
In one colomn response is store like this :- Now i want to filter this response [ { "id": "A", "children": [ { "id": "propertyName#0", "index": 0, "label": "Property", }, { "id": "userName#0", "index": 1, "label": "Reported By", }, { "id": "textinput#0", "index": 2, "label": "Reported By Title", }, { "id": "dateinput", "index": 3, "label": "Date Reported", } ], "component": "sectionDivider" }, { "id": "B", "children": [ { "id": "propertyName#0", "index": 0, "label": "Property", }, { "id": "userName#0", "index": 1, "label": "Reported By", }, { "id": "textinput#0", "index": 2, "label": "Reported By Title", }, { "id": "dateinput", "index": 3, "label": "Date Reported", } ], "component": "sectionDivider" }, { "id": "C", "children": [ { "id": "propertyName#0", "index": 0, "label": "Property", }, { "id": "userName#0", "index": 1, "label": "Reported By", }, { "id": "textinput#0", "index": 2, "label": "Reported By Title", }, { "id": "dateinput", "index": 3, "label": "Date Reported", } ], "component": "sectionDivider" } ] I want to filter like this how can i get this response I have id for the check like id: "A", id :"B" should only filter A and B and inside A and B i also want to filter. [ { "id": "A", "children": [ { "id": … -
Django Mem Cache Through IIS - Not Working as Expected
I'm using Django with no caching options meaning it defaults to memory cache. Caching is simple: Set Cache cache.set('chart_' + str(chartId), chart, 3600) Reset Cache when model is saved @receiver(pre_save, sender=DashboardChart) def increment_dashboard_chart_version(sender, instance, **kwargs): instance.version = instance.version + 1 # Resets cache cache.set('chart_' + str(instance.pk), None, 3600) Access cache cache.get('chart_' + str(chartId)) I'm running Django in production through IIS. What I'm finding is if I save the Chart model, the cache gets reset as expected. However, when reloading the page a few times the chart varies at random between the old version and the new version. My suspicion is that the different IIS worker threads are keeping their own memory version of the cache. Meaning there is not one global cache shared between the different IIS worker threads. As I randomly reload the page, the worker access changes and the cache version I get back is different. Any idea if I'm on the right path and how to solve this issue ?