Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Querying a data with Django ORM to return a specific data that belongs to a user
so I'm trying to build a Ledger App. When new users sign-ups, they create a new Business account that is linked to them (ForeignKey). Here is my model: User = get_user_model() class Business_Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) business_name = models.CharField(max_length=50) Type_of_service = models.CharField(choices=SERVICE_CATEGORIES, max_length=50) business_email_address = models.EmailField(max_length=254) class Meta: verbose_name = "Business_Account" verbose_name_plural = "Business_Accounts" def __str__(self): return self.business_name Now, I want to make a get request view that can query and returns a business account that belongs to a particular user. My current view just returns all the business accounts available in the database irrespective of which user is login. Here is my view: class AddBusinessAcctView(APIView): def get_object(self): try: return Business_Account.objects.all() except: raise status.HTTP_404_NOT_FOUND def get(self,request): queryset = self.get_object() serializer = BusinessAcctSerializer(queryset, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) Now, How can I query business accounts that belong to a particular user?. Thanks in advance -
Is it possible to integrate an old/legacy Django application into Zappa for serverless integration?
I am trying to find a way to integrate our company's Django Web app into Zappa so we can go completely serverless with our REST API. The problem is that our app has existed for several years, making it a lot heavier than the brand new apps that all of these Zappa tutorials init over. Is there a format that Zappa requires for integrating an old Django app into its framework? I have no wait of knowing how much refactoring will be required for Zappa to know how to transition our API into lambda functions. When I tried running Zappa deploy in our root directory, I got the following error, which probably means our app is poorly optimized for the Zappa system: Traceback (most recent call last): File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 896, in deploy function_name=self.lambda_name File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/core.py", line 1520, in get_lambda_function response = self.lambda_client.get_function(FunctionName=function_name) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/botocore/client.py", line 386, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/botocore/client.py", line 705, in _make_api_call raise error_class(parsed_response, operation_name) botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the GetFunction operation: Function not found: arn:aws:lambda:us-east-1:253119149513:function:src-dev During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 3422, in handle sys.exit(cli.handle()) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 588, … -
cant render Json Data in Django template?
i have simple Filter and Search Function but result dosent showup excatly my views.py if request.method == "POST": post=request.POST.get("category") name=request.POST.get("name") print(name) try: category=Type_Child.objects.filter(type_id=post) response_content=list(category.values()) my_products=Product.objects.filter(name__icontains=name) response_content_product=list(my_products.values()) except Exception: response_content=list({}) response_content_product=list({}) pass data=[{ "name":response_content_product, "category":response_content }] print(data) return JsonResponse(data,safe=False) and that's my Ajax </script> $("#id_name").change(function () { const nameId = $(this).val(); // get the selected subject ID from the HTML dropdown list $.ajax({ // initialize an AJAX request type: "POST", url: '{% url "ajax:ajax_home" %}', data: { 'name': nameId, // add the country id to the POST parameters 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), }, success: function (data) { // `data` is from `get_topics_ajax` view function let html_data = ` `; data.forEach(function (data) { html_data += ` ${data.name} Some quick example text to build on the card title and make up the bulk of the card's content. Go somewhere ` }); $("#id_product").html(html_data); // replace the contents of the topic input with the data that came from the server } }); }); -
Django - The "> symbols appear on the outside of the forms fields manytomany and foreignkey
There's something wrong in my template of html rendered in my django project, the follows symbols "> appear on the outside of my forms fields, this fields call a foreignkey (subjects_id) from a manytomany relation (comorbidities_ids). I think that i'm making some mistake when i call the ids of the manytomany relations and foreignkey fields in the html. Can anybody help me? class Medical_Record(models.Model): subjects_id = models.ForeignKey(Subjects, on_delete=models.CASCADE) HC_number = models.CharField(max_length=20, null=False) diseases_id = models.ForeignKey(Diseases, on_delete=models.CASCADE, null=True) comorbidities_ids = models.ManyToManyField(Comorbidities, null=True) surgery = models.TextField(null=True) clinical_outcomes = models.TextField(null=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) <div class="input-group mb-3"> <div class="input-group-prepend"> <label class="input-group-text" for="id_comorbidities_ids">Comorbidities:</label> </div> <select class="custom-select" name="comorbidities_ids" required="" id="id_comorbidities_ids" multiple=""> <option value="{{ form_medical_records.comorbidities_ids }}"></option> </select> </div> -
Pass request as argument in a ready function of an application in django
I want to perform a query and a request must be passed in order to filter my queryset inside a ready function in apps.py file. class AcademicConfig(AppConfig): name = "academic" def ready(self): from academic.models import AcademicSession AcademicSession.objects.get(some_field=request.user.some_field) How do I suppose to pass a request? -
Is there a way to restrict an API on a public webserver to a specific frontend?
My web application has public API endpoints. I have two frontends one for internal admin and the other for customers both using the same backend endpoints. The goal is to allow certain APIs to only be available to the internal admin frontend. I thought about using HTTP ORIGIN header which would contain the frontend url. Is that a good approach? -
Nested or multiple select_for_updates
I wish to acquire locks on more than one unrelated object using .select_for_update. Do I need to wrap each call with a transaction.atomic? I've read the sections in the Django documentation and postgres' Row Locking but it's unclear on the matter. from django.db import models class A(models.Model): data = models.TextField() class B(models.Model): data = models.TextField() This is a bit of a contrived example, but given the above models, can I do this? def update_records(pk_a, pk_b, value): with transaction.atomic(): a_object = A.objects.get(pk=pk_a).select_for_update() b_object = B.objects.get(pk=pk_b).select_for_update() # modify values, etc or do I need to do this? def update_records(pk_a, pk_b, value): with transaction.atomic(): a_object = A.objects.get(pk=pk_a).select_for_update() with transaction.atomic(): b_object = B.objects.get(pk=pk_b).select_for_update() -
Django: Dynamically generated form fields are not show in view
I have the following form in my forms.py: class ObjectForm(forms.Form): object_text = forms.CharField(max_length=1000) def __init__(self, *args, **kwargs): krs = kwargs.pop('krs', None) super(ObjectForm, self).__init__(*args,**kwargs) i=6 self.fields['mytry%s' %i] = forms.CharField(label="mytry%s" %i) if krs: for kr in krs: self.fields['text_%s' %kr.no] = forms.CharField(label="kr_text") Now, the field 'mytry6' above the for-loop is shown when I display the form in the html template. But the fields generated in the for-loop are not shown. When I log the content of the form, I see that the additional fields with 'text_1' etc. are included in the form. But somehow they are not shown?!? Can anybody help? Thanks -
django + gunicorn + uvicorn + nginx 504 gateway timeout after adding --preload
Everything works fine for me when I don't use preload option in gunicorn, but when I add --preload to gunicorn, nginx gets 504 gateway timeout. here is my /etc/systemctl/systemd/gunicorn.service: [Unit] Description=uvicorn daemon After=network.target [Service] Environment=DJANGO_SETTINGS_MODULE=MyProject.settings.production User=user1 Group=www-data WorkingDirectory=/home/user1/myproject ExecStart=/home/user1/myproject/venv/bin/gunicorn MyProject.asgi:application --preload -w 2 -k uvicorn.workers.UvicornWorker --log-file - [Install] WantedBy=multi-user.target -
Multiple field boolean filtering by value with Django
I have 3 fields in a dataset that I want to create querysets over the possible permutation values for those fields. These fields are based on a numerical rating scale, so the queries are based on whether a value is matched in the given field. I've already filtered the fields to ensure that the values in all three fields are at minimum a 7 (out of the possible integer values of 7, 8, 9 for those three fields). Now I want to find the following potential comparisons as querysets (!7 means the value can be 8 or 9): [7, 7, 7] [7, !7, 7] [7, 7, !7] [!7, 7, 7] [7, !7, !7] [!7, 7, !7] [!7, !7, 7] I was able to do this with pandas by creating comparison columns with boolean evaluation to check the following permutations, (i.e. column 1 = 7, column 2 != 7 (so either 8 or 9), column 3 != 7 (so either 8 or 9)). permutation_dict = { "all": (True, True, True), "one and three": (True, False, True), "one and two": (True, True, False), "two and three": (False, True, True), "one": (True, False, False), "two": (False, True, False), "three": (False, False, True), } … -
how to get id from object in POST request
Here I m making a POST request with the following data: { "ruleAssignmentDetails": { "id": 1, "ruleAssignment": { "id": 1, "empId": 1, "roleId": 1, "empName": "Emp01", "roleName": "CEO" }, "detailSrl": 12, "rule": 4, "validityType": "F", "startDate": "2021-06-14", "endDate": null, "frequency": { "id": 1, "frequencyName": "Test", "frequencyTpe": "Weekly" } }, "detailSrl": 12, "parameterName": "Param1", "valueType": "D", "overwriteValue": null, "targetDefination": { "id": 1, "targetName": "MIN SALES", "displayName": "MIN SALES" } } split the objects into respective models but when I m not getting the 'id' of targetDefination and ruleAssignmentDetails serializer.py class RuleAssignmentParamsSerializers(serializers.ModelSerializer): ruleAssignmentDetails = RuleAssignmentDetailsSerializers() targetDefination = TargetDefinationSerializers() class Meta: model = RuleAssignmentParams fields = ( 'id', 'ruleAssignmentDetails', 'detailSrl', 'parameterName', 'valueType', 'overwriteValue', 'targetDefination', ) def create(self,validated_data): ruleAssDetails = validated_data.pop('ruleAssignmentDetails') targetdef = validated_data.pop('targetDefination') serial = RuleAssignmentParams.objects.create(**validated_data) return serial views.py def getSimpleRules(request): simpleRules = RuleSimple.objects.all() simpleRulesSer = OnlySimpleRules(simpleRules,many=True) return JsonResponse(simpleRulesSer.data,safe=False) @api_view(['GET']) def getRuleAssignment(request,pk): if request.method == 'GET': print("get working") q=get_object_or_404(RuleAssignmentParams,pk=pk) f=RuleAssignmentParamsSerializers(q) return JsonResponse(f.data) @api_view(['POST']) def ruleAssignment(request): if request.method == 'POST': data = JSONParser().parse(request) validated_data = data serializer=RuleAssignmentParamsSerializers(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when I run this it shows me this error: IntegrityError at /api/rules/ruleassign (1048, "Column 'ruleAssignmentDetails_id' cannot be null") How do I get the id of ruleAssignmentDetails and targetDefination ? -
Django: How to check that an inline action has been executed?
I have three actions and it just so happens that I have to fix this code so that the application makes sure or at least warns the user (this is still being defined) that they have skipped a step. In my admin.py I have three inline actions: actions = [clean_data, rel_from_db, send_production] They just run actions related to a database in this manner: def send_production(modeladmin, request, queryset): for qs in queryset: qs.clean_data() How can I instead stop the execution (before the loop) to make sure the performed the two previous steps? Could I just save a variable in admin.py that keeps the state. I read the ValidationError indicated in this solution but I'm confused because I wanna validate inline actions (functions) and not exactly a form field. -
Django Error: NoReverseMatch at / ; looking at wrong urlpattern?
I am simply trying to open the web app to the home page, but at startup I am given the NoReverseMatch error message. The full message is the following: Reverse for 'wiki' with no arguments not found. 1 pattern(s) tried: ['wiki/(?P<title>[^/]+)/$']. In case it's relevant, I am using Django version 3.2.4. In urls.py for my project I have: urlpatterns = [ path('', include("encyclopedia.urls", namespace="encyclopedia")), path('admin/', admin.site.urls), ] In urls.py for my app I have: app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<title>/", views.entry, name="wiki"), .... (rest omitted for brevity) ] In views.py I have: def index(request): context = { "entries": ["item1", "item2", "item3"], "form": SearchForm(), } return render(request, "encyclopedia/index.html", context) In index.html, I have: {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li> <form action="{% url 'encyclopedia:wiki' %}", method="POST"> {% csrf_token %} <input type="text" value="{{ entry }}" name="link" hidden> <input type="submit" class="link-btn" value="{{ entry }}" style="border: 0; background-color: white"> </form> </li> {% endfor %} </ul> {% endblock %} As the error message indicates, it appears to be looking at the url pattern named wiki, and then subsequently failing to find the arguments passed to it. However, I am not trying to check that … -
Django View Aggregate Not Doing Calculation
I'm trying to do a little division math in my view for an HTML display. For some reason I'm not getting a calculation with the below view. I'm new to all this so any suggestions would be appreciated. View from django.db.models.functions import Cast from django.db.models import FloatField, F class PatientListView(LoginRequiredMixin, ListView, Cast, FloatField): model = Patient template_name = 'patient_list.html' ind_treat_length = Patient.objects.annotate(treat_len=( F('cycle_length_days') / F('treatments_per_cycle'))) def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( author=self.request.user ) The ind_treat_length annotation is what I have come up with for this. My HTML template request is {{ patient.treat_len }} Am I missing something here? Thanks -
Django - how to filter on a comma seperated string
At my Django models.py I have a "genre" field (models.TextField). This fields contains sometimes only one string and sometimes a comma separated list of string like this: Comedy, Action, Drama Or Action, Fantasy or as mentioned only one string e.g. only Comedy Now at my view I want to do something like this: queryset_comedy = Movies.objects.get_queryset().filter(genre__in=["Comedy", "Family"]) queryset_action = Movies.objects.get_queryset().filter(genre__in=["Action", "Adventure"]) queryset_drama = Movies.objects.get_queryset().filter(genre__in=["Drama", "Thriller"]) I mentioned that my Query only matches field values which are standalone according to the genre field. For example Movie element one has the following genre string: Comedy, Action and Movie element Two only has "Comedy" as single string. Than the query outputs only Movie objects which have the string "Comedy" standalone and not Comedy, Action. How can I make a Movie element match when multiple sorting strings are given for genre? -
Django: How to properly bulk_update_or_create() in a for loop
I am currently creating some django objects (or at least that is the idea) while executing a for loop where I am generating some data. The idea is to create multiple objects or update some of them if already exist. def get_friends(self): for friend_option in self.get_friend_options: friend_permalink = friend_option.get_attribute('href') friend_name = get_name() users.append(user) friend_requests.append(Friend(account=self.current_account, friend_permalink=friend_permalink, friend_name=friend_name, is_friend=False, request_type=Friend.REQUEST_TYPE_RECEIVED, received_request_date=datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') )) Friend.objects.bulk_create(friend_requests) return friend_requests -
Django API for Google Login
I am going to implement Google Login using React+Django. I am using the package: django-allauth for social login(Google via API). When you enter access_token in GoogleLogin view, a user is registered in the database and view returns key. The same key for different access_tokens. My question is, how can I use this key to extract data from database about this user. Can anyone help, please? -
Not able to fetch product id in ecommerce application -django
views.py ''' from django.shortcuts import render,redirect from .models import Cart from new_app.models import Product def cart_home(request): cart_obj,new_obj=Cart.objects.new_or_get(request) products=Cart.objects.all() return render(request,'carts/home.html',{}) def cart_update(request): print(request.POST) product_id=1 print('id below') print(product_id) // not able to get the value of product id in console product_obj=Product.objects.get(id=product_id) cart_obj,new_obj=Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) return redirect('home') ''' models.py(cart) ''' from django.db import models from django.conf import settings from new_app.models import Product from django.db.models.signals import pre_save,post_save,m2m_changed User=settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self,request): cart_id=request.session.get("cart_id",None) # qs=self.get_queryset().filter(id=cart_id) qs=self.get_queryset().only('products') print(qs) if qs.count()==1: new_obj=False cart_obj=qs.first() print('cart obj below') print(cart_obj) if request.user.is_authenticated and cart_obj.user is None: cart_obj.user=request.user cart_obj.save() else: cart_obj=Cart.objects.new_cart(user=request.user) new_obj=True request.session['cart_id']=cart_obj.id return cart_obj,new_obj def new_cart(self,user=None): user_obj=None if user is not None: if user.is_authenticated: user_obj=user return self.model.objects.create(user=user_obj) class Cart(models.Model): user=models.ForeignKey(User,null=True,blank=True,on_delete=models.CASCADE) products=models.ManyToManyField(Product,blank=True) subtotal=models.DecimalField(default=0.00,max_digits=100,decimal_places=2) total=models.DecimalField(default=0.00,max_digits=100,decimal_places=2) timestamp=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) objects=CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender,instance,action,*args,**kwargs): print(action) if action=='post_add' or action=='post_remove' or action=='clear': products=instance.products.all() total=0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal=total instance.save() m2m_changed.connect(m2m_changed_cart_receiver,sender=Cart.products.through) def pre_save_cart_receiver(sender,instance,*args,**kwargs): if instance.subtotal>0: instance.total=instance.subtotal + 10 else: instance.total=0.00 pre_save.connect(pre_save_cart_receiver,sender=Cart) ''' update_cart.html ''' <form method='POST' action='{% url 'update' %}' class="form ">{% csrf_token %} <input type="hidden" name='product_id' value= "{{ product_id }}"> {% if product in cart.products.all %} <button type="submit" class="btn btn-link">remove</button> {% else %} <button type="submit" class="btn btn-success">add to … -
Select chained in admin
Suppose I have the following models (in summary): class Control(models.Model: name = models.CharField() code = models.CharField(unique=True) type = models.CharField() subtype = models.CharField() class List(models.Model): type = models.CharField() subtype = models.CharField() And in my database, I have the list table populated like this: type | subtype -------------------------------- Information | Paper Information | Digital Information | Software Personal | System Processes | - How can I do, that from the admin site, when I add a new Control, the subtype is dependent on what I have chosen in type. For example, if in type I choose Information, that in Subtype you can only choose between Paper, Digital and Software. I know that from a URL that I create I can use AJAX, but I don't know how I could make it work like this from admin. I would be very grateful if someone can solve this question for me, because I have read things but I can not find it. -
Url always redirects to login on POST request
Whenever I try to make a POST request, the url automatically redirects to the login resulting in BAD_REQUEST This is my code for login: class LoginView(View): def get(self, *args, **kwargs): form = LoginForm() context = { 'form':form } return render(self.request, 'core/login.html', context) def post(self, *args, **kwargs): form = LoginForm(self.request.POST or None) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(self.request, email=email, password=password) if user is None: messages.add_message(self.request, messages.ERROR, 'Enter valid email or password') return redirect('login') login(self.request, user=user) return redirect('home') return redirect('login') This is my post function for api: class NoteCreateView(LoginRequiredMixin, APIView): def post(self, *args, **kwargs): print(self.request.user) data = (self.request.data) data['id'] = self.request.user.id print(data) serializer = NoteSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.data, status=HTTP_400_BAD_REQUEST) And this is the POST request made from frontend e.preventDefault() const note = document.getElementById('add-note').value let date = new Date() const data = { 'note':note, 'date_created':date } let url = 'http://localhost:8000/api/notes/create/' fetch(url, { method:'POST', headers:{ 'content-type':'application/json', 'X-CSRFToken':csrftoken }, body:JSON.stringify(data) }) .then(res => { getAllNotes() document.getElementById('form').reset() }) }) The url that it always redirects on making POST request /login/?next=/api/notes/create/ -
Django Custom User Creation Form - Duplicate Entry
Creating a custom page for creating new users. The page edits and deletes users without a problem. When I create a user, I receive django.db.utils.IntegrityError: (1062, "Duplicate entry 'johndoe@gmail.com' for key 'accounts_user.email'"). I know that my code is attempting to save the entry twice. Following my traceback, I think it has something to do with the save function within the form conflicting the form.save() in the view. Here is all the code. I've exhausted my (limited) ideas. views.py @admin_only def index(request): user_accounts = User.objects.all() print(user_accounts) context = {'accounts': user_accounts} return render(request, 'accounts/user_accounts.html', context) @admin_only def create_account(response): data = dict() form = CreateAccountForm() if response.method == 'POST': form = CreateAccountForm(response.POST) if form.is_valid(): form.save() data['form_is_valid'] = True user_accounts = User.objects.all().order_by('id') data['accounts_list'] = render_to_string('accounts/account_list.html', {'accounts': user_accounts}) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string('accounts/create_account.html', context, request=response) return JsonResponse(data) forms.py class UserAdminCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = User fields = ( 'email', 'first_name', 'last_name', ) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, … -
how to allow users to rate a product only once,
a Reviews model linked to Users and Product, nothing special, users can vote as much as they want which is working, but i'm stuck restricting the rating to just once the view so far: class ReviewCreateView(CreateView): model = Review form_class = ReviewForm template_name = "form.html" success_url = reverse_lazy('product_list') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) model class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True,related_name='reviews') user = models.ForeignKey(User, on_delete=models.PROTECT, null=True,related_name='reviewers') rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) the other models wouldn't help that muc ,Product just describe a product ,and default (regular) User model the form is ModelForm based on the Review Model itself any suggestion is welcome, even if i have to redo the model, thank you very much -
after pressing verification link ... nothing happens in Django .. user still unverified
Views.py(name of app: userprofileinfo) from django.shortcuts import render from userprofileinfo.forms import UserForm from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth import authenticate, login, logout from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.views import View from django.contrib import messages from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.template.loader import render_to_string from .utils import account_activation_token from django.urls import reverse from django.contrib import auth @login_required def special(request): return HttpResponseRedirect("You are logged in, Nice!") @login_required def userlogout(request): logout(request) return HttpResponseRedirect(reverse('careforallapp:base')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.is_active = False user.save() email = UserForm('email') current_site = get_current_site(request) email_body = { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } link = reverse('userprofileinfo:activate', kwargs={ 'uidb64': email_body['uid'], 'token': email_body['token']}) email_subject = 'Activate your account' activate_url = 'http://'+current_site.domain+link send_mail( email_subject, 'Hi '+user.username + ', Please the link below to activate your account \n'+activate_url, 'settings.EMAIL_HOST', [user.email], fail_silently=False ) return HttpResponseRedirect(reverse('careforallapp:base')) else: print(user_form.errors) else: user_form = UserForm() return render(request,'userprofileinfo/registration.html', {'user_form':user_form, 'registered':registered}) class VerificationView(View): def get(self, request, uidb64, token): try: id = force_text(urlsafe_base64_decode(uidb64)) user … -
Django app on Azure getting images from static files but not Bootstrap, Jquery or CSS files
Got a Django app deployed on Azure with this structure: wwwroot |---Myproject |---manage.py |---oryx-manifest.toml |---hostingstart.html |---static //Same static folder and same files from myapp ├── myapp │ ├── migrations │ ├── __pycache__ │ ├── static │ │ │---bootstrap-3.3.7-dist │ │ │ │--css │ │ │ │ │--bootstrap.min.css │ │ │ │ js │ │ │ │ │--bootstrap.min.js │ │ │---Datatables │ │ │ │--jQuery-3.3.1 │ │ │ │ │--jquery-3.3.1.js │ │ │ │ │datatables.js │ │ │ │ │datatables.css | | |---Images | | | |--myimage.png | | | |--myimage2.png │ └── templates Thing is, when I call statics on my template this way: <script src="{% static 'Datatables/jQuery-3.3.1/jquery-3.3.1.js' %}"></script> <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}"> <script type="text/javascript" charset="utf8" src="{% static 'Datatables/datatables.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'Datatables/datatables.css' %}"> <img src="{% static 'Images/myimage.png' %}" align="center"/><br> Images render perfectly, but CDN datatable and css styles not, and browser console throw me this errors: bootstrap.min.js:6 Uncaught Error: Bootstrap's JavaScript requires jQuery at bootstrap.min.js:6 And : myappwapp.azurewebsites.net/:1 Refused to apply style from 'https://myapp.azurewebsites.net/static/Datatables/datatables.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Makes no sense, order of calling … -
matching query does not exist. DoesNotExist at /blog/postComment
I am trying to add the feature of commenting and replying to it in my blog. But it is constantly throwing me the error of "BlogComment matching query does not exist." def postComment(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 == "": comment = BlogComment(comment=comment, user=user, post=post) comment.save() messages.success(request, "Your comment has been posted successfully") else: parent = BlogComment.objects.get(sno=parentSno) comment = BlogComment(comment=comment, user=user, post=post, parent=parent) comment.save() messages.success(request, "Your reply has been posted successfully")