Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, how can the Graphene GraphQL endpoint be protected for API usage?
Graphene provides a GraphQL integration into Django and supplies a view to create a URL endpoint. The question is how can the endpoint be protected for API usage? The recommend method is to use a LoginRequiredMixin which is great for logged in users, but not for use as an API. I've tried integrating it with DRF tokens, but still end up with the session middleware requiring CSRF. The only solution that works is adding a CSRF exempt decorator, but I fear that this opens up a security vulnerability. # urls.py path("graphiql/", root_views.SessionGraphQLView.as_view(graphiql=True), name="graphiql"), path("graphql/", root_views.TokenGraphQLView.as_view(graphiql=False), name="graphql"), # views.py class TokenLoginRequiredMixin(AccessMixin): """A login required mixin that allows token authentication.""" def dispatch(self, request, *args, **kwargs): """If token was provided, ignore authenticated status.""" http_auth = request.META.get("HTTP_AUTHORIZATION") if http_auth and "Token" in http_auth: pass elif not request.user.is_authenticated: return self.handle_no_permission() return super().dispatch(request, *args, **kwargs) @method_decorator(csrf_exempt, name="dispatch") class TokenGraphQLView(TokenLoginRequiredMixin, GraphQLView): authentication_classes = [TokenAuthentication] class SessionGraphQLView(LoginRequiredMixin, GraphQLView): pass -
Django modelform not saving
I've had a google, a look through the other topics on here too. Still my form isn't saving. View def newapprentice(request): form = NewApprenticeForm() if request.method == 'POST': #print('Printing POST:', request.POST) form = NewApprenticeForm(request.POST) if form.is_valid(): form.save() return redirect('apprentices/index.html') return render(request, 'apprentices/newapprentice.html', {'form': form}) Template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>New Apprentice</h1> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.name|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.email|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.role|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.cost|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.p_name|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.p_time|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.division|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.line_manager|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-4 mb-0"> {{ form.on_course|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.finished_course|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.left_course|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.start_date|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.finish_date|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.notes|as_crispy_field }} </div> </div> <button … -
Can I use Django and HTML extensions at the same time in VSCcode?
I recently started learning Django and when I am writing templates, I have to switch between HTML and Django HTML extensions to use the tab for autocompletion. With the HTML extension, I can autocomplete the tags using the tab but when Django HTML is in use, it does not work anymore and have to write all the tags manually. Switching between the two is also frustrating, and sticking with the HTML extension means writing the Django syntax (eg. loops, if, and so on) manually also. Is there any extension that provides this? Or is there any way to use both at the same time? If not, even a quick shortcut for switching between the two would help. Thanks. -
Append data in select (option) got from server
I am trying to append the data got from Server via AJAX task in the select options but whenever the append function get executed by clicking the select Button(Day) each time the data get appended like this: 1, 2 ,3.... 1, 2, 3 Means the same data gets appended multiple times. <div class="form-group col-sm-3 d-inline-block" style="padding: 0px;"> <select class="form-control" id="Day" name='day' onclick="get_max_np_date()"> <option disabled selected>Day</option> <script> var max_day; function get_max_np_date() { //Return the maximum Days in Nepali Date System (Bikram Sambat) var get_year = document.getElementById('Year') var get_month = document.getElementById('Month'); year = get_year.options[get_year.selectedIndex].value; month = get_month.options[get_month.selectedIndex].value; console.log(Boolean(year && month)); if (year && month){ $.ajax({ url: 'max-np-day', type: 'get', data: { 'year':year, 'month':month }, success: function (data) { max_day = data; var days; DayElm = document.getElementById("Day") for (days = 1; days <= max_day; days++) { var optionElm = document.createElement("option"); //optionElm.value = days; var daysNode = document.createTextNode(days); optionElm.appendChild(daysNode) DayElm.appendChild(optionElm) } // var node = document.createElement("LI"); //var textnode = document.createTextNode("Water"); /// node.appendChild(textnode); //document.getElementById("myList").appendChild(node); } }) } }; </script> </div> -
Set the ROOT URL for Django Application in Apache
Running my Django App in localhost, working absolutely fine. But as I hosted it on Apache, the url got set to 10.5.10.28/myportal/ and when I try to click a button to switch to another page its taking URL as 10.5.10.28/list which is not found. It should take 10.5.10.28/myportal/list/ to work fine. Or 10.5.10.28/myportal/add/ or 10.5.10.28/myportal/search/ I want 10.5.10.28/myportal/ to be my root URL and rest path should switch after this. from django.urls import path from Device import views urlpatterns = [ # path('admin/', admin.site.urls), path('', views.main_page, name='main'), path('list/', views.list_system, name='list'), path('listdevice/', views.list_device, name='listDevice'), path('search/', views.search, name='search'), path('searchresult/', views.searchresult, name='searchresult'), path('add/', views.add, name='add'), path('addalert/', views.addalert, name='addalert'), # path('delsys/', views.delsys, name='delsys'), # path('deldev/', views.deldev, name='deldev'), path('delmsg/<str:sysin>/<str:sys>/', views.delmsg, name='delmsg'), path('update/<str:sysin>/<str:sys>/', views.update, name='update'), path('updatemsg/<str:dev>/', views.updatemsg, name='updatemsg') ] -
How to add length of 2 lists which has dictionaries it it in Django
I have two lists, both the lists are having number of dictionaries. eg.: list_one = [{"key1": "value"}, {"key1": "value"}] list_two = [{"key2": "value"}, {"key2": "value"}] I want to add length of these two lists in django template tag, so the output will be 4 in this case. I have tried with below but couldn't make it. {{ list_one|length|add:list_2|length }} Please help. -
(venv) (base) both active on a python project
So I am using vscode with conda (for a django project), and trying to activate my virtual environment named "venv". And it goes from: (base) C:\Users\User\Desktop\pfa-master\pfa-master\venv\Scripts> .\activate to something like this: (venv) (base) C:\Users\User\Desktop\pfa-master\pfa-master\venv\Scripts> And if I try to find out Python version, it shows error like this: (venv) (base) C:\Users\User\Desktop\pfa-master\pfa-master>which python 'which' is not recognized as an internal or external command, operable program or batch file. Note: I have Python in environment variables for anaconda. What am I doing wrong? -
pass a parameter from view to context_processors
I have the following structure polls / context_processors.py: def link_list(request,link): link = link data = Page.objects.filter(link=link) return {'link':data} polls / views.py: ... content = { 'content':content } link = request.POST["link"] template = loader.get_template('pages/pages.html') response = HttpResponse(template.render(content , request)) return response what I want to do is to send a parameter from views( might set for each page depending on certain scenario) and and I want to pass this parameter to context_processors. is this possible ? -
when user reply to a comment it is showing time of comment. It should show actual time. How can I fix?
I am learning django. I am working on a blog. When user reply to a comment it is showing time of its parent comment. It should show actual time of reply. I attached a picture with this post.Please have a look , you will better understand my question. How can I fix? I tried but all in vain. may be it is a silly mistake from me or i am not getting it. Thanks in advance view.py def blogPost(request, slug): post = Post.objects.filter(slug=slug).first() comments = BlogComment.objects.filter(post=post, parent=None) replies = BlogComment.objects.filter(post=post).exclude(parent=None) replyDict = {} for reply in replies: if reply.parent.sno not in replyDict.keys(): replyDict[reply.parent.sno] = [reply] else: replyDict[reply.parent.sno].append(reply) context = {'post':post, 'comments':comments, 'user': request.user, 'replyDict': replyDict} return render(request, 'blog/blogPost.html',context) def postComments(request): if request.method == 'POST': comment = request.POST.get('comment') user = request.user postSno = request.POST.get('postSno') post = Post.objects.get(sno=postSno) parentSno = request.POST.get('parentSno') if parentSno == "": comments = BlogComment(comment=comment, user=user, post=post) comments.save() messages.success(request, 'Your Comment has been posted Successfully') else: parent = BlogComment.objects.get(sno=parentSno) comments = BlogComment(comment=comment, user=user, post=post, parent=parent) comments.save() messages.success(request, 'Your reply has been posted Successfully') return redirect(f"/blog/{post.slug}") models.py class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=200) content = models.TextField(max_length=10000) author = models.CharField(max_length=20) region = models.CharField(max_length=20) slug = models.CharField(max_length=50, default="") timestamp = … -
DRF not getting ImageField data
I am trying to update the post. #urls.py postdetail = BlogPostDetailView.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) path('<slug>/edit', postdetail, name='postdetail') #views.py class BlogPostDetailView(viewsets.ModelViewSet): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) #serializers.py class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = BlogPost fields = ('id', 'title', 'slug', 'category', 'thumbnail', 'content', 'date_created', 'author') lookup_field = 'slug' when I go to url to update a post, it shows thumbnail field empty " No file selected". Why it is not showing anything in thumbnail? -
Link back to main app ( path `/` ) from Sphinx docs
I'd like to link back to the main django app from theh sphinx documentation. Main app is hosted at root / Sphinx docs hosted at /docs Nginx serving app, docs and static files All configured in Docker w/ docker-compose Ideally, the link back should extend the small "menu" in the top right, so that instead of: (previous |) (next |) modules | index It would say : (previous |) (next |) modules | index | main app And link back to / for the main app link. Been having problems both adding the link, and then I've simply no idea how to force it where I want it even if I can. I tried this just above toctree, but nothing shows up: MainApp: MainApp_ .. _MainApp: / -
Django project - OPEN MODAL FROM BOOTSTRAP CARD
I'm working on a django project in which i have several bootstrap cards that display some datas that i get from the database. More precisely each cards represents a project, so it has its title, its description, its deadline and so on. At the end of the card i put a button to open a modal to show more details of the project that aren't displayed in the card. My problem is that I don't know how to take the right information of the cards for each modal, for example even if i click on the button of the third card to open the modali to view the detail of the third projects, the modal still shows me the data of the first project (so it takes them from the first card). Can anyone help me please? -
ReactJS - URL Paramaters to filter a search query
firstly, apologies for the horrible question title (edit suggestions welcome!) I'm very new to React and programming as a whole. As a side task, I've been asked to research how to include some date filters into a demo project my company has (I don't work in tech but want to learn). The idea is go filter some incoming messages so only messages between 2 certain dates are displayed. Basically I've been told that the filters are up and ready (Django back-end) to be used with the React front-end. However after fixing a few bugs here and there I can't figure out how to make the date filters actually filter the results. Django query filters: class ViewMessages(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) permission_classes = (permissions.MessagePermissions,) def limit_by_parameter(self, data): """ Include only those results which match all parameters (except search) """ query_set = DataMessage.objects.all() # Start with all email objects try: if data.get('id'): query_set = query_set.filter(pk=data.get('id')) if data.get('exhibit'): query_set = query_set.filter(exhibit_id=data.get('exhibit')) # Filter by foreign key if data.get('case'): query_set = query_set.filter(exhibit_id__case_id=data.get('case')) # Filter by foreign key (once removed) if data.get('source'): query_set = query_set.filter(data_source__iexact=data.get('source')) if data.get('datetime'): query_set = query_set.filter(datetime__gte=data.get('datetime')) if data.get('datetime_lower'): query_set = query_set.filter(datetime__gte=data.get('datetime_lower')) if data.get('datetime_upper'): query_set = query_set.filter(datetime__lte=data.get('datetime_upper')) if data.get('message_type'): query_set = query_set.filter(data_type__iexact=data.get('message_type')) … -
How can one serializer display information from another serializer?
After defining image model and like model, I will create a serializer corresponding to each and show it to PostSerializer. By the way, I put ImageSerializer and LikeSerializer in the PostSerializer field, but JSON does not display any information about these serializers. How can I display this information? Here is my code. models.py class Post (models.Model) : author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author', null=True) title = models.CharField(max_length=40, null=True) text = models.TextField(max_length=300, null=True) tag = models.CharField(max_length=511, null=True) view = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) def __str__ (self) : return self.title @property def comment_count (self) : return Comment.objects.filter(post=self.pk).count() @property def like_count (self) : return Like.objects.filter(post=self.pk).count() class Image (models.Model) : post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) class Like (models.Model) : liker = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) serializers.py class AuthorSerializer(serializers.ModelSerializer): profile = serializers.ImageField(use_url=True) class Meta: model = User fields = ('username', 'email', 'profile') class ImageSerializer (serializers.ModelSerializer) : image = serializers.ImageField(use_url=True) class Meta : model = Image fields = ('image') class LikerSerializer (serializers.ModelSerializer) : id = serializers.CharField(source='liker.pk') class Meta : model = Like fields = ('id') class PostSerializer (serializers.ModelSerializer) : author = AuthorSerializer(read_only=True) image = ImageSerializer(read_only=True, many=True) like_count = serializers.ReadOnlyField() liker = LikerSerializer(read_only=True, many=True) comment_count = serializers.ReadOnlyField() class Meta : model … -
how do i show individual questions in Django template like in online exam using next and previous buttons?
All questions are in Questions table. I am able to display one question but i need to display next questions one by one by clicking and next button like in online exam. Please answer my question. should i use java script for next and previous buttons. please post script also if need. Thank you views.py: def render_questions(request): questions = Questions.objects.all() ques_list = [] for question in questions: ques = {} ques['question'] = question.questions ques['option_a'] = question.option_a ques['option_b'] = question.option_b ques['option_c'] = question.option_c ques['option_d'] = question.option_d ques['answer'] = question.answers ques['ques_no'] = str(question.qs_no) ques_list.append(ques) print(f'{ques_list}', flush=True) return render(request, 'report.html', {'ques': ques_list}) template.html: <form action="answer" method="POST"> {% csrf_token %} {% for question in ques %} {% if forloop.first %} <table cellspacing="15"> <tr> <td><input type="hidden" name="ques_id" value="{{question.ques_no}}">{{ question.ques_no }}</td> <td>{{ question.question }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_a}}"></td><td style="padding-bottom:8px;padding-right:5px;"> {{ question.option_a }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_b}}"></td><td style="padding-bottom:8px;padding-right:5px;">{{ question.option_b }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_c}}"></td><td style="padding-bottom:8px;padding-right:5px;">{{ question.option_c }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_d}}"></td><td style="padding-bottom:8px;padding-right:5px;">{{ question.option_d }}</td> </tr> </table> <a href='answer'> <input type="submit" value="submit"></a><br> <input type="button" value="next">Next <input type="button" value="previous">Previous {% endif %} {% endfor %} -
Move data from one model to another model on a button click
I have two models, Draft and Post. On "Draft" detail page, I need a publish button that moves data from draft to model Post -
in django i have made models but on commenting in blog i found error
class BlogComment(models.Model): sno=models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User, on_delete=models.CASCADE) post=models.ForeignKey(Post, on_delete=models.CASCADE) parent=models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) timeStamp=models.DateTimeField(default=now) Why this error is showing while commenting IntegrityError at /blog/postComment NOT NULL constraint failed: blog_blogcomment.comment -
Django responsive template not working on mobile - static files copied exactly and code including viewpoint checked line by line
The raw template I downloaded shows responsive in browser but when I implemented the same code on my pythonanywhere app it is not showing correctly on mobile. I copied all the static files exactly and checked template code line by line and cannot find any difference to cause this. The viewpoint tag is also included. The problem is that it is not using device width as the width. I attached two pictures to compare. In the original template it is using the device width 414 and in my app it is using width 980 despite the device width 414. Not sure where it is getting the 980 width from. {% load static %} <!DOCTYPE html> <html class="no-js" lang="zxx"> <head> <meta charset="uft-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}title{% endblock title %}</title> <meta name="description" content=""> <meta name="viewpoint" content="width=device-width, initial-scale=1"> <link rel="manifest" href="site.webmanifest"> <link rel="shortcut icon" type="image/x-icon" href="{% static 'assets/img/favicon.ico' %}"> <!-- CSS here --> <link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/slicknav.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/animate.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/magnific-popup.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/fontawesome-all.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/themify-icons.css' … -
Sending JSON object to Django server (Client-side submission)
After submitting a form, the field values are wrapped inside a JSON object but nothing happens when I submit the form. I want a new Email object to be created and display the messages accordingly as defined in views.py. Does anyone know what is going wrong? It is supposed to send a JSON response after the submit button on form is clicked. Views.py @csrf_exempt @login_required def compose(request): # Composing a new email must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # Check recipient emails data = json.loads(request.body) return HttpResponse(request.body) emails = [email.strip() for email in data.get("recipients").split(",")] if emails == [""]: return JsonResponse({ "error": "At least one recipient required." }, status=400) # Convert email addresses to users recipients = [] for email in emails: try: user = User.objects.get(email=email) recipients.append(user) except User.DoesNotExist: return JsonResponse({ "error": f"User with email {email} does not exist." }, status=400) # Get contents of email subject = data.get("subject", "") body = data.get("body", "") # Create one email for each recipient, plus sender users = set() users.add(request.user) users.update(recipients) for user in users: email = Email( user=user, sender=request.user, subject=subject, body=body, read=user == request.user ) email.save() for recipient in recipients: email.recipients.add(recipient) email.save() return JsonResponse({"message": "Email … -
If statement on a Model.field
hopefully this is clear. I am trying to put together a view that takes care of what happens when a user places a bid on an active listing on the auction site I am trying to build. I'm doing an if statement to tackle what happens if a user tries to bid on a closed listing but pylint keeps throwing a syntax error on the line that reads: if auction.status is not 'active': I have tried: if auction.status is closed: if auction.status.closed: Is it a keyword that I'm missing or parentheses? models.py class Listing(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='active') options = ( ('active', 'Active'), ('closed', 'Closed'), ) title = models.CharField(max_length=64) description = models.TextField(max_length=64) price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings") lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True) status = models.CharField(max_length=10, choices=options, default="active") favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True) objects = models.Manager() listingmanager = NewManager() def __str__(self): return f"Product: {self.title} \nDescription: {self.description} \nCurrent Price: £{self.price}\nImage: {self.image} \nCategory: {self.category} \nListed by: {self.lister}" class Bid(models.Model): bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidders") item = models.ManyToManyField(Listing, related_name="bid_item", default=None, blank=True) price = models.DecimalField time = models.TimeField() views.py def bidding(request, listing_id): bid_item = get_object_or_404(Listing, pk=listing_id) bid_item.resolve() bidding = Bid.objects.filter(bidder=request.user.filter(listing=listing).first() if … -
celery: migrating from AMQP to rabbitmq queue system
I am updating an old Django app. Can anyone please direct me to a guide that explain how to migrate celery from the AMQP queue system (deprecated) to rabbitmq. Thank you very much for your help -
Django: Use query result in future queries instead of repeating it
I have a custom user profile model. This model has can_edit property that uses ContentType and Permission objects to determine if the user has permission or not. I'm using this property within serializer and it works fine, but is terribly inefficient, as per each user the ContentType and Permission are queried again. It seems like prefetch_related could fit here, but I don't know how to apply it, as these objects are not referenced directly through some properties, but kinda queried separately. Is it possible to fetch the ContentType and Permission beforehand and just use the results in further queries? Here's my model: class CustomProfile(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) @property def can_edit(self): content_type = ContentType.objects.get_for_model(Article) permission, _ = Permission.objects.get_or_create( codename="edit", name="Can edit", content_type=content_type ) return self.user.has_perm(self._permission_name(permission)) def _permission_name(self, permission): return f"{permission.content_type.app_label}.{permission.codename}" My current query: User.objects.order_by("username").select_related("profile") My serializer: class UserSerializer(serializers.ModelSerializer): can_edit = serializers.ReadOnlyField(source="profile.can_edit") class Meta: model = User fields = ( "id", "username", "first_name", "last_name", "is_active", "is_staff", "can_edit", ) In fact, I have more than one property with similar content to can_edit, so each user instance adds around 6 unnecessary queries for ContentType and Permission. How can I optimize it? -
Data is not saving to the database but shows on terminal in Django
So i have been trying to add Tags using django-taggit, but for some reason tags are not saving to the database when i try to upload a post using website but it works perfectly with django admin(Tags are saving to the database). Also when i go to my Post_edit view and try to update empty tags field then it works. In other words, tags are only saving to the database when i try to edit it using Postedit view or upload it using admin. I want it to save to the database using PostUpload view only(like i have to use PostEdit view for every post to display tags). Also i can see request.POST data is returning the list of Tags on the terminal and form returns no errors. Everything else is saving to the database except Tags. here's my code Views.py Uploading Posts( views.py ) @login_required(login_url="/login/") def post_upload(request): index1 = Blog.objects.all().order_by('-time')[0] content = request.POST.get('content') title = request.POST.get('title') image = request.FILES.get('image') if request.method == 'POST': post_form = PostUpload(request.POST, request.FILES, instance=request.user) if post_form.is_valid(): tags = post_form.cleaned_data['tags'] context = post_form.cleaned_data['context'] excerpt_type = post_form.cleaned_data['excerpt_type'] ins = Blog.objects.create(user=request.user, content=content, title=title, image=image, context=context, tags=tags, excerpt_type=excerpt_type) ins.save() messages.success(request, 'Your Post has been successfully posted') print(request.POST) print(tags) return … -
Django ajax post modal boostrap form
i want to use ajax in boottsrap modal popup form, i found a few doc but it was not clearly. I wan to use ajax form with popup window, for post some models with this window, have can i do it the best way? thansk. -
Cannot create container for service web: status code not OK but 500 ..Encountered errors while bringing up the project
Please watch the screenshot of Dockerfile and docker-compose.yml along with directory structure Dockerfile docker-compose.yml I used that following command in the gitbash terminal Windows 10 after creating django project successfully to now run into docker desktop. $ docker-compose up -d --build After that this is the error which Im facing , error is messy so I m posting a Screenshot please go throught that and help me to fix that. Thank You Error Screenshot