Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest assertion error in django rest framework
my model like this class Appeal(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) other_category = models.CharField(max_length=500, null=True, blank=True) file = models.FileField(upload_to='appeals/', null=True) short_name = models.CharField(max_length=100) appeal_desc = models.TextField() state = models.IntegerField(choices=STATUS, default=NEW) dept = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True) location = models.PointField(srid=4326, null=True) address = models.CharField(max_length=255) history = HistoricalRecords() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) I am going to test this model but I am failing I do not know where I am making a mistake pytest only gives an error like this > assert appeal_res.status_code == status.HTTP_201_CREATED E AssertionError: assert 400 == 201 E +400 E -201 my whole test here class AppealTestCase(APITestCase): client = APIClient() def post_appeal(self, short_name, appeal_desc, address, location, category): url = reverse('appeal-create') data = {'short_name': short_name, 'appeal_desc': appeal_desc, 'address': address, 'location': location, 'category_id': category} response = self.client.post(url, data, format='json') return response def create_user_set_token(self): user = User.objects.create_user(username='test', password='test2020') token = Token.objects.create(user=user) self.client.credentials(HTTP_AUTHORIZATION='Token {0}'.format(token.key)) def test_post_and_get_appeal(self): self.create_user_set_token() category = Category.objects.create(name='Test Category').id print(category) short_name = 'bla bla' desc = 'test desc' location = 'SRID=4326;POINT (1.406108835239464 17.66601562254118)' address = 'test address' appeal_res = self.post_appeal(short_name, desc, address, location, category) assert appeal_res.status_code == status.HTTP_201_CREATED Here What I have tried so far. If anybody know please, help me on this issue, with or without Category model … -
How to Encrypt Password before saving it to User Model Django?
I've created a user-signup page which adds users to User Model in Django But when the data is saved, the Password is not encrypted, i.e. stored as Text only. This creates a problem when the user tries to log in (as Django tries to Decrypt the original password, and they both don't match). Also, I'm extending the User Model so as to add more information about the users which is saved in the Profile Model (Using a One-To-One Link) views.py def user_signup(request): if request.method == "POST": user_form = userSignup(request.POST) phone = request.POST['phone'] address = request.POST['address'] pincode = request.POST['pincode'] if user_form.is_valid() : user = user_form.save() auth.login(request,user) userdata = User.objects.all() for userinfo in userdata: if userinfo.username == user.username: user_id=user.id update_data = Profile.objects.get(pk = user_id) update_data.address=address update_data.phone=phone update_data.pincode=pincode update_data.save() return redirect('/') else: return HttpResponse(" SIGNUP FAILED") else: form = userSignup() profile_form = userSignup_profile() return render(request,"user_signup.html",{'form':form, 'profile_form':profile_form}) def user_logout(request): auth.logout(request) return redirect('/') user_signup.html <body> <form action="user_signup" method="POST"> {% csrf_token %} {{form.as_p}} {{ profile_form.as_p}} <button class="primary" type="submit" >SIGNUP </button> </form> </body> Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=10) address = models.TextField(max_length=200) pincode = models.IntegerField() forms.py class userSignup(forms.ModelForm): password = forms.CharField(max_length=50, widget = forms.PasswordInput()) class Meta: model = User fields = ('first_name', 'last_name','username', … -
Why can't I access subclass type for my Django model instances?
I have something like this: class Cat(models.Model): #some fields class SiameseCat(Cat): #some additional fields for cat in pet_store.cats.all(): print(isinstance(cat, SiameseCat)) print(type(cat)) Even when my instantiated SiameseCats are visible under a separate heading on the django admin page, I always get "False, Cat" printed to the terminal for each cat in the pet store. If I try to print(cat.siamese_only_field), I get an attribute error. I need to access and output the siamese_only_field for my project to work. Also, this whole thing is generally a head scratcher and I'd like to know what I'm doing wrong. Why can't I access the model subclass of an object as expect? -
AttributeError at /admin/orders2/order/11/change/ 'NoneType' object has no attribute 'username'
Everything is working fine in my frontend, this problem is occurring when I'm trying to access the orders in my admin panel. I tried to figure out where the problem was, but failed. Why is this throwing an error? Can anyone please help me solve this problem? Thanks in advance! My models.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20) ordered = models.BooleanField(default=False) def __str__(self): return self.user.username My admin.py: class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'being_delivered', 'received', 'refund_requested', 'refund_granted', 'shipping_address', 'billing_address', 'payment', 'coupon'] list_filter = ['ordered', 'being_delivered', 'received', 'refund_requested', 'refund_granted'] list_display_links = ['user', 'shipping_address', 'billing_address', 'payment', 'coupon'] search_fields = ['user__username', 'ref_code'] admin.site.register(Order, OrderAdmin) -
Multiple Image uploding with Django Rest Framework and Ajax
I'am creating CreateAPIView with Django Rest Framework and calling it with ajax. I want to upload multiple images with a post but could only upload only 1 image. This is my model: class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField(blank=True) message_html = models.TextField(editable=False) group = models.ForeignKey( Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE) liked = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='post_liked') updated = models.DateTimeField(auto_now=True, blank=True) destination = models.ForeignKey( Destination, on_delete=models.CASCADE, blank=True, null=True) type = models.CharField(choices=CATEGORY, max_length=100, default='Public') objects = PostManager() def __str__(self): return self.user.username .... class PostImage(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, default=None, related_name='post_images') image = models.FileField(upload_to='post-files', blank=True) def __str__(self): return self.post.message This is my serializer: class PostImageModelSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = '__all__' class PostModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): file_fields = kwargs.pop('file_fields', None) super().__init__(*args, **kwargs) if file_fields: field_update_dict = {field: serializers.FileField( required=False, write_only=True) for field in file_fields} self.fields.update(**field_update_dict) def create(self, validated_data): validated_data_copy = validated_data.copy() validated_files = [] for key, value in validated_data_copy.items(): if isinstance(value, InMemoryUploadedFile): validated_files.append(value) validated_data.pop(key) post_instance = super().create(validated_data) print(validated_files) for file in validated_files: PostImage.objects.create( post=post_instance, image=file) return post_instance user = UserDisplaySerializer(read_only=True) post_images = PostImageModelSerializer(many=True, read_only=True) timesince = serializers.SerializerMethodField() destination = DestinationDisplaySerializer(read_only=True) did_like = serializers.SerializerMethodField() liked = serializers.SerializerMethodField() class Meta: model = Post fields = … -
how to redirect to a profile page and see the data of the logged in user in Django?
I have been working on a small project, and it was developing smoothly until I got a road block. However, I am not able to route to the profile page. My website workflow is as below: 1) user sign up and redirect to login screen once registration successful. 2) user login and now he/she sees a form, where he/she needs to fill in mandatory fields 3) save and then either click on "profile" link(in the navbar) to see the profile data, or "save" button will redirect to the profile page automatically. point 3) is not working. For now I have a hyperlink in the NavBar for "profile". But its not doing anything though I have written the GET method. May be I am not fetching the data properly. I have gone through couple of web link here and here within the Stackoverflow, but they solutions not working for me Below are my django files details: views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView from django.contrib.auth.models import User from .models import UserProfile # from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .forms import SignUpForm, UserProfileForm from django.views.decorators.csrf import … -
How can i set proxy for load tiles in Leaflet with Django or Nginx?
I have this HTML leaflet code in Django or Nginx: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" /> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"/> <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" ></script></head> <body> <div id="mapid" style="width: 600px; height: 400px;"></div> <script> var mymap = L.map('mapid').setView([51.505, -0.09], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' ).addTo(mymap); </script> </body></html> This code: L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') load all tiles in leaflet. And I have proxy and port like IP proxy:45.4.85.75 Port Proxy:9991 how can i set this proxy for Load all L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') with this IP proxy? Openstreetmap just is an example. My reason: is any reason. How can I do? Leaflet,Django or Nginx has any function? My goal is for the server to recognize all users from one ip ( Mean IP proxy) -
Can we use instance in the form?
hello guys i am working on form i didint find how to get instance in the form. This is not a model form def form(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): else: form = Form() return render(request, 'app/form.html', {'form': form}) -
How to use get_FOO_display() to access an uninstantiated model in Django
Am new to programming and I would like to access the get_FOO_display() function for the below model before having any objects (database entries). I know I can use SubOrder.EXTRA_CHOICES and SubOrder._meta.get_field(), but in both cases I get a list of tuples returned (M, 'Mushrooms'), (P, 'Peppers'), etc. How can I just get Mushrooms, Peppers, etc. as a list? I tried SubOrder._meta.get_extra_display() but I get an AttributeError: 'Options' object has no attribute 'get_extra_display' - Django's Model _meta API doesn't seem to allow that. My model is below: class SubOrder(Sub): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, primary_key=True, related_name="sub_item_id") extra_count = models.IntegerField(default=0, validators=[MaxValueValidator(4), MinValueValidator(0)]) MUSHIES = 'M' PEPPERS = 'P' ONIONS = 'O' XTRCHEESE = 'C' EXTRA_CHOICES = ((MUSHIES, 'Mushrooms'), (PEPPERS, 'Peppers'), (ONIONS, 'Onions'), (XTRCHEESE, 'Extra Cheese'),) extra = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True) -
how to make profile for each user
I have an app that if a user signs up, the app will automatically make a profile page for it, the sign up and login part works correctly but it doesn't make a profile page, I have to do it in the admin page. How should I solve this problem? this is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) this is my views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your Acount Has Been Created You Are Now Be Able to Login') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST ,request.FILES , instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your Acount Has Been Updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form':u_form, 'p_form':p_form } return render(request, 'users/profile.html', context) this is my forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class … -
How can I create a Django model in views.py?
In a DetailView page for object "Patient", I have a form. When the form is filled and submitted, I want to create a "Location" object. Then, I want to create a ForeignKey pointing to the "Patient" object that we are looking at in the DetailView. As you can see, if the form is valid, I call the model constructor, save the information and connect it to the patient object. However when I check Django Admin, I can't see a new object created. I totally improvised as I couldn't find examples online. Is this the way to do it? class PatientDetailView(DetailView, FormMixin): model=Patient form_class = PastLocationForm #template_name = 'patient_detail.html' def get_success_url(self): return reverse('patient_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): pastLocationDetail = Location() setattr(pastLocationDetail,'location',str(form.cleaned_data['location']).split(',')[0]) setattr(pastLocationDetail,'address',str(form.cleaned_data['location']).split(',')[1].split(', ')[0]) setattr(pastLocationDetail,'district',str(form.cleaned_data['location']).split('District: ')[1].split(',')[0]) setattr(pastLocationDetail,'grid_x',str(form.cleaned_data['location']).split('Coordinates: (')[1].split(', ')[0]) setattr(pastLocationDetail,'grid_y',str(form.cleaned_data['location']).split('Coordinates: (')[1].split(', ')[1][:-1]) setattr(pastLocationDetail,'date_from',form.cleaned_data['date_from']) setattr(pastLocationDetail,'date_to',form.cleaned_data['date_to']) setattr(pastLocationDetail,'details',form.cleaned_data['details']) setattr(pastLocationDetail,'patient', self.object) return self.form_valid(form) else: return self.form_invalid(form) Location model class Location(models.Model): patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True) . . Note: I printed out both the objects print(type(self.object)) print(pastLocationDetail) And everything seems fine. I really don't understand why it is not written to the database -
ajax response return with function for
Can you tell me how can I replace code html with function 'for from django'? $.ajax({ url: url, data: $('#FormSite').serialize(), type: "POST", async:false, success: function(response) { $($("#Pic").first()).replaceWith($(response['Pic'])); $("#HeaderWpis").text(response['h1']); $("#WpisChild").html("<div id='WpisChild'> {% for News in Messags %} <p>{{ News.title }}</p> </div>"); }, error: function(data) { alert('Bad connection'); console.log(data); } }); When I do this I got {%for%} from third div 'WpisChild' as text. The function does not perform on the page. Could you tell me why? -
no redirect from auth_view.LoginView.as_view(authentication_form=LoginForm)
i am using auth_view.LoginView.as_view() urls.py as default login in django. To add more fields i used custom form with AuthenticationForm in form.py, but after using custom form i cannot redirect from login page as i click submit button here is my form.py ''' from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): user_type_choice = (('visitor', 'Visitor'),('guest', 'Guest'),('contractor', 'Contractor')) username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) user_type = forms.MultipleChoiceField(choices=user_type_choice, widget=forms.NullBooleanSelect, required=True) here is my urls.py from django.urls import path from django.contrib.auth import views as auth_view from account.form import LoginForm from . import views urlpatterns =[ path('login/', auth_view.LoginView.as_view(authentication_form=LoginForm), name='login'), path('logout/', auth_view.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard') ] here is my views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required # Create your views here. @login_required def dashboard(request): render(request, 'account/dashboard', {'section': dashboard}) sorry for bad english. i am a newbie, please pardon me for my mistakes -
Django + Heroku + MongoDB Atlas (Djongo) = DatabaseError with No Exception
One line description of the issue Whenever my django app deployed on heroku tries to access my MongoDB Atlas cluster to submit a form or check an admin login it throws something like the attached error. Extra Details Error reproducible on heroku build here I think that this is error has to do with how heroku interacts with my MongoDB Atlas cluster, as I am able to get the app to successfully read and make modifications do different records in my database when I run the build locally. I have enabled traffic from all IP addresses to my Atlas cluster, removed the default Heroku PostrgreSQL database from my Heroku app and the config variables, and stored my own database IP as a config var. Any help would be greatly appreciated. Python script # Model Script from django.db import models class RawRequest(models.Model): content = models.CharField(max_length=130) identifier = models.CharField(max_length=30) # Views Script from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.http import HttpResponse from django.views.generic import CreateView from .models import RawRequest # Create your views here. def index(request): return HttpResponse("euler-calc terminal GUI") def potato(request): return HttpResponse("potato") class RequestView(CreateView): model = RawRequest fields = ('content', 'identifier') def get_success_url(self): … -
How to add an image to Django's Syndication RSS-feed
Having this model: class MyModel(models.Model): … image = StdImageField( upload_to="img/images", blank=True, variations={ "large": (1024, 1024), "thumbnail": (150, 150, False), "medium": (600, 600), }, delete_orphans=True, ) and this view … from django.contrib.syndication.views import Feed … class LatestItems(Feed): title = "LatestItems" description = "Latest Items" link = "/sitenews/" def items(self): return MyModel.objects.all() def item_title(self, item): return item.description_short def item_description(self, item): return item.description def item_link(self, item): return reverse('item_detail', args=[item.pk]) How to add an image to the body of an RSS-article? -
how do I convert Django queryset values data to pandas dataframe?
I have a Django Queryset which I obtain using `answers = CatResponse.objects.values('administration_id','administered_words','administered_responses').filter(administration__in=administrations)` The result looks like: <QuerySet [ { 'administration_id': 102201, 'administered_words': ['hat', 'cheese', 'milk', 'bath', 'hi', 'meow', 'moo', 'cookie', 'duck', 'apple', 'banana', 'ear', 'car', 'uh oh', 'baby', 'nose', 'no', 'book', 'bye', 'shoe', 'daddy*', 'mommy*', 'ball', 'eye', 'juice', 'bubbles', 'woof woof', 'grandma*', 'hot', 'hair', 'fish (animal)', 'please', 'cat', 'thank you', 'night night', 'yes', 'truck', 'water (beverage)', 'cup', 'diaper', 'water (not beverage)', 'quack quack', 'ouch', 'kitty', 'cracker', 'bear', 'eat', 'spoon'], 'administered_responses': [True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True] },{ 'administration_id': 102200, 'administered_words': ['bird', 'balloon', 'apple', 'banana', 'ear', 'car', 'uh oh', 'baby', 'nose', 'eye', 'no', 'book', 'bye', 'duck', 'cookie', 'moo', 'meow', 'hi', 'bath', 'milk', 'cheese', 'bubbles', 'woof woof', 'grandma*', 'hot', 'hair', 'fish (animal)', 'please', 'cat', 'thank you', 'night night', 'yes', 'truck', 'water (beverage)', 'cup', 'diaper', 'water (not beverage)', 'quack quack', 'ouch', 'kitty', 'cracker', 'bear', 'eat', 'spoon', 'door', 'baa baa', 'mouth', 'grandpa*'], 'administered_responses': [True, True, True, False, True, False, True, False, True, … -
(AttributeError: module 'PIL.Image' has no attribute '_meta') When resizing images with pillow
I was trying to change the size of an image but then when I was to run the code it showed up this error:`AttributeError: module 'PIL.Image' has no attribute '_meta' This si my models.py file: from django.db import models from PIL import Image class LmtbProject(models.Model): title = models.CharField(max_length=200) description = models.TextField() public = models.BooleanField(default=True) LmtbImage = models.ImageField(blank=True) def __str__(self): return f'{self.title}' def save(self): super().save() img = Image.open(self.LmtbImage.path) output_size = (1000, 800) img.thumbnail(output_size) img.save(self.LmtbImage.path) class SecondaryImage(models.Model): MyProject = models.ForeignKey(LmtbProject, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') def __str__(self): return f'{self.MyProject.title}' def save(self): super().save() img = Image.open(self.image.path) output_size = (1000, 800) img.thumbnail(output_size) img.save(self.image.path) `This is my view that I use with it: def project(request): projects = LmtbProject.objects.all() context = { 'projects': projects } return render(request, 'projects.html', context) def project_detail(request, id): project = get_object_or_404(LmtbProject, id=id) photos = SecondaryImage.objects.filter(MyProject=project) return render(request, 'project-detail.html', {'project': project, 'photos': photos}) -
Chrome becoming unresponsive when parsing json from ajax response (Mozilla works)
Initial page load works without any issues: json = JSON.parse('{{ json|escapejs }}'); but if I refresh my data with an ajax call to my django back-end calling the same exact function returning the same exact data chrome becomes unresponsive (mozilla has no issue parsing the json on both page load and ajax refresh): json = JSON.parse(response.json); It's a fairly large amount of data, but can someone please explain what's going on and why it's only chrome that isn't able to parse the json and only in the ajax response? -
How to pass an object from one view to another in Django?
I want to pass an object from one view to another in my Django project. But I got an error such as Object of type ModelCreate is not JSON serializable Here is my sender view: @login_required(login_url = "user:login") def modelCreate(request): customer_name = str(request.user) home_path = Methods.get_home_path(customer_name) outputs = request.user.profile.selected_outputs process = ModelCreate(str(home_path), customer_name, outputs) request.session['process'] = process return redirect("data:status") Here is my receiver view; @login_required(login_url = "user:login") def process_status_view(request): process = request.session['process'] return render(request, "pending_page.html") How can I pass this object? -
Why Am I getting "None" when using ForeignKey on integer value from another model that I know that have integer number?
I wanted to ask you for your help. I have two models. In the first one I wanted to reference foriegn key from the second one to be able to print votescore that I store there. My models.py : class Question(models.Model): question = models.CharField(max_length=300) answered = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) votesscore = models.ForeignKey('VoteQuestion', on_delete=models.CASCADE, null=True, blank=True, related_name='question_votesscore') def __str__(self): return self.question class VoteQuestion(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE, blank=False, null=True) votesubmitted = models.DateTimeField(null=True, blank=True) votesscore = models.IntegerField(default='0') amountofvotes = models.IntegerField(default='0') def __str__(self): return self.votesscore class Meta: unique_together = ['user', 'question', 'votesscore'] Next in my views.py: def home(request): allquestionswithanswers = Question.objects.filter(datecompleted__isnull=False) allquestionswithoutanswers = Question.objects.filter(datecompleted__isnull=True) return render(request, 'main/home.html', {'allquestionswithanswers': allquestionswithanswers, 'allquestionswithoutanswers': allquestionswithoutanswers}) And in my home.html I am calling it like this: {% for question in allquestionswithanswers %} <li> {{ question }} Score: {{ question.votesscore }} {{ question.user }} <br><br> <form class='my-ajax-form' method='POST' action='' data-url="{% url 'questionvoteup' question.id %}" > {% csrf_token %} <button type='submit'>UP</button> </form> {% for answer in question.answer_set.all %} {{ answer }}<br> {% endfor %} </li> {% endfor %} And when I try to print {{ question.votesscore }} I get value "None". Yet I am sure that in … -
Django - taking values from POST request, JavaScript fetch API
Sorry if this is a noob question, I am creating an Django app and for that i am trying to access data received from POST request, using JavaScript fetch API but it is showing empty I am not getting what is my mistake. I have tried to remove to all unnecessary part to debug and even on executing only this part I am getting same error. Code of my views.py def checkdb(request): if request.method == "POST": a = request.POST.get('tag', 'default') print("printing", a) print(request.POST) return HttpResponse("Hello") def check(request): return render(request, 'shop/new.html') Code of URLS.py urlpatterns = [ path('', views.index, name="shop"), path('checkdb/', views.checkdb, name="checkdb"), path('check/', views.check, name="check"), ] Code of new.html, it has only script tag to fetch request just for testing purpose. <script> data = JSON.stringify({ headline: "Testing", tag: "Testing", background_image: "Testing", content: "Testing", user: 1 }) let csrftoken = getCookie('csrftoken'); let response = fetch("/shop/checkdb/", { method: 'POST', body: data, headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, }) function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name … -
'django-admin' is not recognized as an internal or external command, operable program or batch file. Windows10
I tried starting my own project in Django but I keep getting "'django-admin' is not recognized as an internal or external command, operable program or batch file." C:\>cd C:\Users\Gamer Grill\Desktop C:\Users\Gamer Grill\Desktop>mkdir django-practise C:\Users\Gamer Grill\Desktop>cd django-practise C:\Users\Gamer Grill\Desktop\django-practise>mkdir my_first_project C:\Users\Gamer Grill\Desktop\django-practise>django-admin startproject first_project 'django-admin' is not recognized -
Syntax Error in manage.py while executing process_tasks
I'm trying to execute some background apps in Django 2.2 but every time I call python3 manage.py process_tasks it raise syntax error other commands like run server, migrate, ... works fine only for process_tasks it raises this error even when I comment on all background task codes File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax -
Display pdf file with proper indentation
I want to Display Pdf file on webpage. The Pdf File contains Python Program which has indentation. But while displaying the file i am not able to get the proper spacing as in the pdf. import PyPDF2 def read_file(request): pdfFileObj = open('media/documents/from_django.pdf', 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pageObj = pdfReader.getPage(0) text=pageObj.extractText() pdfFileObj.close() context = {'file_content': text} return render(request, "file.html", context) HTML <!DOCTYPE html> <html lang="en"> <head> <title>File</title> </head> <body> {{ file_content}} </body> </html> -
my marketing_message is displayed only in index.html and rest of the pages middleware dont display marketing messages
I think since i am adding marketing_message in templates of views.py thats why my context is displaying message only at index.py... i want to display my message in every page of my app. middleware.py--- from .models import MarketingMessage from django.utils.deprecation import MiddlewareMixin class DisplayMarketing(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): print("something") try: request.session['marketing_message'] = MarketingMessage.objects.all()[0].message except: request.session['marketing_message'] = False settings.py--- MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'marketing.middleware.DisplayMarketing', ] added it in views.py-- def index(request): products = Product.objects.all() marketing_message = MarketingMessage.objects.all()[0] context = {'products':products,'marketing_message':marketing_message} return render(request,'pro/index.html',context) my views.py def index(request): products = Product.objects.all() marketing_message = MarketingMessage.objects.get() context = {'products':products,'marketing_message':marketing_message} return render(request,'pro/index.html',context) base.html-- {% if marketing_message %} <div class="alert alert-success alert-dismissible alert-top-message" role="alert"> <h3> {{ marketing_message.message|safe }} </h3> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %}