Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why modelformset always returns error "this field is required"?
I try to render modelformset in a template manually and when I hit submit button it gives an error saying that "This field is required.". I create modelformset like this: from django.forms import modelformset_factory ImageFormset = modelformset_factory(PostImages, fields=('image',), extra=0, can_delete=True) formset = ImageFormset(queryset=post.postimages_set.all()) And when I render modelformset like this, everything works: {{ formset.management_form }} {{ formset.as_p }} But when I render it like this I get an error: {{ formset.management_form }} {% for f in formset %} <img src="/media/{{ f.image.value}}" style="max-width: 400px;" alt=""> {{ f.image }} {{ f.DELETE }} {% endfor %} -
Django redirects or react history?
For some time I've been developing a django rest/react app. I'm still a newbie in this topic and most of the time I apply just-working solutions to my project. Gradually I'm lerning new things. There is this topic that bothers me. In my app I have this like 'main view' with a nav bar and a drawer (simply from material-ui). In drawer I've declared some buttons for navigation. Now the only view/layout changing is this empty space excluding nav bar and drawer (on the left). So it's facebook-like layout (with only middle part changing when navigating trough main stream or groups/pages). Those buttons in drawer use history.push() from react, as it was easiest to apply, but I wonder is it the right way ? Django has it's redirections, shouldn't I use those ? There is not much of a comparison between history and redirect. Something interesting I've found is: React-Router - Link vs Redirect vs History . Also, I've implemented a simple login and django auth, but with axios.posting I'm able to trace this this request in browsers network. Is there a better, or more important a safer way of requesting ? -
View.py changes not updating on Django site
New Django user. Hello world. Got it to work. "Hello, world!" in the browser. I went back into views.py and updated the line to read "Hello, world! You're at the index." and saved it. Refreshing the browser (F5) does not show the change. Even Ctrl-F5 doesn't refresh it. I'm running ./manage.py runserver, and it recognizes that the file was changed and reloads the site: /home/pi/pidjango/doorbell/views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 14, 2021 - 14:00:19 Django version 3.1.7, using settings 'pidjango.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But refreshing the browser still shows the old line. I have to reboot the computer in order to see the change. But it does change, so I know the file is the correct one in the correct spot. I'm not even sure what this is called. It's some kind of cache that's not flushing, so I researched Django caching and couldn't find anything that helped. I'm running '''DEBUG = True''', so you'd think this would be a pretty common thing to do. This is on a headless Raspberry Pi, connected by SSH, so there's no local … -
communication feature in django / vuejs
I have been asked for a project to developp a communication feature for a website that is implemented in vue.js for the front-end and Django in back-end. The goal would be to have a video,voice and chat options and to have an option of constant surveillance like a baby monitor would do on one end. I have researched many options and found that WebRTC might solve this issue. However I am still looking for diverse already made options that would avoid me too much implementation work. Does somebody has a good advice or know some tools that could help me ? Thank you very much and have a great day! -
Pass parameters from Django template to view
I am pulling data from an API and passing it through to my template. I would like to give users a few options and to do so I need to pass those options from my template to the params for the API in my view. What is the best way to go about doing that? For instance, I am rendering a game schedule and I need to change the value for "league" or "date" in the params via a button click. view params = {"league": "nba", "date": "2021-03-14"} results = requests.request("GET", URL, headers=headers, params=params).json() -
Django: Add class to a div depending on a variable
I'd like to declare in the template a variable that allows me to position an image inside a section on the left or the right. I just don't understand how can I do it on the variable side. Here's my current code, main.html : {% with img_left=False %} {% include 'section-service.html' %} {% endwith %} section-service.html: <div class="sect_service-inside {% if img_left=True %} serv_img-left {% else %} serv_img-right {% endif %}"> <div id="here_img">...</div> <div id="here_text">...</div> </div> but I get the error Could not parse the remainder: '=True' from 'img_left=True' Note that I'll use this section multiple times in the main.html page, that's why I'd like to have the variable left-right. -
How to aggregateSUM all keyvalues(=cost) from a field(payment) (one to one relationship) of a model(Session)
I would like to traverse a (one to one relationship) field of session. Specifically the payment and for each Session-payment aggregate Sum all the payment.cost Something like for each session-payment (if payment exists) aggrSum all the cost VALUES. in my views.py (sthing gotta change) "TotalCost": ( sessions.values_list("payment").aggregate(Sum("cost")) ), models.py. (these are my stable files) class Payment(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) payment_req = models.BooleanField(default=False) cost = models.FloatField(blank=True, validators=[validate_positive]) invoice = models.CharField(max_length=100) user_id = models.ForeignKey(User, on_delete=models.CASCADE) # session_id = models.OneToOneField(Session, on_delete=models.CASCADE) def __str__(self): return str(self.id) class Session(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) payment = models.OneToOneField(Payment, on_delete=models.CASCADE) user_comments_ratings = models.TextField() def __str__(self): return f"Id = {self.id}" -
How to set custom model manager as a default model manager in Django?
I have multiple apps and models in Django project. Now i want to use custom model manager in all apps models. i don't want to write custom model manager query inside of every single model. I just want to know is that possible to set custom model manager as default models manager for all apps? manager.py class CustomQuerySet(models.Manager): def get_queryset(self): return super(CustomQuerySet, self).get_queryset().filter(status=True) -
Change the color of the icon in jquery (django project)
I added to the wish list for products.(django project) Users click on a heart-shaped icon if they add a product to this list. If a user has already added this product to the list, the heart icon is red, and if this product is not in the user's favorites list, the heart icon is white. I want to change the color of the icon each time I remove or add it to the list. In the code I wrote, this operation is done only once, and if it clicks again at the same time, there will be no change in color. {% if request.user in product.favourite.all %} <a href="{% url 'home:favourite' product.id %}" class="favourite-product fa-btn{{ product.id }}" data-id='{{ product.id }}' data-text="remove"> <i class="fa fa-heart test{{ product.id }}" style="color:red"></i></a> {% else %} <a href="{% url 'home:favourite' product.id %}" class="favourite-product fa-btn{{ product.id }}" data-id='{{ product.id }}' data-text="add"> <i class="fa fa-heart test{{ product.id }}" style="color:#eee;"></i></a> {% endif %} # ajax $(document).on('click', '.favourite-product', function (e) { e.preventDefault(); const likeText = $(`.fa-btn${product_id}`).attr("data-text"); const trim = $.trim(likeText) $.ajax({ url: $(this).attr('href'), type: 'GET', data: { 'product': product_id }, success: function (response) { if (trim === 'add') { $(`.test${product_id}`).css({"color": "red"}); } else { $(`.test${product_id}`).css({"color": "#eee"}); } }, error: … -
When I run my django project, I face this issue. Kindly help me to resolve this
Traceback (most recent call last): File "C:\Users\SARAVANAN\Envs\test8\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) -
Django: Specific unique_together condition
I have a model Article: class Article(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) class Meta: unique_together = ('author', 'title') The method get_sentinel_user: def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted')[0] Thus, using on_delete=models.SET(get_sentinel_user), I save posts after deleting the author (if he agrees to this, I ask him in a separate form). And instead of a real author, I set a "stub"-user as the author for his posts. In such a situation, there is a problem with the uniqueness condition. If two users had articles with the same title and then one of them was deleted, then an error will occur when trying to delete the second user. Accordingly, I would like this error to be absent. So that the uniqueness condition applies only to real users and their articles. class Meta: constraints = [ models.UniqueConstraint( name='unique_combiantion_article_name_and_author', fields=['title', 'author'], condition=~models.Q(author__username='deleted') ) ] But then I made sure that this does not work, we cannot use author__username. Right now I'm thinking about just overriding validate_unique method. But first I would like to ask for advice. Maybe there is some other solution for this problem. Thanks for any help. -
nginx and hosting a server name domain
I want to connect my ip adresse to a domain name. When I run in a browser "my.ip.adress" the server responds but when I try with "mydomain.com" it doesn't work. I have a 404 error. In my hosting platform I linked "my.ip.adress" to the domain name. I have wait 48 hours as it's recommended to link ip with domaine name. I'm not sure of the configuration that I did. Maybe my env file ".env-prod" is not call and the pipes break Could you help me the folder representation: env/ myblog/ mysite/ settings.py wsgi.py … scripts/ static/ my env file : .env-prod export DEBUG=off export SECRET_KEY='mysecretkey' export ALLOWED_HOSTS="['my.ip.adress', 'mydomain.com', 'www.mydomain.com']" export DATABASE_URL=postgres://user:password@db.example.com:5432/production_db?sslmode=require I have this /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target I have /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/myblog ExecStart=/home/ubuntu/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ mysite.wsgi:application [Install] WantedBy=multi-user.target I have also /etc/nginx/sites-available/myblog server { listen 80; server_name my.ip.adress; # could I have mydomain.com and www.mydomaine.com there ? root /home/ubuntu/myblog/; location /static { alias /home/ubuntu/myblog/static/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8000; break; } } } In my /etc/nginx/sites-available/default server … -
Django tables 2 - how do i change the queryset of the model i am displaying?
I'm trying to display all model objects after a get request in a table using django-tables2. It's currently displaying all and I can't figure out how to filter the queryset based on a model pk in my view: views.py class ViewJob(LoginRequiredMixin, SingleTableView): model = JobResults table_class = JobResultsTable template_name = 'app/viewjobresults.html' paginator_class = LazyPaginator table_pagination = {"per_page": 30} def get_context_data(self, **kwargs): """ ViewJob get_context_data request """ context = super(ViewJob, self).get_context_data(**kwargs) print("ViewJob >get_context_data()") context['job_obj'] = Job.objects.get(pk=self.kwargs.get('pk')) # context['object_list'] = context['object_list'].filter(job_id=context['job_obj'].id) return context template - app/viewjobresults.html {% extends "base.html" %} {% load render_table from django_tables2 %} {% render_table table %} {% endblock %} tables.py class JobResultsTable(tables.Table): job = tables.Column( accessor='job_id.job_name', verbose_name='Job') results = tables.Column( accessor='results', verbose_name='Result') class Meta: attrs = {"class": "table is-bordered"} Currently the table rendered is ALL Job objects in a queryset. I have the specific job_obj in my view get_context_data() to filter this, but when i filter context['object_list'] (line hashed out) it still displays the entire list of JobResults. How can I change the queryset given to the table? -
How can I add a "snooze" button in Django with Ajax?
In my Django app I want to have a snooze button, which I want to use in order to postpone a deadline for an object. The corresponding model has a datefield called alarm and I want to pass the snooze command together with a number x of days that should be added to the current setting. So far I found out that I cannot do this directly from the template and multiple sites suggested the use of Ajax. I have never used that. My files look like this. views.py def Operation_Snooze_Method(request): print(request) if request.POST: if request.is_ajax(): print("Ajax") # I guess here I would handle the alarm if I could bring the Ajax call to work at all. else: print("no ajax") print(request.POST) return render(request, templ_folder_name + landingpage) part of my models.py class Operation(models.Model): title = models.CharField(max_length=255, blank=False, null=False, verbose_name="Title of the operation") alarm = models.DateField(verbose_name="Date of the alarm", null=True, blank=True) [...] def Operation_Snooze(self,x): self.alarm = datetime.now() + timedelta(days=x) urls.py path('snooze/', views.Vorgang_Snooze_Method, name="snooze"), my base.html, which is the template that I extend with my other templates $document.ready(function(){ $("#snooze").submit(function(event){ event.preventDefault(); $ajax({ type:"POST", url:"{% url 'app_name_myproject:snooze' %}", data:{ 'id':$('#snooze').val() 'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val() }, }); return false; };) }); </script> [...] {% if urgent_operations %} # this … -
why does my django project keep showing no assignment even after upload them?
I' unable to show the error as there is no traceback, there seems to be a problem in my code that I am unable to sort. My project is assignment submissions platform, and in the student submission page it shows that there are no assignments even though I ahve created alot of them. I'm pasting my code below, please do have a look and any sort of help would be really appreciated. Views.py # for Teacher to create assignment. @login_required def upload_assignment(request): assignment_uploaded = False teacher = request.user.Teacher students = Student.objects.filter(user_student_name__teacher=request.user.Teacher) if request.method == 'POST': form = AssignmentForm(request.POST, request.FILES) if form.is_valid(): upload = form.save(commit=False) upload.teacher = teacher students = Student.objects.filter(user_student_name__teacher=request.user.Teacher) upload.save() upload.student.add(*students) assignment_uploaded = True else: form = AssignmentForm() return render(request,'upload_assignment.html',{'form':form,'assignment_uploaded':assignment_uploaded}) # for students to view all the assingments @login_required def class_assignment(request): student = request.user.Student assignment = SubmitAssignment.objects.filter(student=student) assignments_list = [x.submitted_assignment for x in assignment] return render(request,'class_assignment.html',{'student':student,'assignment_list':assignment_list}) Models.py class logger(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Student') name=models.CharField(max_length=250) roll_no = models.CharField(max_length=50) email = models.EmailField(max_length=254) def __str__(self): return self.name class Meta: ordering = ['roll_no'] class Teacher(models.Model): username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Teacher') name = models.CharField(max_length=250) subject_name = models.CharField(max_length=250) email = models.EmailField(max_length=254) students = models.ManyToManyField(Student, related_name="teachers", through="StudentsInClass") def __str__(self): return self.name … -
Drf throttling restart when POST
I created some app and want to set up different throttling for GET/POST,PUT,PATCH. When I make a GET request, it works fine. But when I perfom POST/PUT/PATCH it looks like cache is restarted. I want to create also extra headers so that's why I think this is actually the problem. Throttling.py class SetHeaders: def throttle_success(self): self.history.insert(0, self.now) self.cache.set(self.key, self.history, self.duration) print(self.key, self.history, self.duration) print(f"REMAIN TIME {self.duration - (self.now - self.history[-1])}") print(f'LIMIT {self.get_rate()}') print(f'REMAIN RATE {self.num_requests - len(self.history) + 1}') return True class UserPostRateThrottle(SetHeaders, throttling.UserRateThrottle): scope = "user_post" def allow_request(self, request, view): if request.method == "GET": return True return super().allow_request(request, view) class UserGetRateThrottle(SetHeaders, throttling.UserRateThrottle): scope = "user_get" def allow_request(self, request, view): if request.method in ("POST", "PUT", "PATCH"): return True return super().allow_request(request, view) views.py class TruckViewSet(viewsets.ModelViewSet): queryset = Truck.confirmed.all() serializer_class = TruckSerializer filterset_class = TruckFilter permission_classes = ( permissions.DjangoModelPermissions, IsOwnerOrReadOnly, ) throttle_classes = (UserGetRateThrottle, UserPostRateThrottle) def _get_images(self, request): for img in request.data.getlist("image"): image_serializer = TruckImageSerializer(data={"image": img}) image_serializer.is_valid(raise_exception=True) def create(self, request, *args, **kwargs): if request.data.get("image"): self._get_images(request) return super(TruckViewSet, self).create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save(owner=self.request.user) def update(self, request, *args, **kwargs): if request.data.get("image"): self._get_images(request) return super(TruckViewSet, self).update(request, *args, **kwargs) serializers.py class TruckSerializer(serializers.ModelSerializer): location = LocationSerializer( read_only=True, ) owner = serializers.PrimaryKeyRelatedField( read_only=True, ) name = … -
Hot re return a costume error mesage in graphene?
I created the following class to update the post in spesfic conditions but if the contitions ==False the I need to return {"message": "Only the owner of the post and the admin(website's wonr) can edit and delet this post"} But the JsonResponse don't work likt it is with RestFramework! class UpdatePost(graphene.Mutation): # owner(added_by)+admin can update and delete class Arguments: id = graphene.Int(required=True) description = graphene.String() post = graphene.Field(schema.Posts) @classmethod def mutate(cls, root, info, id, description): post = models.Post.objects.get(id=id) if (info.context.user == post.added_by): post.description = description post.save() return CreatePost(post=post) else: JsoneResponse({"message": "Only the owner of the post and the admin(website's wonr) can edit and delet this post"}) -
Reverse for '' not found. '' is not a valid view function or pattern name - django fix
When trying to create the get_absolute_url. Am geting this error, am not sure why since i searched and i saw many tutorials but couldnt figure out why. -
Chaining multiple filter() in Django returning nothing
I was trying to filter two conditions but it's not returning anything That's the function that has the condition i'm using def airport_view(request, code): airport = Airport.objects.get(code=code) flights = Flight.objects.filter(origin=airport).filter(destination=airport) context = { 'airport':airport, 'flights':flights } return render(request, "flights/airport.html", context) The airport works normally but the multiple filter chain doesn't work, even that i got three flights which has one of both conditions That's the related models if it helps you class Airport(models.Model): code = models.CharField(max_length=64) name = models.CharField(max_length=64) class Flight(models.Model): origin = models.ForeignKey('Airport', on_delete=models.CASCADE, related_name="From") destination = models.ForeignKey('Airport', on_delete=models.CASCADE,related_name="To") passengers = models.ManyToManyField('Person', blank=True) -
Get Bounding Box from Django PolygonField
I am trying to get the bounding box for a PolygonField in a Django model. I read here that you can use extent but when running the below as per the extent documentation: qs = newJob.objects.filter(pk=1).aggregate(Extent('loc')) print(qs['loc__extent']) I get the error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: function st_extent(geography) does not exist LINE 1: SELECT ST_Extent("app_newjob"."loc") AS "loc__ext... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. My model (simplified) looks like this: class newJob(models.Model): name = models.CharField(max_length=64) desc = models.CharField(max_length=64) loc = models.PolygonField() And in my test: from django.contrib.gis.db.models import Extent newJob.objects.create( name="test", desc="test", loc="SRID=4326;POLYGON ((0.9063720703125029 52.32023207609735, 0.8239746093749998 52.10819209746323, 1.170043945312496 52.14191683166823, 1.170043945312496 52.31351619974807, 0.9063720703125029 52.32023207609735))" ) qs = newJob.objects.filter(pk=1).aggregate(Extent('job_loc')) I'm running a PostGIS database on the back. Any ideas what I'm doing wrong? -
Django create field in ModelForm if condition is True
I am going to have a Product, which can have some variations, and also Product, which has no variants. So for the first case, there should be fields 'quantity' and 'variant' select box rendered. For the second case, only a field with 'quantity' should be rendered because the product has no variants. Is possible to do that somehow with ModelForms? This is my form, where now quantity and variant is mandatory to fill: class AddToCartForm(forms.ModelForm): variant = forms.ModelChoiceField( queryset=ProductVariant.objects.none(), ) quantity = forms.IntegerField(min_value=1, initial=1) class Meta: model = OrderItem fields = ['quantity', 'variant'] def __init__(self, *args, **kwargs): self.product_id = kwargs.pop('product_id') product = Product.objects.get(id=self.product_id) super().__init__(*args, **kwargs) self.fields['variant'].queryset = product.variant.all() def clean(self): product_id = self.product_id product = Product.objects.get(id=self.product_id) quantity = self.cleaned_data['quantity'] if product.stock < quantity: raise forms.ValidationError( f'The maximum stock available is {product.stock}') Thanks for any help! -
Django Choices field to add to cart function
I have an app with a choices field for prices. Two of the categories have a Choices field. I tried to get the desired size of the customer by using the request.POST.get script on the views.py to get the value of the price, but it's not showing up. Views.py @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, customer=request.user, ordered=False, price = request.POST.get('inlineRadioOptions') ) order_qs = Order.objects.filter(customer=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.price = request.POST.get('inlineRadioOptions') order_item.price order_item.item_quantity += 1 order_item.save() messages.success(request, "This item was updated to your cart." ) else: messages.success(request, "This item was added to your cart." ) order.items.add(order_item) order.save() else: order = Order.objects.create( customer=request.user) order.items.add(order_item) order.save() messages.success(request, "This item was added to your cart." ) return redirect("featured-food", slug=slug) On Views.py, I added price as a parameter and use the script request.POST.get('inlineRadioOptions') to get the value of the selected radio button, but it does not work. Models.py class Item(models.Model): name = models.CharField(max_length=50) categories = models.CharField(choices=CATEGORY_CHOICES, max_length=50) sizes = models.CharField(choices=SIZES_CHOICES, max_length=50, null=True, blank=True) cake_size = models.CharField(choices=CAKE_CHOICES, max_length=50, null=True, blank=True) img = models.ImageField(upload_to=get_upload_path, null=True, blank=True) description = models.TextField() beverage_s_price = models.FloatField(null=True, blank=True) beverage_t_price = models.FloatField(null=True, blank=True) beverage_g_price = models.FloatField(null=True, blank=True) beverage_v_price = models.FloatField(null=True, blank=True) … -
Django - make signal wait for file to be ready
Im experiencing a wired issue using Django signals. Each time a user saves a new avatar onto his profile also a thumbnail version of the picture gets saved beside the high quality version. This is working fine until the image should get changed or delted, here I have written two signals to handle both fileds, the avatar and the avatar_tn field. For some reason my signals are working sometimes and sometimes not, especially they have problems if the underlining filesystem is remote, like NFS, CIFS or iSCSI. It seems that the signal always expects that the file is ready and already written, which is obviously not the case due to network and I/O-Delay ... signals.py # Runs on avatar deletion @receiver(models.signals.post_delete, sender=User) def avatar_auto_delete_files(sender, instance, **kwargs): if instance.avatar: if os.path.isfile(instance.avatar.path): os.remove(instance.avatar.path) if instance.avatar_tn: if os.path.isfile(instance.avatar_tn.path): os.remove(instance.avatar_tn.path) # Runs on avatar change @receiver(models.signals.pre_save, sender=User) def avatar_auto_delete_files_on_change(sender, instance, **kwargs): if not instance.pk: return None try: old_avatar = sender.objects.get(pk=instance.pk).avatar old_avatar_tn = sender.objects.get(pk=instance.pk).avatar_tn except sender.DoesNotExist: return None if not old_avatar: return None new_avatar = instance.avatar new_avatar_tn = instance.avatar_tn if not old_avatar == new_avatar: if os.path.isfile(old_avatar.path): os.remove(old_avatar.path) if old_avatar_tn == new_avatar_tn: if os.path.isfile(old_avatar_tn.path): os.remove(old_avatar_tn.path) Is there any way I can make the signal wait for … -
How pass parameter in this method?
Hello I'm newbie Python user. I study now django queryset. but query.pyi in _BaseQuerySet's method def values(self, *fields: Union[str, Combinable], **expressions: Any) -> ValuesQuerySet[_T, Dict[str, Any]]: ... I want to pass a parameter to that function, but the first code runs, but the second code does not. error code not error code Full code Run with response error What should I do to get it running normally? -
how to save converted json data into database column in django
so basically, i request to develop a upload function allow the user upload a dataset, in the same time, the backend will convert the dataset into json format and save to database column. For example, the database design be like ['id', 'name', 'file', 'json_format']. However i can't do that while upload the file it will show error for it. this is my models.py: class Document(models.Model): name = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='') uploaded_at = models.DateTimeField(auto_now_add=True) json_format = models.JSONField() This is my forms.py: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('name', 'document') This is my view.py: def home(request): file_data = Document.objects.all() error_message = False #Upload CSV FILE if request.method == 'POST': form = DocumentForm(request.POST,request.FILES) if form.is_valid(): if form.data['name']: # Check existing data if Document.objects.all().filter(name=form.cleaned_data.get("name")).exists(): form = DocumentForm() error_message = True return render(request,'home.html', {'form':form, 'file_data': file_data,'error_message':error_message}) else: #form.save() get_name = form.name get_file = Document.objects.get(name=get_name) read_file = p.read_csv(get_file) #read file convert_to_json = read_file.to_json #convert the dataset to json form.save(update_fields=['json_format']) #update the json to column return redirect('/') else: form = DocumentForm() return render(request,'home.html', {'form':form, 'file_data': file_data})