Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the entry that i am making in database is not visible on frontend .Please help me out with this
I am trying to create a comment feature on my post .At initial level I just made a table comment and post. And made a manual entry in comment table through admin side but even that comments are also not available on the post(frontend).[It looks like the image given below][1] My models.py for post and comment looks like this: class Comment(models.Model): post=models.ForeignKey(MyPost,related_name="comments", on_delete=models.CASCADE) name=models.CharField(max_length=255) body=models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.subject,self.name) class MyPost(models.Model): pic = models.ImageField(upload_to="images\\", null=True) subject = models.CharField(max_length = 200) msg = models.TextField(null=True, blank=True) cr_date = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey(to=MyProfile, on_delete=CASCADE, null=True, blank=True) def __str__(self): return "%s" % self.subject I added this in html page: <h2> Comments</h2> <br/> {% if not post.comments.all %} No comments yet...<a href="#"> Add one</a> {% else %} <a href="#">Add Comment</a> <br/> {% for comment in post.comments.all %} <strong> {{ comment.name }} - {{ comment.date_added }} </strong> <br/> {{ comment.body }} {% endfor %} {% endif %} <br/> -
Save data to Django's model from HTML form without forms.py
I'm trying to save some data to database from html form, not django's form. So I'm not using forms.py at all (I don't want to be blocked by all that abstraction and same fields in models.py and forms.py) So I'm using standard generic view like this #views.py class EnigmaView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): return render(request, "main/enigma.html") def post(self, request, *args, **kwargs): posted_data = request.POST if posted_data['type_'] == "暗号化": random_len = randint(3, 30) generated_pass_list = array.array("b", ()) for _ in range(random_len): numb = RandomNumber(1, 9).get() generated_pass_list.append(numb) data_to_encode = ''.join(str(e) for e in generated_pass_list) Enigma.decoded = posted_data['value'] Enigma.encoded = data_to_encode Enigma.save(self) return render(request, "main/enigma.html") and trying to save it to the model like this #models.py from django.db import models class Enigma(models.Model): encoded = models.CharField(max_length=100) decoded = models.CharField(max_length=100) def __str__(self): return self.decoded which throws me an Error AttributeError: 'EnigmaView' object has no attribute '_meta' Is this mean I need to define form in forms.py with MetaClass ? Is there a way to save thge data without it? -
problems while adding mathtype to django-ckeditor
how to add mathtype to django-ckeditor? I tried a lot but it is not showing. I also tried ckeditor_config. blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah -
Dango Filter - Filter DateTime Value
i have json datetime like this { "datetime": "2020-09-11 11:09:52", } I tried to filter it something like this localhost:8000/api/v1/history?datetime=2020-09-11%2011:09:52. Here what i tried class AuditlogFilter(filters.FilterSet): datetime = filters.DateTimeFilter(method="datetime_filter") class Meta: model = CRUDEvent fields = ['datetime'] def datetime_filter(self, queryset, name, value): return queryset.filter(Q(datetime__icontains=value)) However i got empty value. Is there a way i can archieve it??? Thanks in advance... -
Value Error when submitting form in Django mysql
I am getting a value error when submitting a form in Django. I have successfully connected the MySQL database in XAMPP. I can not find a solution to this.Here is my form code, <form class="user" method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control form-control-user" id="Cus_name" name="Cus_name" placeholder="Enter Customer Name..."> </div> <div class="form-group"> <input type="text" class="form-control form-control-user" id="Cus_address" name="Cus_address" placeholder="Enter Address... "> </div> <div class="form-group"> <input type="email" class="form-control form-control-user" id="Cus_email" placeholder="Enter Email Address..."> </div> <div class="form-group"> <input type="text" class="form-control form-control-user" id="Purpose" placeholder="Enter Purpose..."> </div> <div class="form-group"> <input type="date" class="form-control form-control-user" id="Date" placeholder="Enter Date..."> </div> <div class="form-group"> <input type="time" class="form-control form-control-user" id="Time" placeholder="Enter Time..."> </div> <div class="form-group"> <input type="text" class="form-control form-control-user" id="Venue" placeholder="Enter Venue..."> </div> <button name="submit" type="submit" class="btn btn-success">Submit</button> <hr> </form> Here is my Views.py from django.shortcuts import render from .models import AppointmentDet from django.contrib import messages def InsertDetails(request): if request.method == 'POST': if request.POST.get('Cus_name') and request.POST.get('Cus_address') and request.POST.get('Cus_email') and request.POST.get('Purpose') and request.POST.get('Date') and request.POST.get('Time') and request.POST.get('Venue'): saverecord = AppointmentDet() saverecord.Cus_name = request.POST.get('Cus_name') saverecord.Cus_name = request.POST.get('Cus_address') saverecord.Cus_name = request.POST.get('Cus_email') saverecord.Cus_name = request.POST.get('Purpose') saverecord.Cus_name = request.POST.get('Date') saverecord.Cus_name = request.POST.get('Time') saverecord.Cus_name = request.POST.get('Venue') saverecord.save() messages.success(request, "details saved successfully!") return render(request, "appform.html") else: return render(request, "appform.html") Please help. -
Serializer key value pair data in django rest frameworks
I'm using hstore field in my project. Every things is working fine. I followed this approach to serialize hstore field and it is working fine. https://librenepal.com/article/use-jsonfield-with-django-rest-framework/ But my requirements is little bit different. I've some prepopulated data in data and some of them are confidential. Now I wan't serialize all the data except of key value pair data. i don't know is this is possible or not. If not sorry for this silly question. -
ModuleNotFoundError: No module named 'bootstrap4'. python crash course
i am running into that error. at first i had bootstrap3 installed in my project directory. it was throwing the same error after some googling i saw some troubleshoots advising to install bootstrap4 still am facing the same error. i need help. Below is my code. installing bootstrap4 pip install django-bootstrap4 settings.py setting for bootstrap bootstrap4 = { 'include_jquery':True, } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_logs.apps.LearningLogsConfig', 'users', 'bootstrap4', ] base.html {% load bootstrap4 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Learning Log</title> {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <!--static navbar --> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> </button> <a class="navbar-brand" href="{% url 'index' %}"> Learning Log</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'topics' %}">Topics</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a>Hello, {{ user.username }}.</a></li> <li><a href="{% url 'users:logout' %}">log out</a></li> {% else %} <li><a href="{% url 'users:register' %}">register</a></li> <li><a href="{% url 'users:login' %}">log in</a></li> {% endif %} </ul> </div> <!--/.nav-collapse --> </div> </nav> <div class="container"> <div class="page-header"> {% block header %}{% endblock header %} </div> <div> {% block … -
Python Django - returning posts to a user based on their group
I am trying to create my own Learning Management System (LMS) as a project to learn a range of programming languages. So far users can login/logout and register. However what i want the system to do is to return a post to the user specific to the group I have assigned to them in the admin page. EXAMPLE user:'Steve' is assigned to group:'Maths' When 'Steve' logs in, if there are any posts assigned to 'Maths' then i want only those posts to be shown on their homepage. Further to this, if 'steve' is in other groups, I want posts from those groups to also be displayed. Below is html of the homepage which i have created. with this i can only show all posts to a user if they are in a very specific group. I understand that somewhere i will need to do some python programming to get this to work. If you need to see any more of my code I will be more than happy to provide. Thank You :) <div class="row"> {% for group_for in request.user.groups.all %} {% if group_for.name == "Science" %} {% for work in homework %} <div class="row"> <div class="col s12 m6 14"> … -
2 Forms on same model not saving as same user - Django
I'm creating a questionnaire / survey, and have two forms (Model Form) built on the same model. These forms are called on separate views, but when saved they appear as separate users in the database. I'm not sure how to get them so save as the same user, I am already using the ' post = form.save(commit=False), post.user = request.user, post.save()' method to save the forms. Model: class QuizTakers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) industry_choices = ( (1, 'Service'), (2, 'Hospitality'), (3, 'Wholesale/Retail'), (4, 'Manufacturing'), (5, 'Agriculture') ) industry = MultiSelectField(choices=industry_choices, max_length=1, max_choices=1) company_name = models.CharField( max_length=100) email = models.EmailField(blank=True) score = models.FloatField(default=0) completed = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.company_name Forms: # Form for getting company name class QuizTakerForm(forms.ModelForm): class Meta: model = QuizTakers fields = ['company_name'] # Form for getting company industry class QTIndustryForm(forms.ModelForm): class Meta: model = QuizTakers fields = ['industry'] Views: # view for getting company name def start(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = QuizTakerForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required request.session['company_name'] = form.cleaned_data['company_name'] post = form.save(commit=False) post.user = request.user post.save() # … -
Last messages from every (sender, receiver) pair - django
Here my models.py file class Message(models.Model): sender = models.ForeignKey(User, related_name='user_sent_msgs', on_delete=models.CASCADE) receiver = models.ForeignKey(User, related_name='user_received_msgs', on_delete=models.CASCADE) text = models.CharField(max_length=255) sent = models.DateTimeField(auto_now_add=True) I need to list last message from every chat (sender, receiver) pair like: id sender receiver text sent 1 user1 user2 hi ... 78 user3 user1 ... ... 322 user11 user1 ... ... 1231 user1 user4 ... ... Here is my code to generate that list: def get_queryset(self): users = set() msgs = Message.objects.filter(Q(sender=user) | Q(receiver=user)).order_by('-sent') res = [] for msg in msgs: if msg.sender == user and msg.receiver.id not in users: users.add(msg.receiver.id) res.append(msg.id) elif msg.receiver == user and msg.sender.id not in users: users.add(msg.sender.id) res.append(msg.id) self.queryset = Message.objects.filter(pk__in=res).order_by('-sent') Above code is working, but looking for more professional and clean python (django orm) code Is there any optimal solution?? -
get Django "self.request.user" with Token authentication
I have a Django Rest/ Vue.js application. I was using basic Django authentication but since it is a Single Page Application, I switched to Token Authentication so I can manage login/logout/register through an endpoint and get a more consistent application. Overall is working fine but my main problem is that I made some permissions and override some viewsets. I have to disable them in order to have my app to work with token authentication: My permissions: from rest_framework import permissions class IsOwnReviewOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.restaurant_review.review_author == request.user class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.review_author == request.user And my viewset: class RestaurantReviewViewset(viewsets.ModelViewSet): queryset = models.RestaurantReview.objects.all().order_by("-created_at") def get_serializer_class(self): if self.request.method == 'GET': return serializers.RestaurantReviewGETSerializer else: return serializers.RestaurantReviewSerializer permission_classes = [IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly] def perform_create(self, serializer): serializer.save(review_author=self.request.user) So my guess is that Django can't find request.user, is it related to my new authentication? Can Token Authentication provide it? -
update_view - tags field (django-taggit)
I trying to build a Blog and for my tag system I thought would be great to use django-taggit but there is a probelem when I want to update the BlogPost This is how I add them when I create the Blog Post: tag1, tag2 ,tag3 And this is how it looks like when I try to update the Blog Post: [<Tag: tag1>, <Tag: tag2>, <Tag: tag3>] blog/forms.py from django import forms from .models import BlogPost, Category class BlogPostForm(forms.Form): title = forms.CharField() # slug = forms.SlugField() content = forms.CharField(widget=forms.Textarea) # class BlogPostModelForm(forms.ModelForm): choices = Category.objects.all().values_list('name', 'name') choice_list = [] for item in choices: choice_list.append(item) class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'category', 'content', 'publish_date', 'image', 'private', 'tags'] widgets ={ 'title': forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(choices=choice_list, attrs={'class': 'form-control'}), # 'slug': forms.TextInput(attrs={'class': 'form-control'}), 'content': forms.Textarea(attrs={'class': 'form-control'}), 'publish_date': forms.TextInput(attrs={'class': 'form-control'}), 'image': forms.FileInput(attrs={'class': 'form-control-file'}), 'private': forms.CheckboxInput(attrs={'class': 'form-check-label'}), 'tags': forms.TextInput(attrs={'class': 'form-control'}), } blog/views.py update_view @login_required(login_url='login') def blog_post_update_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) form = BlogPostForm(request.POST or None, instance=obj) if form.is_valid(): form.save(commit=False) form.save_m2m() return redirect('/blog') template_name = 'form.html' context = {"title": f"Update {obj.title}", "form": form} return render(request, template_name, context) Can anyone explain how can I fix this? -
Django rest nested child serializer (having reverse relation) list creation
I am new to django rest and currently working on serializers to handle nested creation of objects ModelB is the object whose instance is to be created and it has a reverse relation with modelC and has a direct relation with modelA ModelA has to fetched and passed to ModelB during its creation ModelC list is to be created alongwith ModelB Models class ModelA(TimeStampMixin, CoordinateMixin): name = models.CharField(max_length=150) class ModelB(TimeStampMixin): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) modelA = models.ForeignKey( ModelA, on_delete=models.PROTECT, related_name='modela_reverse' ) class ModelC(TimeStampMixin): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) modelB = models.ForeignKey(ModelB, on_delete=models.CASCADE, related_name='modelb_reverse') modelD = models.ForeignKey(ModelD, on_delete=models.CASCADE, related_name='modelD_reverse') class ModelD(TimeStampMixin): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=50) Serializers: class ModelDSerializer(serializers.ModelSerializer): class Meta: model = ModelD fields = ['name', 'uuid'] class ModelCSerializer(serializers.ModelSerializer): modeld = ModelDSerializer(many=False) class Meta: model = ModelC fields = ['modeld', 'quantity'] class ModelA(serializers.ModelSerializer): class Meta: model = ModelA fields = ['name', 'uuid'] read_only_fields = ['name'] def to_internal_value(self, data): modelA = ModelA.objects.get(**data) return modelA class ModelB(serializers.ModelSerializer): modelb_reverse = ModelCSerializer(many=True) modelA = ModelASerializer(many=False) class Meta: model = ModelB fields = ['modelb_reverse', 'modelA'] Uptil now i have been able to carry the creation of ModelB through its serializer when only nested modelA is included but i am stuck at … -
Django - serializing multiple rows to a list
I have three tables Vertex, Edge, Graph Vertex can be part of many graphs. can reoccur in the same graph. Edge table denotes the edge between any two vertices in a graph. Models class Graph(models.Model): id = models.TextField( primary_key=True, null=False) name = models.TextField() class Vertex(models.Model): id = models.TextField( primary_key=True, null=False) name = models.TextField() extras = models.JsonField() class Edge(models.Model): graph = models.ForeignKey( "Graph", related_name="edges") node = models.ForeignKey( "Vertex", related_name="g_vertex") dependency = models.ForeignKey( "Vertex", related_name="e_vertex") Serializers class VertexNameSerializer(serializers.ModelSerializer): class Meta: model = Vertex fields = ['name'] class VertexSerializer(serializers.ModelSerializer): class Meta: model = Vertex fields = ['name', 'extras'] class EdgeSerializer(serializers.ModelSerializer): node = VertexSerializer() dependency = VertexNameSerializer() class Meta: model = Edge fields = ['node', 'dependency'] class GraphSerializer(serializers.ModelSerializer): edges = EdgeSerializer(many=True) class Meta: model = Graph fields = ['id', 'name', 'edges'] depth = 3 GraphViewSet class GraphViewSet(viewsets.ModelViewSet): queryset = Graph.objects.all() serializer_class = GraphSerializer For the above Graph Tables: +-----+--------------+ | id | Name | +-----+--------------+ | g-1 | Sample Graph | +-----+--------------+ Vertex +-----+------+-------+ | id | Name | Extra | +-----+------+-------+ | v-1 | A | {} | | v-2 | B | {} | | v-3 | C | {} | +-----+------+-------+ Edge +-------+------+------------+ | Graph | Node | Dependency | +-------+------+------------+ … -
css is not working after converting of html to pdf in django
I am trying to convert html file to pdf for download purpose in django using xhtml2pdf library. But after convert to pdf , css is not working , anyone please help me out, here is my html code snippet <html lang="en"> <head> <meta charset="utf-8"> <title>Certificate</title> {% load static %} <link href="{% static 'koss/css/bootstrap.min.css' %}" rel="stylesheet"> <style> .test { position: relative; bottom: -309px; left: 331px; color: #151313; padding-left: 25px; padding-right: 20px; } #profile_image1{ margin-top: -147px; margin-left: 171px; } #profile_image2{ margin-left: 156px; } </style> </head> <body> <div class="test"> <h3>name 1</h3> </div> <div class="test"> <h3> name2 </h3> </div> <div class="test"> <h3>name3 </h3> </div> <img id="profile_image1" alt="image" class="img-fluid m-3" src="{% static 'koss/img/memcirti1.png'%}" onerror="imgError(this);"> <br> <img id="profile_image2" alt="image" class="img-fluid m-3" src="{% static 'koss/img/memcirti2.jpg'%}" onerror="imgError(this);"> </body> </html> How can i solve the problem? -
What is Django Databses connection string for Azure sql Database using user managed identities?
I am trying to connect to the Azure database using managed identity. But failing Can anyone help me with strings to use. -
I can't get the big file and post message, When I deloy django and vue in the server
1.I deloy the django and the vue to the server 2.When I upload a small file and post message, I can get the message and file; But when i upload a big file and post message, I can get the message is None and can't get the file. 3.This is my django source code. image_vul_name = request.POST.get("image_vul_name") image_vul_port = request.POST.get("image_vul_port") image_vul_rank = request.POST.get("image_vul_rank") image_vul_rank = float(image_vul_rank) image_vul_desc = request.POST.get("image_vul_desc") image_vul_lable = request.POST.get("image_vul_lable") docker_name = request.FILES['myfile'] image_name = docker_name.name[:-4]``` -
How to match URL for sending multiples values using reverse Django
Basically I have this in my admin.py return format_html( '<a class="button" href="{}" style="background-color:seagreen;">Enable</a>', reverse('crawlers_tasks_admin:click_enable', args=[obj.name, obj.nindex]) ) I am trying to send obj.name and obj.nindex to my function in view.py (btw obj.name and obj.nindex both are strings). When I click on this link using the Admin Panel of Django, It should trigger the function in views.py But due to the wrong regex matching it's not hitting the right URL in URLs.py Here is my function in views.py whom I am trying to send these values. def click_enable(request, nindex): # body of function is here Here is my urls.py path which actually needs some correction: path('crawler_scheduler_enable/(?P[a-zA-Z_\D]+)$', views.click_enable, name='click_enable'), -
Declare multiple Django relationships using the same column as the foreign key
Using Django ORM I want to declare multiple relationships that use the same column to reference entities from different tables. Though it looks quite strange it's a necessary measure. class First(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4) second = models.OneToOneField( 'Second', ondelete=models.DO_NOTHING, db_constraint=False, related_name='uuid', ) third = models.OneToOneField( 'Third', ondelete=models.DO_NOTHING, db_constraint=False, related_name='uuid', ) class Second(models.Model): first_uuid = models.UUIDField(primary_key=True) class Third(models.Model): first_uuid = models.UUIDField(primary_key=True) The code above doesn't work because Django complains it can't use the same column twice or something like this. Is there a legit way to do this without introducing additional columns? -
expo-image-picker send image to django restful api
I am new in react native. I am trying to build an ios app to upload image to gcs through django backend api server. when I upload a image to backend, django has received a InMemoryFile but nothing inside. I have no idea how to solve this problem. Could anyone help me please? my uploading code in expo django response -
problems when adding mathtype to django-ckeditor
I am making online examination system in django. in that, i need to integrate mathytpe with ckeditor. I tried to add . my code is something like this for ckditor: CKEDITOR_CONFIGS = { 'default': { 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'external_plugin_resources':[('ckeditor_wiris', 'https://www.wiris.net/demo/plugins/ckeditor/', 'plugin.js')], 'extraAllowedContent': ' '.join(mathElements) + '(*)[*]{*};img[data-mathml,data-custom-editor,role](Wirisformula)', 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source']}, {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']}, {'name': 'insert', 'items': ['Image', 'Table', 'HorizontalRule', 'SpecialChar', 'Mathjax','mathtype', 'PageBreak', 'Iframe']}, '/', {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, {'name': 'tools', 'items': ['Maximize', 'ShowBlocks']}, {'name': 'about', 'items': ['About']}, {'name': 'yourcustomtools', 'items': [ # put the name of your editor.ui.addButton here 'Preview', 'Maximize', ]}, ], 'toolbar': 'YourCustomToolbarConfig', 'mathJaxLib': 'https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML', 'tabSpaces': 4, 'extraPlugins': ','.join([ 'uploadimage', # the upload image feature # your extra plugins here 'div','autolink','autoembed','embedsemantic','autogrow', 'widget', 'lineutils', 'clipboard', 'dialog', 'dialogui', 'elementspath', 'mathjax', 'ckeditor_wiris' ]), } } I also added ckeditor_wiris plugin to /static/ckeditor/ckeditor/plugins/ But it is not displaying mathtype. how can i display it? -
vscode with django-template installed does not auto indent
I am using vscode to edit django template files. After installing django or django-template extensions the auto indent does not work anymore. before after Already tried: "files.associations": { "**/*.html": "html", "**/templates/*/*.html": "django-html" }, "emmet.includeLanguages": {"django-html": "html"}, -
Guys help me: In Django ManyToManyField missed in the database. how to rectify
models.py class Consumer_order(models.Model): name = models.ForeignKey(Consumer, on_delete=models.CASCADE) ac_no = models.CharField(max_length=32) newspaper = models.ManyToManyField(Newspaper,related_name="Consumer_ac_no") added_date = models.DateField(max_length=32,auto_now_add=True) def __str__(self): return str(self.ac_no) PG ADMIN Consumer_order model missed newspaper Django Admin has Consumer_order input Traceback : Traceback (most recent call last): File "C:\Users\userDocuments\Django\Project--Django\Pro_Venv\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) File "C:\Users\user\Documents\Django\Project--Django\Pro_Venv\NewspaperAPI\insert_data_script.py", line 10, in transfer_daily_data NameError: name 'self' is not defined {'id': 1, 'name_id': 1, 'ac_no': '10012435', 'added_date': datetime.date(2020, 9, 6)} {'id': 2, 'name_id': 1, 'ac_no': '2545254', 'added_date': datetime.date(2020, 9, 9)} -
How to upload image as multipart/form data in Django restframework?
I am trying to upload a image file from react and and when i tried to upload a file in response i can see that file sent as a multipart/fromdata but my response says that unsupported media type multipart/formdata i tried to use also parser_classes =[FileUploadParser] but then response says that file name is missing.Here is code of my bakcend so far what i did. Models.py class CarPhoto(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) car = models.ForeignKey(Car, models.CASCADE, verbose_name=_('car')) category = models.CharField( max_length=255, choices=CATEGORY, null=True, blank=True) sub_category = models.CharField(max_length=255, null=True, blank=True) file = models.FileField( _("Upload documents image"), null=True, blank=True, upload_to=document_upload_to, ) View.py class CarProfilePhotoView(RetrieveUpdateDestroyAPIView): parser_classes = [FileUploadParser] permission_classes = [OIsAuthenticated] serializer_class = serializers.PhotoCarSerializer def get_queryset(self): return models.Car.objects.filter(fleet__managers=self.request.user) def put(self, request, filename): request.user.profile = models.CarPhoto() request.user.profile.file.save( '%d.jpg' % request.user.profile.sub_category, request.data['file']) return Response({ "file": request.build_absolute_uri(request.user.profile.file.url), }) Serializer.py class CarPhotoSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) file = serializers.SerializerMethodField() class Meta: model = models.CarPhoto exclude = ['created_by', 'car'] def get_file(self, obj): if obj.file: return self.context['request'].build_absolute_uri(obj.file.url) def create(self, validated_data): validated_data['created_by'] = self.context['request'].user return super().create(validated_data) class PhotoCarSerializer(serializers.ModelSerializer): car_photo = CarPhotoSerializer( many=True, source="carphoto_set", required=False ) class Meta: model = models.Car fields = ["car_photo"] def update(self, instance, validated_data): if 'carphoto_set' in validated_data: ids_set = [ndata['id'] for ndata in validated_data['carphoto_set'] if 'id' in … -
Cannot get Cookie value set by django
I have a page that refreshes with data based on cookie set by django. I am using XMLHTTPRequest with AJAX to refresh page. I have a view that should fetch data based on cookie but when get request is made to that url, request.COOKIE returns None not even csrf. How can I get cookie set by django in this scenario? Thanks