Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to turn on/off a particular field from Django admin?
I want to implement a setting in my Django admin dashboard where I can disable/enable a particular field. If I should disable the field, the data in that field will not be rendered on the web page. If I should enable the field, then the data will be shown in the webpage. I only want to do this from my the admin dashboard. This is my models.py: class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to='products/') description = models.TextField() quantity = models.CharField(max_length=10) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) This is the admin.py: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'category', 'slug', 'price', 'available') list_filter = ('category', 'available') list_editable = ('price', 'available') prepopulated_fields = {'slug': ('name',)} I want to have the ability to enable/disable (maybe like a toggle button) the description field from my admin dashboard. Is there a way to implement this in my admin.py file? How can I go about this? Thanks. -
problem with django after changing python version
I've been upgrading my Ubuntu server from version 16.04 to 18.04, and upon completion, some of my old sites set up on Django stopped working. In similar threads I found information about trying to create a new virtualenv for each site - unfortunately, in my case this didn't help. I still can't fire up the manage.py file. In response, I get a stack of errors related most likely to importing modules. Traceback (most recent call last): File "/xxx/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/xxx/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/xxx/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/xxx/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/xxx/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/xxx/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/xxx/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/xxx/local/lib/python2.7/site-packages/aldryn_forms/contrib/email_notifications/models.py", line 16, in <module> from emailit.api import construct_mail File "/xxx/local/lib/python2.7/site-packages/emailit/api.py", line 2, in <module> import premailer File "/xxx/local/lib/python2.7/site-packages/premailer/__init__.py", line 2, in <module> from .premailer import Premailer, transform File "/xxx/local/lib/python2.7/site-packages/premailer/premailer.py", line 29, in <module> from lxml import etree ImportError: /xxx/local/lib/python2.7/site-packages/lxml/etree.so: undefined symbol: PyFPE_jbuf I created the virtual environment as follows: virtualenv --no-site-packages newvens, pip install -r requirements.txt - copied from previous directory, copying … -
How to return the most recent record in Django using Django Rest Framework?
I want to return the most recent record i.e. with the highest id. I have tried using last() method and order_by approach, but it gives error 'object of type 'Notification' has no len()'. Following is the code: class NotificationViewSet(viewsets.ModelViewSet): queryset = models.Notification.objects.all() permissions_classes = [permissions.AllowAny] serializer_class = serializers.NotificationSerializer -
Integrating ray with django not achieving same performance
I have a Django + Apache + WSGI app which has certain endpoints with specific actions such as: Load/Reload names from database [keeps in memory all the data] Inserting/Updating names [the names loaded in memory] Searching names similarity [search for the names] (would like to improve performance) The action #3 receives some parameters and returns the corresponding matching names according the logig. It tooks around 0.9s to go search around 200k ~ 300k names (multithreading) and I need to improve that response time. I have tried with multiprocessing module but is taking a bit more time than original implementation as I need to do a copy of the data or serialize/deserialize the data everytime. After doing some research I found ray. I have created a dataset and tested it in local and remote mode and the results were 3-5 times faster. Te issue is that I can't find a way of integrate my django app to ray logic and achieve the same performance: ray.init(ignore_reinit_error=True) #collecting some data and then calling to ray results = ray.get(tree.TrieNode.search_name_remote.remote(parameters) The results are almost the same. I only contact the database on the action #1 to load the data so I don't have to use … -
How to check how many anonymous or logged in users are visiting my django app
I have a django app and can't seem to find any straight forward answer to my question. I would like to know how many total users are accessing my site like a counter of users logged in at a time. -
Cannot load Vue JS files from Static folder in Django Template
I have made a templates folder in my app directory. and there I created another folder with my app's name and then I place my html file. index.html. After then I have build another directory name static in my project folder and place all my vue.js files there. index.html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> </head> <body> <div id="app" class="container"> <h3 class="d-flex justify-content-center"> Vue JS Front End </h3> <h5 class="d-flex justify-content-center"> Dr. Appointment Portal </h5> <nav class="navbar navbar-expand-sm bg-light navbar-dark"> <ul class="navbar-nav"> <li class="nav-item m-1"> <router-link class="btn btn-light btn-outline-primary" to="/home">Home</router-link> </li> <li class="nav-item m-1"> <router-link class="btn btn-light btn-outline-primary" to="/doctor">Doctor</router-link> </li> <li class="nav-item m-1"> <router-link class="btn btn-light btn-outline-primary" to="/appointment">Appointment</router-link> </li> </ul> </nav> <router-view></router-view> </div> <script src="{% static 'variables.js' %}"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.10.1/qs.min.js"></script> <script src="{% static home.js %}"></script> <script src="{% static doctor.js %}"></script> <script src="{% static appointment.js %}"></script> <script src="{% static app.js %}"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> </body> </html> In my static folder: In my app.js: const routes=[ {path:'/home',component:home}, {path:'/doctor',component:doctor}, {path:'/appointment',component:appointment} ] const router=new VueRouter({ routes }) const app = new Vue({ router }).$mount('#app') I am getting output (while running Django Server): But, when I … -
Django: save ForeignKey field when form is saved and filter by it
I've two models in my project and I'm having troube with two parts of my code: form.instance.docfile = request.docfile.document here I'd like to autocamatically save the connection between the Color model and the Document one but it doesn't work color = Color.objects.filter(docfile=request.docfile.document).order_by("id")[0] here I'd like to filter and get back only the information about the color for the specific file which the Color model is connnected with and only for the file uploaded from the user. Thank you all for the help. Model class Document(models.Model): ] user = models.ForeignKey(ObjectInformation, on_delete=models.CASCADE) docfile = models.FileField(storage=NumberStorage(), upload_to=directory) upload_date = models.DateField(default=datetime.now) class Color(models.Model): docfile = models.OneToOneField(Document, on_delete=models.CASCADE) color_one = models.CharField(null=True) color_two = models.CharField(null=True) View def upload(request): if request.method == 'POST': form = ColorForm(request.POST, request.FILES) if form.is_valid(): form.instance.docfile = request.docfile.document form.save() if not result.has_errors(): message = 'The form is not valid. ' else: form = ColorForm() documents = Document.objects.filter(user=request.user.userinformation).all() context = { 'documents': documents, 'form': form } return render(request, 'list.html', context) def color_view(request, doc_id): docfile = Document.objects.filter(pk=doc_id) color = Color.objects.filter(docfile=request.docfile.document).order_by("id")[0] context = { 'docfile': docfile, 'color': color } return render(request, 'show.html', context) -
Check content type with if statement to determine what to do
I have django model with a generic relation associated. class SectionLine(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField( default=uuid.uuid4, editable=True) content_object = GenericForeignKey('content_type', 'object_id') For the most part that generic relations is associated with one of these two models class Title(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title_name = models.CharField(max_length=40) .... class JobPosition(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... Within a view function I am trying to figure out what model between Title and JobPosition is associated with a specific SectionLine instance so that i can determine what to do next. I now that I can access SectionLine.content_type to see the content type (for example, it prints titles_and_names | title - the app name is titles_and_names) but I don't know what to compare it to... basically, if SectionLine.content_type == ??? -
scrollbar visible on fullscreen mode
I made an image viewer app, that just sends an image to a TV using a raspberry, displaying it on the connected screen via HDMI. The displaying software is Chrome, but I have a tiny problem: There is a very small area of 4px I have to crop the bottom of the image in order to not see a scroll bar. Example: Screen Res is 1024 x 768 using a 1024 x 768 pic in fullscreen mode creates a vertial scollbar decreasing the y pixels by 4 (1024 x 768) makes the scrollbar disappear, but shows me a white border under my image in Chrome for Linux fullscreen mode. I have no fancy css or html code whatsoever: let content = document.getElementById("content"); let ImageDiv = document.createElement("IMG"); ImageDiv.src = pic.file content.appendChild(ImageDiv); with only very little of css: body { margin: 0; } what is the best way to get rid of the border and the scrollbar? -
Geo Django 3.2 django.db.utils.OperationalError: no such function: lwgeom_version
I was trying to fetch the list of Dentists that are nearby from a user's current location. users' current location(latitude and longitude) is sent through query parameters. The dentist's location is saved in a model called location where the id of the dentist is the foreign key and unique identifier. I have used the PointField field from drf_extra_fields.geo_fields in LocationSerializer I'm using python 3.10 and Django 3.2.8 Model class Location(models.Model): id = models.OneToOneField(Dentist, on_delete=models.CASCADE, primary_key=True) location = models.PointField(srid=4326) Serializer from drf_extra_fields.geo_fields import PointField class LocationSerializer(serializers.ModelSerializer): location = PointField() class Meta: model = Location fields = ['id', 'location'] View class NearByDentistView(APIView): def get(self,request): longitude = float(self.request.query_params.get('longitude')) latitude = float(self.request.query_params.get('latitude')) user_location = Point(latitude,longitude,srid=4326) queryset = Location.objects.filter(location__distance_lte=(user_location, D(km=100))) serializer = LocationSerializer(queryset,many=True) return Response(serializer.data) Response Internal Server Error: /api/v1/user/dentist/nearby/ Traceback (most recent call last): File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 421, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such function: lwgeom_version The above exception was the direct cause of the following exception: Traceback (most recent call last): File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\asgiref\sync.py", line 482, in thread_handler raise exc_info[1] File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\django\core\handlers\exception.py", line 38, in inner response = await get_response(request) File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\django\core\handlers\base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\asgiref\sync.py", … -
Which view is responsible of rendering `successful installation` page?
I just installed the django and created a new project called api. now in api.api.urls there is the default: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] so there is url pattern for the admin site, but where is the url pattern for the home page (the page with the rocket) and which view is responsible for rendering it? -
firebase auth not working in django production
The below code works perfectly in localhost but not working in the staging server and there are no errors. it is returning "non_field_error": ["Given token not valid for any token type"] but this same token works perfectly in the localhost. What might be the issue ? cred = credentials.Certificate(BASE_DIR / "cred.json") firebase_admin.initialize_app(cred) class FirebaseAuthentication(BaseAuthentication): def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") token = auth_header.split(" ").pop() decoded_token = auth.verify_id_token(token) uid = decoded_token["uid"] user, created = User.objects.get_or_create(username=uid) return (user, None) -
Deployed prometheus with Django and Kubernetes, how to make it scrape the Django app?
I have a Django project deployed in Kubernetes and I am trying to deploy Prometheus as a monitoring tool. I have successfully done all the steps needed to include django_prometheus in the project and locally I can go go localhost:9090 and play around with querying the metrics. I have also deployed Prometheus to my Kubernetes cluster and upon running a kubectl port-forward ... on the Prometheus pod I can see some metrics of my Kubernetes resources. Where I am a bit confused is how to make the deployed Django app metrics available on the Prometheus dashboard just like the others. I deployed my app in default namespace and prometheus in a monitoring dedicated namespace. I am wondering what am I missing here. Do I need to expose the ports on the service and deployment from 8000 to 8005 according to the number of workers or something like that? My Django app runs with gunicorn using supervisord like so: [program:gunicorn] command=gunicorn --reload --timeout 200000 --workers=5 --limit-request-line 0 --limit-request-fields 32768 --limit-request-field_size 0 --chdir /code/ my_app.wsgi my_app service: apiVersion: v1 kind: Service metadata: name: my_app namespace: default spec: ports: - name: http port: 80 protocol: TCP targetPort: 80 selector: app: my-app sessionAffinity: None … -
Django: POST and GET request and rendering on a template
I'm probably lost in a glass of water but at the moment I can't figure it out. I'm working on a restaurant capstone project where the client is able to see a menu page, a purchase page and the owner of the restaurant after login is able to manage and enter a new recipe and create his personal menu. What I'm trying to do is: when the owner of the restaurant submits a POST request where he entered the recipe, i want that the recipe appear also in the page where is the menu. In this way is able to update new recipe and change maybe the old one. (I copy model, form and view code for a complete overview): form.py class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = '__all__' model.py class Recipe(models.Model): name = models.CharField(max_length=50) ingredients = models.CharField(max_length=500) def __str__(self): return self.name View.py def recipeEntry(request): recipe_menu = Recipe.objects.all() form = RecipeForm() if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): form.save() return redirect("recipe") context = {'form':form, 'recipe_menu':recipe_menu} return render(request, 'inventory/recipe.html', context) recipe.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Recipe</title> </head> <body> <form method="post", action="">{% csrf_token %} {{form.as_p}} <input type="submit" value="Add Recipe"> </form> {% for rec in recipe_menu … -
How do I send Django object as parameter in Javascript?
So as mention in title, I'm trying to send my Django object to JavaScript so I can massage it in the front end. Let me show you the code (simplified). views.py def main_page(request): contents = Contents.objects.all() context = { 'contents' : contents } return render(request, 'main/home.html', context) template {% for u in all_ans_us_paginated %} <div class="row"> <div class="col"> <div class="" id="{{u.id}}" onclick="DetailModal('{{u}}')"> </div> </div> </div> {% endfor %} ... <script> function DetailModal(u) { console.log('{{u.author}}'); console.log('{{u.body}}'); } </script> My intention is to show a modal when the click event is triggered. But putting the modal part aside, I can't pass data as parameter to JavaScript. *I don't want to make any changes in the python code. Is it possible to do it only with HTML and JavaScript? **JSON.parse(u) won't work, because u is string. -
Which framework should I learn for freelancing, Django or Node.js [closed]
I have also learned python, java script, css and html I searching best backend framework (Django and Node.js) -
Upload 10000 xlxs records to mysql using django
I have around 10k xlxs files (each with 4 different sheets and same data format for all sheets). I wanted to fetch that data and add that data to MySQL tables. With my current code it is takin around 1-2 hrs. to fetch and fill data. I wanted to optimize this and reduce time to around 5-10 mins for 10k files. Pls suggest me right solution. TIA. class ImportFileView(APIView): def post(self,request): xlsx_file = request.FILES.getlist('file') # Around 10k files for file in xlsx_file: wb_obj = openpyxl.load_workbook(file) working_sheet = wb_obj['Sheet1'] create_table_one = TableOne.objects.create( id = working_sheet['B1'].value, first_name = working_sheet['B2'].value, last_name = working_sheet['B3'].value, country = working_sheet['B4'].value, region = working_sheet['B5'].value, lab = working_sheet['B6'].value, sample_date = working_sheet['B7'].value, issue_date = working_sheet['B8'].value, release_year = working_sheet['B9'].value, comments = working_sheet['B10'].value, ) create_table_one.save() for col in range(2,4): group = working_sheet[get_column_letter(col)+str(11)].value name = working_sheet[get_column_letter(col)+str(12)].value unit = working_sheet[get_column_letter(col)+str(13)].value sample_unit = working_sheet[get_column_letter(col)+str(14)].value parameter = working_sheet[get_column_letter(col)+str(15)].value type = working_sheet[get_column_letter(col)+str(16)].value default_value = working_sheet[get_column_letter(col)+str(17)].value for row in range(19,90): create_data = TableData.objects.create( id = create_table_one.id, temperature = working_sheet['A'+str(row)].value, group = group, name = name, unit = unit, sample_unit = sample_unit, parameter = parameter, type = type, default_value = default_value, actual_value = working_sheet[get_column_letter(col)+str(row)].value ) create_data.save() working_sheet = wb_obj['Sheet2'] for col in range(2,100): if working_sheet[get_column_letter(col)+str(5)].value == None or working_sheet[get_column_letter(col)+str(5)].value … -
Setting DEBUG = False, ALLOWED_HOST = ['localhost', '127.0.0.1'] causes 500 Error
I'm using Django 3.0 with the setting: DEBUG = True when I change to DEBUG = False and run manage.py runserver, I get the following error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False and after changing ALLOWED_HOSTS = ['localhost', '127.0.0.1'] It is throwing Server Error (500) I've tried all the solutions of stack overflow related to this problem, but not able to solve this. Please Help, how can I fix this? -
register in Django administration isn't work
i tried to add register to my django and it doesn't work it means it doesn't register in Django administration bast.html <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> {%block head %} <title>Base</title> {% endblock %} </head> <body> <br> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/account/login">Login Page</a> <a class="navbar-brand" href="/account/register">Register</a> </div> <div id="navbar" class="navbar-collapse collapse"> {%if user.is_authenticated %} <ul class="nav navbar-nav "> <li><a href="/account">Home</a></li> <li><a href="/account/login">login</a></li> <li><a href="/account/profile">profile</a></li> <li><a href="/account/profile/edit">edit profile</a></li> <li><a href="/account/logout">logout</a></li> <li><a href="{% url "login" %}">login</a></li> </ul> {% else %} <ul class="nav navbar-nav navbar-right"> <li><a href="/account/login">login successfully!</a></li> <li><a href="/account/register">Register</a></li> </ul> {% endif %} </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </nav> {% block body%} <h1>Login</h1> {% endblock %} </body> </html> another file is register.html {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Welcome</h1> <p> register below! </p> <h2>REGISTER</h2> <form method="post"> {{form.as_p}} {% csrf_token %} <button type ="submit">register</button> </form> </div> {% endblock %} and also here is my login.html file that its work {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Welcome</h1> <p> Login below! </p> <h2>LOGIN</h2> <form method="post"> {{form.as_p}} {% csrf_token %} <button type … -
Image for loop in Django template html
I would like to ask how to generate images in for loop in html template in Django: this code doesn't work: Plants: {% for plant in plants %} {{ plant.name }} {% endfor %} but if I replace this: {{ plant.name }}.jpg by this: carrot.jpg then the image is displayed. All the images I have saved in static/plant_photos and the name of each photo correspond with name of the plant. -
Django REST Framework - Get reverse value of boolean field in serializer
I have 2 models: class Model(models.Model): ... related = models.ForeignKey( 'RelatedModel', on_delete=models.CASCADE, related_name='related_model' ) class RelatedModel(models.Model): ... flag = models.BooleanField() I need to pass value of 'flag' attribute of RelatedModel in Model instance serializer and additionally this value must be reversed i.e. if it is 'True', I should return 'False' as boolean data type. Already implemented this with method: class ModelSerializer(serializers.ModelSerializer): ... flag = serializers.SerializerMethodField() @staticmethod def get_flag(obj): return not obj.related.flag class Meta: model = Model fields = ( ... flag ) But maybe there is opportunity to use only serializer fields like this but with reverse value? flag = serializers.BooleanField( source='related.flag', read_only=True ) -
Add two instances to same table in django
In my case, it a treasury managing app, the task is i want to transfer an amount x from this treasury to the other treasury, from bank to cashier or from paypal acc to my bank, i m adding two instances to same table but with different details. anyone can help pls. thanks in advance MODEL : class Treasury(models.Model): name = models.CharField(max_length=256) class TreasuryItem(models.Model): treasury = models.ForeignKey('Treasury', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) name = models.CharField(max_length=256) debit = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) credit = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) FORM : class TreasuryItem1Form(ModelForm): class Meta: model = TreasuryItem fields = "__all__" class TreasuryItem2Form(ModelForm): class Meta: model = TreasuryItem fields = "__all__" VIEW: def TreasuryItem_Create(request, pk): treasurys = Treasury.objects.all() treasury = treasurys.get(id=pk) form1 = TreasuryItem1Form() form2 = TreasuryItem2Form() if request.method == 'POST': form1 = TreasuryItem1Form(request.POST) form2 = TreasuryItem2Form(request.POST) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() return redirect('treasury_profile', pk) -
Cannot assign "(<Qualification: Qualification object (1)>,)": "QualificationApproval.qtitle" must be a "Qualification" instance
this is my model of Qualification Approval class QualificationApproval(models.Model): """Model definition for QualificationApproval.""" # TODO: Define fields here qtitle = models.ForeignKey(Qualification, on_delete=models.CASCADE) ofEqualCode = models.CharField(max_length=100) porposDate = models.DateField() anNo = models.IntegerField() status = models.CharField(max_length= 50, default="pending") sec9 = models.ForeignKey(Sec9, on_delete=models.CASCADE) class Meta: """Meta definition for QualificationApproval.""" verbose_name = 'QualificationApproval' verbose_name_plural = 'QualificationApprovals' so here is qtitle is foreign key of qualification the problem is that when I assign the qualification in QualifcationApproval so its give me and error def sec9edit(request, secId): if 'userId' not in request.session: return render(request, "front/login.html", { "message": "Login Required First" }) user = User.objects.get(pk = request.session['userId']) sec1 = Sec1.objects.get(user = user ) qualification = Qualification.objects.all() if request.method == "POST" and secId: sec9 = Sec9.objects.get(pk = secId) sec9.curriculum = request.POST['curriculum'] sec9.save() qlrn = request.POST.getlist('qualification') code = request.POST.getlist('code') pdate = request.POST.getlist('pdate') anticipated = request.POST.getlist('anticipated') j = 0 qa = QualificationApproval.objects.filter(sec9 = sec9) for q in qlrn: if q: qua = Qualification.objects.get(pk = q.split(',')[0]) print(type(qa[j].qtitle)) qa[j].qtitle = qua, qa[j].ofEqualCode = code[j], qa[j].porposDate = pdate[j], qa[j].anNo = anticipated[j], qa[j].sec9 = sec9 qa[j].save() messages.success(request, 'Section 9 udpated successfully') return HttpResponseRedirect(reverse('addCentre/sec10')) else: try: sec9 = Sec9.objects.get(sec1= sec1) qa = QualificationApproval.objects.filter(sec9 = sec9) except: return render(request, "front/sec9.html", { "qualification": qualification }) return render(request, … -
Save output of generic listview into html-file
Using django I get the correct output displayed in the browser when direct it to right URL after login and add the needed query string (GET) parameters. Now I would like - from a different view - to get the aforementioned output and save it directly into a (server side) (html) file. Do I need to construct an HttpRequest object? What settings are required there? How to I get the content out of the HttpResponse? Or is there a simpler solution? -
How to get results from celery task to react via django rest framework
I am trying to create a celery task within django rest framework and return the result to the react frontend. Here is my URLs from .views import ImageViewSet from rest_framework import routers from django.urls import path, include router = routers.DefaultRouter() router.register(r'analyze', ImageViewSet) urlpatterns = [ path('', include(router.urls)), ] Here is my serializer class ImageViewSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer def create(self, request, *args, **kwargs): serializer = TestSerializer(data=request.data) ...some logic result = test_task.delay(file_path) return JsonResponse({"task_id": result.id, "task_status": result.status}, status=status.HTTP_201_CREATED) def list(self, request, task_id, *args, **kwargs): task = current_app.AsyncResult(task_id) response_data = {'task_status': task.status, 'task_id': task.id} if task.status == 'SUCCESS': response_data = TestSerializer(Test.objects.get(pk=task.get())) return Response(response_data.data, status=status.HTTP_201_CREATED) I can see that the def create function works because when I go to the Django admin, I find everything saved and calculated correctly. I believe the problem is in def list or the URL files On my frontend I have the following getResults= () => { let formData = new FormData() formData.append('picture', files[0]., files[0].name) axios.post("/api/analyze/", formData, { headers: { 'accept': 'application/json', 'content-type': 'multipart/form-data' } }) .then(resp => { console.log(resp.data) }) } I get {task_id: '8f09fc07-e434-4e8c-88c4-f4d60fb711dd', task_status: 'PENDING'} But I am not sure how to update this function so I get the results when celery is …