Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CKEditor change color
How change black color dialog window widget Django-CKEditor? Due to the black color background, not visible black text in django admin. Or tell me where the text color of Django-CKEditor dialog boxes changes. -
Forbidden (CSRF token missing.) error when trying to make a POST request. Using React (Axios) and Django
I've been trying to solve this issue in various ways for awhile now, but every answer I have seen on here has not worked for me yet. I am running React (and Redux) on my localhost:3000, and Django on localhost:8000. I'm very still new to this, but I have seen posts where people have said to include csrf token in the header where the axios post is taken place, but that hasn't worked for me. I've also tried fiddling with settings.py, but none of that has worked as well. This is what I had before researching just to hopefully get a base. Thank you! Here is my /actions/auth.js import axios from 'axios'; import { LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED_SUCCESS, USER_LOADED_FAIL, } from './types'; // login function export const login = (email, password) => async (dispatch) => { const config = { headers: { 'Content-Type': 'application/json', }, }; const body = JSON.stringify({ email, password }); try { const response = await axios.post( `${process.env.REACT_APP_API_URL}/auth/jwt/create/`, body, config ); dispatch({ type: LOGIN_SUCCESS, payload: response.data, }); dispatch(load_user()); } catch (err) { dispatch({ type: LOGIN_FAIL, }); } }; settings.py """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR … -
How properly add async methods to DRF application ? what is the best approach for it: Asyncio or Celery?
I'm a new to async in django and want to make some experiments with it. Exactly wan to make my CRUD methods in DRF async at least. Asyns I mean approximelty the same dehaviour as JS async\await. What I need to start from: Asyncio or Celery ? May be some articles and sources to read . Thanks ! P.S. using django 4.0 (just updated), drf 3.13.1 -
Flask return a proper list object to test in Postman
im currenty doing some work for school; i have a flask app and some postman tests that i have to pass, one of which requests an array of dicts (something like [{dict1}, {dict1},..]) ive been trying to return this: result = [{ "reservationUid": data["reservationUid"], "status": data["status"], "startDate": data["startDate"], "tillDate": data["tillDate"], "book": book_data, "library": library_data }] ive used jsonify(), dumps() + mimetype='application/json', make_response() but nothing really helped, it seems like if i do so, postman wont count that as a json but as an undefined? for example, for return Response(dumps(result), mimetype='application/json') it returns TypeError: Cannot read property 'status' of undefined here is the part of the test where it dies: const response = pm.response.json(); pm.expect(response).to.be.an("array") const reservation = _.find(response, { "reservationUid": reservationUid }) pm.expect(reservation.status).to.be.eq("RENTED") pm.expect(reservation.startDate).to.be.not.undefined pm.expect(reservation.tillDate).to.be.not.undefined tho my response data returns looks like [ { "reservationUid": "f464ca3a-fcf7-4e3f-86f0-76c7bba96f72", "status": "RENTED", "startDate": "2021-10-09", "tillDate": "2021-10-11", ... <some more data here> } ] basically status is actually "RENTED" like required. for django apps that return serializers data with many=True field such tests work just fine, but since u cant just return an array in flask this gets so complicated :( my best solution is to redirect my requests to the django app but isnt … -
Django - create multiple tables from Excel sheets
Forgive me for the relative naivete of this question...I inherited a Django project with zero Django experience myself so I'm trying to keep this thing running while teaching myself the framework at the same time. I have an Excel workbook with multiple sheets and I want to be able to create a table for each sheet. The workbook comes from an API, so I'm using requests to download the workbook. I'm familiar with downloading an Excel workbook and creating a dataframe for each tab, but I'm not sure how to pass multiple dataframes on to multiple models within Django without making the get request one time for each of the sheets. Here is an example of my update command for a flat file get request: import os import pandas as pd import sys import json from datetime import date, datetime from utils.update_dataset_command import UpdateDatasetCommand class Command(UpdateDatasetCommand): app_label = 'my_app' model_name = 'table1' def pull_data(self, fields): # Pull the dataset from get_request = requests.get('URL.csv') dataframe = pd.read_csv(get_request.content) return dataframe What I'm trying to achieve is to be able to do something like: Class Command(UpdateDatasetCommand): app_label = myapp model_names = ['table1', 'table2', 'table3'] def pull_data(self, fields): get_request = requests.get('URL.xlsx') Excel = pd.ExcelFile(get_request.content) … -
Prefetch query with relational conditions - Django
I'm trying to make a request that prefetch all the data to reduce the amount of requests to my database. I'm using the prefetch_related() method and the Prefetch object class to tell what to load in the same request, here is my code: pairs_queryset = Pair.objects.filter(quote_id="2781", last_price__isnull=False) \ | Pair.objects.filter(quote_id="825", last_price__isnull=False) \ | Pair.objects.filter(quote_id="3408", last_price__isnull=False) queryset = Portfolio.objects.prefetch_related( Prefetch('connections__wallets__currency__metadata__images'), Prefetch('connections__wallets__currency__base_pairs', queryset=pairs_queryset), ).get(id=portfolio_id) data = Serializer(queryset).data My problem here is that I have multiple base_pairs in my database that depends on the Connection model. So I would like to add a filter that depends on a value contained in on of the previous models (i.e. connection) of the prefetch. As connections is a set (multiple values), I want that the following: connections__wallets__currency__base_pair retrieve the base_pair related to the connection currently fetched. Here is a diagram: connections__wallets__currency__base_pairs ^ |_______________________________| depends on I read the documentation and couldn't find any solution. Is it possible? -
Stuck creating a django posts filter
I need to filter the posts by the options selected between: "most commented" "category" "date". This is actually my code: models: class BlogPost(models.Model): class BlogPostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='publicado') options = ( ('borrador', 'Borrador'), ('publicado', 'Publicado') ) categoria = models.ForeignKey(BlogCategoria, on_delete=models.PROTECT,default=1) titulo = models.CharField(max_length=250) excerpt = models.TextField(null=True) contenido = models.TextField() slug = models.SlugField(max_length=250, unique_for_date='publicado',null=False, unique=True) publicado = models.DateTimeField(default=timezone.now) autor = models.ForeignKey(Usuario,on_delete=models.CASCADE,related_name="autor") status = models.CharField(max_length=10,choices=options,default='borrador') imagen = models.ImageField(default= "empty.jpg" ,null=True, blank = True) objects = models.Manager() postobjects = BlogPostObjects() class Meta: ordering = ('-publicado',) db_table= "blog_post" view: class BlogInicio(ListView): template_name = "Blog/blog_inicio.html" model = BlogPost context_object_name = "posts" paginate_by = 9 def get_queryset(self): return BlogPost.postobjects.all() -
how to update a form inside a class based detail view?
I created a survey form for each user which the staff user can fill it for them. I created a detail view and added formMixin just like this: class ScientificInfoView(FormMixin, DetailView): model = ScientificInfo template_name = 'reg/scientific-info.html' form_class = ScientificInfoForm def get_success_url(self): return reverse('scientific-info', kwargs={'pk': self.object.pk}) def get_context_date(self, **kwargs): context = super(ScientificInfoView, self).get_context_data(**kwargs) context['form'] = ScientificInfoForm() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): f = form.save(commit=False) f.user = self.object.user f.save() return super(ScientificInfoView, self).form_valid(form) it works just fine but I want the staff to be able to edit and update these forms as well. If I click on the object and refill the form it wouldn't update the previous one but makes a new object for that user. I don't want that. I need to somehow change this view to update the view if the user has this object already. I created a dashboard that divides those who have filled forms and those who haven't. I want the filled ones to get redirected to the update view, not the detail view I wrote. is there a way to update this one or should I create … -
Debug Celery tasks without CELERY_ALWAYS_EAGER
I'm facing an issue with Debugging Celery tasks running in a chain. If I set the CELERY_ALWAYS_EAGER configuration the tasks will run on the same process one by one and I'm able to Debug. but, when I set this configuration another problem is raised, I have an issue creating a socket. socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_ICMP) I get an error: _sock = _realsocket(family, type, proto) error: [Errno 1] Operation not permitted I can guess it's a result of the CELERY_ALWAYS_EAGER configuration. How can I handle this issue? -
I can't create a form with password1 password2 in Django
error:Unknown field(s) (password1, password2) specified for User I have no idea why it doesn't work as documentation says Documentation: class UserCreationForm¶ A ModelForm for creating a new user. It has three fields: username (from the user model), password1, and password2. It verifies that password1 and password2 match, validates the password using validate_password(), and sets the user’s password using set_password(). My forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] my views.py class CreateUserView(CreateView): model = User form = CreateUserForm template_name = 'registration/register.html' fields = ['username', 'email', 'password1', 'password2 ] class UserLoginView(LoginView): next_page = "home.html" '] urls.py urlpatterns = [ path('register/', CreateUserView.as_view(), name='register'), ] -
CRIPSY FORMS InvalidCursorName at html file
i'm new to Django but so far i developed a lot of beginner projects. Since i want to share the stuff and learn the last step of django(deployment) i started to dig into Docker containers and AWS deploying methods. My project works perfectly on the local server without docker but when i put it into container and run i have the error in my form page which shown below; InvalidCursorName at /request/form_request / cursor "_django_curs_140621549230904_sync_2" does not exist Request Method: GET Request URL: http://127.0.0.1:8000/request/form_request%20/ Django Version: 3.2.10 Exception Type: InvalidCursorName Exception Value: cursor "_django_curs_140621549230904_sync_2" does not exist Exception Location: /py/lib/python3.9/site-packages/django/db/models/sql/compiler.py, line 1178, in execute_sql Python Executable: /py/bin/python Python Version: 3.9.9 Python Path: ['/app', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/py/lib/python3.9/site-packages'] Server time: Sun, 19 Dec 2021 15:37:57 +0000 Error during template rendering In template /py/lib/python3.9/site-packages/crispy_forms/templates/bootstrap/field.html, error at line 30 cursor "_django_curs_140621549230904_sync_2" does not exist {% if not field|is_checkboxselectmultiple and not field|is_radioselect %} 22 <div class="controls"> 23 {% if field|is_checkbox and form_show_labels %} 24 <label for="{{ field.id_for_label }}" class="checkbox {% if field.field.required %}requiredField{% endif %}"> 25 {% crispy_field field %} 26 {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} 27 </label> 28 {% include 'bootstrap/layout/help_text_and_errors.html' %} 29 {% else %} 30 {% crispy_field … -
guidance with Dj-rest-auth and implementing google login in flutter app
I have a flutter application with a DRF back end. currently using Dj-rest-auth for regular authentication (token). I'm at a point where I'd like to implement social authentication (specifically Google). I searched a few resources but still don't quite get the workflow. https://github.com/iMerica/dj-rest-auth/pull/336/commits/8f5cc65049c4bcb0c650bde707f5023013497b20 my guess is: you set up your application on google cloud console. You make a request to get an "access token" to the google auth on the Frontend (in my case flutter) send that access token to your Back end - django to confirm. which then sends back a regular token for authentication? Any guidance would be appreciate. -
Django intermittent multithread shared queue
I am trying to solve this simple problem in django the Correct Way Worker1(thread): django connected to serial device streaming data ~ 1kb/s Consumer1(thread): reads FIFO (queue) and processes the data as it enters the fifo **the consumer will run intermittently How do I pass the queue object to the newly created consumer if the worker is already running with its own queue? I use memcached. I could pass the queue object that way? The example below works because i use globals. In Django views this will not be the case. My consumer will start in a fresh def that is triggered by a url... stop_thread=False q=queue.Queue(maxsize=100) connectSerial() t2= threading.Thread(target=consumer,args=(q),daemon=True).start() time.sleep(5) stop_thread=True def connectSerial(): ser = serial.Serial() ser.baudrate = 1000000 ser.timeout=1 ser.port = '/dev/ttyACM2' ser.open() t1 = threading.Thread(target = readSerial, args = (ser), daemon = True).start() def readserial(ser): global stop_thread,q msg = bytearray() buf = bytearray() #trimmed at open must add back while True: if(stop_thread): break try: while True: timelast=time.time() i = max(1, min(2048, ser.in_waiting)) msg = ser.read(i) buf.extend(msg) a= msg[0:1][0] q.put(a) break except Exception as e: stop_thread=True ser.close() break stop_thread=True ser.close() def consumer(): global stop_thread,q while not stop_thread: if not q.empty(): a=q.get() b=a*100 print(b) -
django template variable - uncaught referenceerror i is not defined
I have this code in html template: {%for i in result %} <tr> <td id="tdId_{{ i.id }}1">{{i.1}}</td> <td id="tdId_{{ i.id }}2">{{i.2}}</td> <td id="tdId_{{ i.id }}7">{{i.7}}</td> <td id="tdId_{{ i.id }}8">{{i.8}}</td> <td id="tdId_{{ i.id }}9">{{i.9}}</td> <td id="tdId_{{ i.id }}10">{{i.10}}</td> <td id="tdId_{{ i.id }}4">{{i.4|date:'Y-m-d H:i'}}</td> <td><input type="datetime-local" id="tdId_{{i.id}}5"/></td> <td><button value="{{i.id}}" type="button" onclick="setEndActivity({{i.id}})">End</button><td/> <!-- <td><button value="{{i.id}}" type="button" onclick="setEndActivity(this.value)">End</button><td/> --> </tr> {% endfor %} It writes error message: Uncaught ReferenceError: i is not defined at setEndActivity ((index):198) at HTMLButtonElement.onclick ((index):68) setEndActivity @ (index):198 onclick @ (index):68 The commented line didn't help. -
How can you use a request.user in model form in django?
I want to be able to use the request.user in the model form init. Here is my view: def create(request, pk): if request.method == 'POST': form = CreateForm(request.POST) if form.is_valid(): object = form.save() object.save() return render(request, 'going_create.html', {'object':object}) else: form = CreateForm() return render(request, 'being_create.html', {'form':form}) Basically, I need request.user to prefill a django form field. Here is my form: class CreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(CreateForm, self).__init__(*args, **kwargs) self.fields['first_name'].initial = self.request.user.first_name class Meta: model = creater fields = ( 'first_name', ) Also, there are form = CreateForm(request.POST) if request.method == 'POST', and form = CreateForm() when else. So, as I am not familiar with using a function view, I hope you could tell me where I need to add the code so that I could use request.user to prefill a django field. Thank you, and please leave any questions you have. -
Can't get Django redirect to work appropriately in a paginated view
I have this paginated view which caters for voting similar to Django official beginner's tutorial, but with pagination. I observed that when I submit and redirect to the next page, i.e the next question, when I submit at this page (which is eq to 2) it redirects back to page 1 instead of page 3 def vote(request): questions = Question.objects.all() paginator = Paginator(questions, 1) try: page_number = request.GET.get('page', 1) print('current_page: ', page_number) page_obj = paginator.get_page(page_number) question = page_obj.object_list.get() # object list contains the objects in the page selected_choice = question.choice_set.get(pk=request.POST['choice']) # increment selected choice and save selected_choice.vote += 1 selected_choice.save() url = f"{reverse('vote')}?page={page_obj.next_page_number()}" return HttpResponseRedirect(url) except (KeyError, Choice.DoesNotExist): return render(request, 'vote.html', { 'page_obj': page_obj, 'error_message': "You didn't select a choice.", }) except PageNotAnInteger: page_obj = paginator.get_page(1) except EmptyPage: page_obj = paginator.get_page(paginator.num_pages) context = { 'questions': questions, "page_obj": page_obj } return render(request, 'vote.html', context) URL: localhost:8000/vote/ at first instant localhost:8000/vote/?page=2 next Then instead of localhost:8000/vote/?page=3 it goes back to localhost:8000/vote The navigation in the template for the view works as expected but this isn't. Thanks in advance -
image not showing in the templates in django
this my templates when i add song from my database everything is working fine but image not showing in the templates how can i solve that this is my templates. {% for audio in songs %} <div class="player"> <div class="imgBx"> <div> <p>{{audio.book_title}}</p> <p>{{audio.artist}}</p> <p>{{audio.author}}</p> </div> <img src="{{object.image_url}}" alt=""> </div> <audio controls> <source src="{{audio.file.url}}" type="audio/mp3"> </audio> </div> {% endfor %} this is my models.py from django.db import models Create your models here. class Audio(models.Model): book_title = models.CharField(max_length=100, null=False, blank=False) file = models.FileField(upload_to='file') author = models.CharField(max_length=100, null=False, blank=False) artist = models.CharField(max_length=100, null=False, blank=False) image = models.ImageField(upload_to=file, null=True, blank=False) def __str__(self): return self.book_title def image_url(): if self.image and hasattr(self.image, 'url'): return self.image.url this is my views.py from django.shortcuts import render from .models import Audio Create your views here. def index(request): context = {'songs': Audio.objects.all()} return render(request, 'index.html', context) -
Get data for div based on select value with ajax
I am currently stuck with getting data for a div on the same page based on the selected value from a dropdown. I have a dropdown where the user can select a value. Based on the selection, the div in the second part of the page should be filled in. I can get the console.log right with the selected value, but I cannot make it work to get the necessary data. Any help is appreciated. The goal is to create an individual scorecard with the prefilled table in the next step. My html looks like this: <!--Dropdown--> <div class="container"> <select id="choosecourse"> <option value="">Select course</option> {% for course in courses %} <option>{{ course.name }}</option> {% endfor %} </select> </div> <!--Second part of the page which should be filled in based on the selection--> <div class="container"> <h5>{{ id.name }}</h5> </div> <div class="container"> <table class="table input-width"> <tr> <td>Holes:</td> <td>{{ id.holes }}</td> <td>Par:</td> <td>{{ id.par }}</td> </tr> <tr> <td>Your handicap:</td> <td>{{ user.handicap }}</td> <td>Extra strokes:</td> <td><input type="number" min="0"></td> </tr> </table> </div> My javascript looks like this: <script> $(document).ready(function() { $('#choosecourse').change(function(){ var name = document.getElementById("choosecourse").value; console.log(name) }); }); </script> My views.py looks like this: def add_score(request): courses = CourseOverview.objects.all() return render(request, "mrc/add_score.html", { "courses": courses … -
Django model: set a "week of day" field as string from existing models.DateField()
I am trying to set a Session class's field based on another model Teacher's field. Basically, each Teacher has an assigned day of week (Monday, etc) and I want each Session object to have the Teacher.name as field based on Session's date field. For example, Session class with the date=2021-12-25 would have the field weekday='Saturday' hence get a my_teacher_name='Mr.Saturday' Since I need a string value such as "Monday" to query the teacher assigned to that day, I'm trying to figure out how to do this! Here's the code: from django.utils import timezone from datetime import date, datetime class Session(models.Model): class Timeblock(models.TextChoices): A = "8:00-8:20", "8:00-8:20" B = "8:20-8:40", "8:20-8:40" C = "8:40-9:00", "8:40-9:00" D = "9:00-9:20", "9:00-9:20" E = "9:20-9:40", "9:20-9:40" F = "9:40-10:00", "9:40-10:00" student = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) date = models.DateField() timeblock = models.CharField(max_length=10, choices=Timeblock.choices) helptype = models.CharField(max_length=50) class Teacher(models.Model): class Weekday(models.TextChoices): mon = "Monday", "Monday" tue = "Tuesday", "Tuesday" wed = "Wednesday", "Wednesday" thu = "Thursday", "Thursday" fri = "Friday", "Friday" sun = "Sunday", "Sunday" name = models.CharField(max_length=50) email = models.CharField(max_length=50) expertise = models.CharField(max_length=100) assigned_day = models.CharField(max_length=10, choices=Weekday.choices) def __str__(self): return self.name Here's what I've tried so far in Session class: weekday = date_posted.datetime.strftime("%A") my_teacher … -
How to automatically choose related model using field value
Assume, we have model class BaseModel(models.Model): is_a = models.BooleanField() and two models related to this one: class A(models.Model): value_1 = models.IntegerField() base = models.ForeignKey(BaseModel, related_name='a') class B(models.Model): value_1 = models.IntegerField() value_2 = models.IntegerField() base = models.ForeignKey(BaseModel, related_name='b') What I need is to refer to A or B depending on is_a property. For example, base = BaseModel.objects.get(id=1) if base.is_a: obj = A.objects.create(value_1=1, base=base) else: obj = B.objects.create(value_1=1, value_2=2, base=base) return obj or if base.is_a: queryset = base.a.all() else: queryset = base.b.all() return queryset i.e., every time I have to check the is_a property. Is there more graceful way? There are two only related models, A and B, no other ones will appear in the nearest future. Part of the problem can be solved with django-polymorphic, e.g.: class A(PolymorphicModel): ... class B(A): ... This allows to retrieve all A's and B's with one request like base.b.all(), but the problem here is that every B creates instance of A, which is unwanted. I've considered GenericForeignKey as well. As far as I understood it has a number of limitations like "1) You can't use GenericForeignKey in query filters ; 2) a GenericForeignKey won't appear in a ModelForm" (from GenericForeignKey or ForeignKey). -
How to return manytomanyfield as object in Django RestFramework API
I tried to create an API with Django RestFramework, so i created 2 models Note and Task and have a ManyToManyField in Note model so i can put many Task in a Note but the API i created don't return full object feature but just the id. Here is my code: class NoteAPI(ListAPIView): serializer_class = NoteSerializer queryset = Note.objects.all() Here is my models: class Task(models.Model): task = models.CharField(max_length=255, null=False, blank=False) detail = models.CharField(max_length=255, null=True, blank=True) completed = models.BooleanField(default=False) priority = models.IntegerField(default=0) def __str__(self): return self.task class Note(models.Model): title = models.CharField(max_length=255, null=False, blank=False) priority = models.CharField(max_length=1, choices=PRIORITY_CHOICES, default="B") detail = models.CharField(max_length=255, null=True, blank=True) completed = models.BooleanField(default=False) task = models.ManyToManyField(Task, related_name="note_task", blank=True) process = models.IntegerField( default=0, validators=[max_int_value]) def __str__(self) -> str: return self.title + " is "+ str(self.process) + "% completed" And i want the out put can looks like: [ { "id": 2, "title": "Sleep", "priority": "F", "detail": "Don't do it, stay awake and do your job", "completed": false, "process": 0, "task": [ { "id": 1, "task": "Go to bed", "completed": false }, { "id": 2, "task": "Start counting", "completed": false } ] } ] But it actually be like this [ { "id": 2, "title": "Sleep", "priority": "F", "detail": "Don't … -
ran into error while building Django/PostgreSQL app with docker-compose
While trying to create Django/PostgreSQL app as mentioned in here I'm getting following error : db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2021-12-19 14:50:52.192 UTC [1] LOG: starting PostgreSQL 14.1 (Debian 14.1-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit db_1 | 2021-12-19 14:50:52.193 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-12-19 14:50:52.193 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2021-12-19 14:50:52.199 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2021-12-19 14:50:52.231 UTC [26] LOG: database system was interrupted; last known up at 2021-12-19 14:49:29 UTC web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). db_1 | 2021-12-19 14:50:53.782 UTC [27] FATAL: the database system is starting up web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | psycopg2.OperationalError: FATAL: the database system is starting up web_1 | web_1 | web_1 | The above exception was the direct cause of the following exception: web_1 | web_1 | Traceback (most recent call last): web_1 | File … -
How to create an array inside an object when working with MongoDB using Django?
I am working on a project where I want my user model to have this structure. structure { "_id":{ "$oid":"61bf3e026ffc7993a082773e" }, "email":"user@domain.com", "role":"student", "type":"t1", "fname":"ABC", "from":{ "org-user":[ "83bf3e026ffc7993a0827731", "78bf3e026ffc7993a0827731" ] } } In this model, "from" is the object which has one key "org-user". This "org-user" is an array of mongodb object IDs. This is the code I have written so far. from djongo import models class User(models.Model): class Meta: db_table = "users" _id = models.ObjectIdField() email = models.EmailField( max_length=255, unique=True, ) role = models.CharField(max_length=255, default="student") type = models.CharField(max_length=255, default="internal") fname = models.CharField(max_length=255) any idea on how I can achieve this in Django? -
how to update only the file field in model using django rest..i use angular as frontend
I want to update only specific fields in my model. This is my models.py class CheckinQnResult(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True,related_name='client_create') appt = models.ForeignKey(Appointment, null=True, blank=True, on_delete=models.SET_NULL, related_name='appt_qn') is_first_visit = models.BooleanField(default=False) document = models.FileField(upload_to='documents', null=True, blank=True) duration_of_sickness = models.CharField(max_length=100, null=True, blank=True) age_noticed = models.CharField(max_length=100, null=True, blank=True) first_sought_age = models.CharField(max_length=100, null=True, blank=True) med_treated = models.CharField(max_length=1000, null=True, blank=True) I want to update only specific fields in my model. This is my view.py class DocumentView(ViewSet): model = CheckinQnResult serializer_class = DocumentAlldataSerializer permission_classes = [IsAuthenticated] authentication_classes = [BasicAuthentication, TokenAuthentication, JSONWebTokenAuthentication] def create(self,request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): ch_qn = serializer.save() appt = Appointment.objects.get(id=request.data.get('appt_id')) appt.save() ch_qn.appt = appt ch_qn.save() return Response({'status': 'success', 'message': 'Check in questions submitted successfully'}, status=status.HTTP_200_OK) else: return Response(serializer.errors) def getdocument(self,request): queryset = CheckinQnResult.objects.filter(client=request.user) serializer = DocumentAlldataSerializer(queryset,many=True) return Response({'status':'success','data':serializer.data},status=status.HTTP_200_OK) ) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = CheckinQnResult.objects.get(id=request.data['id']) serializer = self.serializer_class(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response({'status': 'success', 'data': serializer.data}, status=status.HTTP_200_OK) def delete(self, instance): instance = CheckinQnResult.objects.get(id=self.request.GET.get('id')) instance.delete() return Response({'status': 'success', 'message': 'Document Deleted successfully'}, status=status.HTTP_200_OK) I want to update only specific fields in my model. This is my serializer.py class DocumentAlldataSerializer(serializers.ModelSerializer): appt = AppointmentSerializer() client=UserSerializer() class Meta: model = CheckinQnResult fields = '__all__' extra_fields = ['appt','client'] Here … -
refresh_from_db in proxy model at Django, Process finished with exit code -1073741571 (0xC00000FD)
In Django project, I have a class, "ClassName" that has a table in postgresql. I also have Proxy class, inherit from "ClassName", with name "ProxyClassName". if run refresh_from_db() on instance of "ProxyClassName", everything is fine, but if I specify any fields, refresh_from_db(fields=['field1', 'field2', 'field3']), code will crash with error "Process finished with exit code -1073741571 (0xC00000FD)" I see it has something to do with stack overflow and stack size (Process finished with exit code -1073741571 (0xC00000FD) in Python), but how should I prevent this from happening?