Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i query all the fields in a django Many to Many
Trying to loop over a many to many relationship where I want all the fields. My Models: class Recipe(models.Model): title = models.CharField(max_length=200) slug = AutoSlugField(populate_from="title") category = models.ForeignKey(RecipeTopic, on_delete=models.CASCADE) image = models.ImageField() description = models.TextField() ingredients = models.ManyToManyField(Ingredient, through="IngredientList") directions = models.TextField() servings = models.IntegerField() time = models.IntegerField() cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE) def __str__(self): return self.title class IngredientList(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) Recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) amount = models.FloatField(default=1) unit = models.ForeignKey(Units, on_delete=models.CASCADE) My Views: from .models import Recipe def home(request): recipe = Recipe.objects.all() context = { "title": "Home Page", "recipe": recipe } return render(request, "home.html", context) and my template: {%for r in recipe %} <h2>{{r.title}}</h2> <h4>Ingredients:</h4> {%for i in r.ingredients.all %} <p>---{{i.amount}}{{i.unit}} {{i.ingredient}}</p> {%endfor%} {%endfor%} Want to showcase the ingredients, their amount, and the units that goes along with them. Except that I am only getting the "ingredient" title -
setting new file storage path in django model
I am trying to change the file storage path in model instance via view.py (instance.model.path = new_path) and I get can't set attribute. Not sure why as I can change the file name. view.py def SaveFile(request): if request.method == 'POST': model, created = MyModel.objects.get_or_create(record_id=request.POST['record_id']) file=request.FILES['report'] model.report = file.name call_id = model.record.call_ID date = datetime.now() date = str(date.strftime("%d.%m.%Y-%H:%M:%S")) file_storage = FileSystemStorage(location=os.path.join(MEDIA_ROOT, 'Reports', call_id)) file_name = file_storage.save(str(date + '-' + file.name),file) model.report.path = file_storage.location model.report = file_name model.save() return JsonResponse(file_name, safe=False) -
Errors don't show in Templates after custom validation
I'm working on a form where few field inputs depend on each other. I implemented custom validation and added error messages to it but, although custom validation works, error messages don't get shown in templates. form.py class NewCalculationForm(forms.ModelForm): def clean(self): cleaned_data = super(NewCalculationForm, self).clean() if self.cleaned_data.get('Tsrcin') <= self.cleaned_data.get('Tsrcout'): raise forms.ValidationError({"Tsrcout": "Source outlet temperature has to be lower than inlet temperature."}) # msg = "Source outlet temperature has to be lower than inlet temperature." # self.errors["Tsrcout"] = self.error_class([msg]) if self.cleaned_data.get('Tsinkin') >= self.cleaned_data.get('Tsinkout'): raise forms.ValidationError({"Tsinkout": "Sink outlet temperature has to be higher than inlet temperature."}) # msg = "Sink outlet temperature has to be higher than inlet temperature." # self.errors["Tsinkout"] = self.error_class([msg]) return cleaned_data class Meta: model = Calculation fields = ['Tsrcin', 'Tsrcout', 'Qsrc','Tsinkin','Tsinkout',] view.py def index(request): if request.method == 'POST': form = NewCalculationForm(request.POST or None) if form.is_valid(): Tsrcin = form.cleaned_data.get("Tsrcin") Tsrcout = form.cleaned_data.get("Tsrcout") Qsrc = form.cleaned_data.get("Qsrc") Tsinkin = form.cleaned_data.get("Tsinkin") Tsinkout = form.cleaned_data.get("Tsinkout") [Pnet, Pel, thermaleff, savepath] = cycle_simulation(Tsrcin, Tsrcout, Qsrc, Tsinkin, Tsinkout) file1 = DjangoFile(open(os.path.join(savepath, "TSDiagrammORCCycle.png"), mode='rb'),name='PNG') file2 = DjangoFile(open(os.path.join(savepath, "TQDiagrammORCCycle.png"), mode='rb'),name='PNG') instance = Calculation.objects.create(userid = request.user,Tsrcin = Tsrcin, Tsrcout = Tsrcout,\ Qsrc = Qsrc, Tsinkin = Tsinkin, Tsinkout = Tsinkout, Pel = Pel,\ time_calculated = datetime.today(), result = Pnet,\ thermaleff … -
How to perform a __all_in query with Django?
I have three models class Pizza(models.Model): toppings = models.ManyToManyField(Topping) class Topping(models.Model): name = models.CharField(max_length=50) class Order(models.Model): must_have_toppings = models.ManyToManyField(Topping) I want to find all Orders that match a certain Pizza. For this, I would like to do something like orders = Order.objects.filter(must_have_toppings__all_in=my_pizza.toppings) What I tried: orders = Order.objects.filter(must_have_toppings__in=my_pizza.toppings) doesn't work, because Orders with just one of the Pizza's toppings in their must_have will be returned. And: orders = Orders.objects for topping in my_pizza.toppings.all(): orders = orders.filter(must_have_toppings=topping) doesn't work, because it will return orders that have all the toppings from the pizza, even if some of the must_have_toppings are missing. For example, a Pizza with Tomatoes and Mushrooms will return an Order that needs Tomato, Pepper, and Mushroom. How can I look for Orders where the must_have_toppings are ALL in the Pizza object? (I am using MySql) -
How to pass value to django admin change list template?
I am linking my django admin to a custom change list template as shown in the images below, but how can I pass on a variable to this template from my admin page? -
How to create relation on in django User model and other model if other model have two fields to make relation
I am working on an application where I have two types of users Patients and Doctors, where patients can book appointments with doctors. I am using Django's built-in User model to register users. I have an appointment model but I am unable to make the relation between the appointment model and the user model as I want to reference the patient and doctor in the appointment model. when I tried with Foreign Key Appointment Model class Appointment(models.Model): patient = models.ForeignKey(UsersInfo,on_delete=models.CASCADE,default="None") doctor = models.ForeignKey(DoctorInfo,on_delete=models.CASCADE,default="None") doctor = models.CharField(max_length=20,blank=False) patient = models.CharField(max_length=20,blank=False) date = models.DateField(blank=False) time = models.TimeField(blank=False) status = models.CharField(default="pending",blank=True, max_length=20) during migrate python manage.py migrate Error (venv) D:\Python\Django\FYP\HeatlhCare>py manage.py migrate Operations to perform: Apply all migrations: Users, admin, auth, contenttypes, sessions Running migrations: Applying Users.0002_auto_20210921_1250...Traceback (most recent call last): File "D:\Python\Django\FYP\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'None' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Python\Django\FYP\HeatlhCare\manage.py", line 22, in <module> main() File "D:\Python\Django\FYP\HeatlhCare\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Python\Django\FYP\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "D:\Python\Django\FYP\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python\Django\FYP\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python\Django\FYP\venv\lib\site-packages\django\core\management\base.py", line … -
Django Excel Export (using xlwt)
I'm trying to export data tied to an id from a view, to an excel file, this is the code: from django.shortcuts import render from clientesapp.models import Cliente, Orden from django.http import HttpResponse import xlwt def excel_create(request, id): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="recibo.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('recibo') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold=True columns = ['Orden', 'Cliente', 'Entrada', 'Instrumento', 'Marca',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Orden.objects.get(id=id) rows.values_list('num_orden', 'client', 'fechain', 'instrumento', 'marca') for row in rows: row_num +=1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response I want to export to excel this table, that also shows the id i need to get the data: Table with id But this code shows me the error "Orden object have no attribute values_list". How can i solve this problem? -
Redirection failure in django
I'm trying to create a dashboard on Django It consists of 7 pages and every third page is giving error PYCHARM, django module Localhost Python 3,7 Django Latest version I have written all the URLs properly And it comes like that Localhost/maps this one is fine but the next click is Localhost/maps/reports now this is error I want that every time a link is clicked it goes back to localhost and then take the new link.The codes urls are like this from django.urls import path from . import views urlpatterns = [ path('', views.index), path('login/', views.login), path('maps/', views.maps), path('profile/', views.profile), path('preferences/', views.preferences), path('register/', views.register), path('reports/', views.reports), path('weather/', views.weather), path('help/', views.help), ] -
How to display PDF files in the same html page in file history in Django?
I have a web application created with Django in which a user can upload a pdf file. There is a view called 'file history' which displays the 'ID', 'Docfile', 'Source', 'Date'. And when a user clicks on a file name I'd like to display it in the same html page. I have read a lot of similar question on stackoverlflow and other sites on the internet but I did not find a useful guide except the one below: A similar solution can be found here: ChillarAnand's answer The html page looks like this: The code which produces this is: class Version(models.Model): docfile = models.FileField(upload_to = history_directory_path, db_column = 'docfile',max_length=500) source = models.CharField(max_length=50,default='') date = models.DateTimeField(auto_now_add=True, db_column='date') def doc_url(self): if self.docfile and hasattr(self.docfile, 'url'): return self.docfile.url How can I use this code snippet in my model? def embed_pdf(self, obj): # check for valid URL and return if no valid URL url = obj.pdf_file.url html = '<embed src="{url}" type="application/pdf">' formatted_html = format_html(html.format(url=obj.cover.url)) return formatted_html -
Django Rest Framework partial=True not working
I am a beginner in Django & DRF and I have a very dumb problem with my project, in which it doesn't allow me to do partial update. I am using generic views (UpdateAPIView) and I have been stuck with it for 2 weeks now. It allows me to update, however I have to fill every field but what I want to do is to pop email & mobile number if they are the same as the stored value in the database. Hoping someone might help and thank you in advance. Model: class BusinessPartner(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) mobile_number = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=150, unique=True) business_name = models.CharField(max_length=255, blank=True) type_of_business = models.CharField(max_length=150, blank=True) street_address = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=150, blank=True) state_province = models.CharField(max_length=150, blank=True) postal_zip = models.IntegerField(null=True, blank=True) services_offered = models.TextField(null=True, blank=True) account = models.ForeignKey(Account, on_delete=models.CASCADE) class Meta: ordering = ["-account"] def __str__(self): return self.first_name + " " + self.last_name Serializer: class BusinessPartnerSerializer(serializers.ModelSerializer): class Meta: model = BusinessPartner fields = [ "id", "first_name", "last_name", "mobile_number", "email", "business_name", "type_of_business", "street_address", "city", "state_province", "postal_zip", "services_offered", "account", ] extra_kwargs = {"id": {"read_only": True}} def update(self, instance, validated_data): partner = BusinessPartner.objects.get(account=instance) print("Previous mobile number: ", getattr(partner, "mobile_number")) print("New mobile number: … -
how can i resolve this 'Push rejected, failed to compile Python app. ! Push failed' error in heroku
i am getting this build error while deploying on heroku can anyone tell why is this error happened ? Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB) Collecting pyttsx3==2.90 Downloading pyttsx3-2.90-py3-none-any.whl (39 kB) Collecting pytz==2021.1 Downloading pytz-2021.1-py2.py3-none-any.whl (510 kB) ERROR: Could not find a version that satisfies the requirement pywin32==300 (from -r /tmp/build_7bcad96a/requirements.txt (line 99)) (from versions: none) ERROR: No matching distribution found for pywin32==300 (from -r /tmp/build_7bcad96a/requirements.txt (line 99)) ! Push rejected, failed to compile Python app. ! Push failed my requirements.txt has asgiref==3.4.1 beautifulsoup4==4.10.0 bs4==0.0.1 certifi==2021.5.30 charset-normalizer==2.0.4 Django==3.2.7 django-phone-field==1.8.1 djangorestframework==3.12.4 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==4.8.0 docutils==0.17.1 gunicorn==20.1.0o idna==3.2 Kivy==2.0.0 kivy-deps.angle==0.3.0 kivy-deps.glew==0.3.0 kivy-deps.sdl2==0.3.1 Kivy-Garden==0.1.4 Pygments==2.10.0 PyJWT==2.1.0 pypiwin32==223 pytz==2021.1 pywin32==301 requests==2.26.0 soupsieve==2.2.1 sqlparse==0.4.1 termcolor==1.1.0 urllib3==1.26.6 whitenoise==5.3.0 setuptools==0.7.3 is it just because of python or something else..? any solutions pls.. -
Django form is always returning false:
I am trying to update an entry. But form.save() is returning false. And I am unable to get the situation. Views.py def update(request, id): customer = Customer.objects.get(id=id) if request.method == "POST": form = customerForm(request.POST, instance=customer) if form.is_valid(): form.save() return redirect("/") else: return render(request, 'index.html') else: form = customerForm() return render(request, 'edit.html', {'customer': customer}) models.py from django.db import models from django.db import connections # Create your models here. class Customer(models.Model): # id = models.CharField(max_length=100) customer_name = models.CharField(max_length=256) phone = models.CharField(max_length=256) address = models.CharField(max_length=256) city = models.CharField(max_length=256) email = models.EmailField() product_company = models.CharField(max_length=256) product_brand = models.CharField(max_length=256) product_model = models.CharField(max_length=256) imei = models.CharField(max_length=20) reported_issue = models.CharField(max_length=256) possible_solution = models.CharField(max_length=256) actual_solution = models.CharField(max_length=256) estimated_time = models.CharField(max_length=256) actual_time = models.CharField(max_length=256) current_status = models.CharField(max_length=256) additional_notes = models.CharField(max_length=256) date_created = models.CharField(max_length=256) date_updated = models.CharField(max_length=256) class Meta: db_table = "datagrid" forms.py from django import forms from django.forms import fields, widgets from customerDetails.models import Customer class customerForm(forms.ModelForm): class Meta: model = Customer fields = ['id', 'customer_name', 'phone', 'address', 'city', 'email', 'product_company', 'product_brand', 'product_model', 'imei', 'reported_issue', 'possible_solution', 'actual_solution', 'estimated_time', 'actual_time', 'current_status', 'additional_notes', 'date_created', 'date_updated'] widgets = {'customer_name': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.TextInput(attrs={'class': 'form-control'}), 'city': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'product_company': forms.TextInput(attrs={'class': 'form-control'}), 'product_brand': forms.TextInput(attrs={'class': 'form-control'}), 'product_model': forms.TextInput(attrs={'class': 'form-control'}), … -
'Tag' object has no attribute 'count' in for loop
I am building a BlogApp and I am trying to create a notification when a particular tag is used 10 times. So i am using if statement in for loop so if any tag used 10 times then create notification But when i try to count then it is showing 'Tag' object has no attribute 'count' models.py class Post(models.Model): post_user = models.ForeignKey(User, on_delete=models.CASCADE) psot_title = models.CharField(max_length=30) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_of = models.ForeignKey(Post, on_delete=models.CASCADE) views.py def page(request): subquery = Tag.objects.filter(post__post_user=request.user).annotate( num_name=Count('name') for que in subquery: if que.count() > 10: Notification.objects.create(user=request.user) context = {'subquery':subquery} return render(request, 'page.html', context} What have i tried :- I also tried len like :- for que in subquery: if len(que) > 10: Notification.objects.create(user=request.user) But it showed object of type 'Tag' has no len() I have tried many times by removing count() and len() but it showed 'int' object has no attribute 'name' Any help would be much Appreciated. Thank You -
Django: How to pass js variable to html template as tag
My task is to send the result of the test, created using javascript, to the html-template to use it in the {% if mark> = 4%} tag, in order to write to the database that the test is passed. I tried composing an ajax request but not sure if it is correct. views.py def practice(request, lesson_id): form = LessonDone() posts = get_object_or_404(Lessons, pk=lesson_id) lessonid = Lessons.objects.get(pk=lesson_id) mark = request.POST.get('url') if request.method == 'POST': p, created = DoneLessonsModel.objects.get_or_create( user=request.user, lessons=lessonid, defaults={'done': True}, ) form = LessonDone(request.POST, instance=p) if form.is_valid(): try: form.save() return redirect('practice') except: form.add_error(None, 'Ошибка') context = {'posts': posts, 'form': form, 'mark': mark} return render(request, 'landing/../static/practice.html', context) urls.py ... path(r'lesson/<int:lesson_id>/practice/', views.practice, name='practice'), ... practice.html ... <div class="buttons "> <button class="restart btn-dark">Перепройти тест{{ mark }}</button> {% if mark >= 4 %} <form action="" method="POST"> {% csrf_token %} {{ form }} {% endif %} <button class="quit btn-dark" type="submit" value="Submit" id="send-my-url-to-django-button">Выйти</button> {% if mark >= 4 %} </form> {% endif %} </div> ... </script> <script type="text/javascript"> $(document).ready(function() { var url = userScore; $("#send-my-url-to-django-button").click(function() { $.ajax({ url: {% url 'practice' posts.pk %}, type: "POST", dataType: "json", data: { url: url, csrfmiddlewaretoken: '{{ csrf_token }}' }, success : function(json) { alert("Successfully sent the URL to … -
How to restrict staff unauthorize access to admin page django?
I have created my admin page, so when the admin login it will redirect them to this url http://127.0.0.1:8000/home/, but the admin can change the url to http://127.0.0.1:8000/logistic/ after they login, how to prevent this from happen? Any help would be appreciated -
Connect c# windows app to django website with api
i have a Django website and a c# windows application , i want to create encrypted web api and read this api in my c# win app, the most important thing is security , i want a solution to do it , -
How to manage Django form validation with dynamically generated forms
Let's say I have the following html page: LIVE CODE Let's say that in each row there is a form (I have to implement it), How can I do so that when I click on 'save' button (also to be implemented) all the inputs of each row are sent in the request.POST and I can process them individually in the backend. This is my view for a new expense: def new_expense(request): data = { 'title': "New Expense", } data['projects'] = Project.objects.filter(is_visible=True).values('id') data['expense_category'] = dict((y, x) for x, y in EXPENSE_CATEGORY) data['expense_type'] = dict((y, x) for x, y in EXPENSE_TYPE) form = ExpenseForm() if request.method == "POST": reset = request.POST['reset'] form = ExpenseForm(request.POST) if form.is_valid(): form.save() if reset == 'true': form = ExpenseForm() data['form'] = form return render(request, "expense/new_expense.html", data) I would like to create a similar view for multiple new expense creation. -
Django Templates - How to auto increment an integer?
I'm using Django with Alpine.js. I'm trying to loop over users' images from 1 to 20. For instance, 'user-1.jpg', 'user-2.jpg', and so on and so forth. The following is, of course, not working, but at least it will give you a sense of what I'm trying to achieve: {% load static %} <template x-for="(item, index) in items" :key="index" hidden> <img class="absolute rounded-full z-10 animate-float" :style="item.style" :src="`{% static img/user-${index+1}.jpg %}`" :width="item.size" :height="item.size" :alt="`User ${index+1}`" @mouseenter="active = index; commentOn = true" @mouseleave="commentOn = false" /> </template> I know that I probably should use {{ forloop.counter }} but I'm not sure how exactly should I use it in this type of context. -
Fetching data from outside API with Authorization key in Django
I am trying to fetch data from outside API with post method in django. in my views.py I can fetch data with: response = requests.post('https://url_address').json() It works totally fine for simple APIs but when come to authorized API, i.e. I need to put some value like Content-Type, Authorization in header in postman or some command in body->raw in postman, I can't fetch data with the aforementioned simple Django syntax. It says: {'Message': 'Request data is in Bad Format.'} Please help how can I add Header and Body commands with this API call from Django? -
How to convert unicode character to decimal in Django
Here let us consider my unit_price to be 1000 my views.py as class StockView(View): def get(self, request, id=None): stock_movement = StockMovements.objects.filter(client=client) item_unit_price = request.GET.get('unit_price','') if item_unit_price: if '=' in item_unit_price: unit_price = item_unit_price.split('=')[1].strip() price = Decimal(unit_price) stock_movement = stock_movement.filter(item__unit_price=price) if '>' in item_unit_price: unit_price = item_unit_price.split('>')[1].strip() price = Decimal(unit_price) stock_movement = stock_movement.filter(item__unit_price__gte=price) def autocomplete_items(request): client = request.user.client q = request.GET.get('term') job_items = JobItems.objects.filter(client_id=client) products = job_items.filter(Q(item_name__icontains=q)|Q(unit_price__gte=q),is_deleted=False) return HttpResponse(json.dumps(res[:15])) Here is my template.html <div class="form-search contacts-search pull-right {% if searchapplied %}search-applied{% endif %}"> <form method="GET"> <div {% if search %} class="input-append"{% endif %}> <input type="text" class="search-query" name="unit_price" id="item_unit_price" placeholder="Unit Price" class="ui-autocomplete-input" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span> <button class="btn btn-danger" type="submit" style="margin-bottom: 8px;"> <i class="fa fa-search" aria-hidden="true"></i> </button> </div> </form> here is my script for template.html $('#item_unit_price').autocomplete({ source: function(request, response) { $.ajax({ url: "/autocomplete_items/?flag=True", data: { term: request.term, unique: true, }, dataType: 'json', success: function(json_data) { var chain_names = []; for(i=0; i<json_data.length; i++) { chain = json_data[i]; chain.value = json_data[i].label; chain.label = json_data[i].label; chain_names.push(chain); } response(chain_names); } }) }, minLength: 1, select: function(event, ui) { $( "#item_unit_price" ).val( ui.item.value);; } }); here is my models.py class StockMovements(models.Model): item = models.ForeignKey(JobItems, related_name="stock_movements") class JobItems(models.Model): unit_price = models.DecimalField(null=True, max_digits=10, decimal_places=2, default=0.00, verbose_name='Retail price') Now if … -
Django How to bring data into url from DB?
Models.py from django.db import models # Create your models here. class reviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() class buildingData(models.Model): building_name = models.CharField(max_length=50) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) views.py # Create your views here. from django.shortcuts import render from rest_framework.response import Response from .models import reviewData from .models import buildingData from rest_framework.views import APIView from .serializers import ReviewSerializer class BuildingInfoAPI(APIView): def get(request): queryset = buildingData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(request): queryset = reviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), #path('api/buildingdata/(I want to put building name here)', ReviewListAPI.as_view()) ] I am making review api. I want to use building name as url path to bring reviews for specific buildings For example, there are a, b, c, d, e reviews a, b, c reviews are for aaabuilding d, e reviews are for aaabuilding api/buildingdata/aaabuilding (only shows aaabuilding review) api/buildingdata/xxxbuilding (only shows xxxbuilding review) I've searched some dynamic url posts, but they were not that i want. Is there any way to bring building name into url from db? -
How to use Curl post request for Django
I am new to Django. My application post request to/from zabbix and doesnt have authentication mechanism and I am not using REST framework. My setup is Django+Nginx+Gunicorn_Whitenoise+Certbot for SSL on RHEL box. I have a requirement to post data using curl command. I tried using curl with -X POST -G options but getting error. Most of the google search says to use REST ful framework. Please advise on best solution to use curl post request for existing Django application with minimun modifications. -
Django server not opening with 0.0.0.0:8000
I have a AWS server runs on Nginx and which hosts a React application working fine on server. Now I want a Django app for restframework to be available on the same server. Iam following the Document and uploaded the Django app on the server and try to run the app by trying python3 manage.py runserver 0.0.0.0:8080. There is no error but I cannot access my ip with http://server_domain_or_IP:8080. Please help where am I going wrong? -
How to run to bot on DigitalOcean
I have bot in my Django project and I deployed my project to DigitalOcean my site working but I don't know how do run to bot I tried write to gunicorn but it is not working. How to write to gunicorn python manage.py bot enter image description here -
Number of Tags used in post which were commented by user
I am building a simple Blog App and I am trying to implement a feature. In which, If a user commented on a post with post tags - tag1, tag2. And I will retrieve the Tags of which user commented on post And i am trying to count Number of times a user commented on a post with same tag Like I am trying to show :- Tag Name Number of times used tag1 16 Times tag2 10 Times tag3 8 Times This table is showing :- User commented on a post with the tag which was used in previous post. For Example :- A new user named "user_1" commented on a Post with tags tag5, tag6, tag8 then A query will show that user_1 has commented on post tags 1 times in tag5 , 1 time in tag6 and 1 time in tag8. And I will do the rest later. models.py class BlogPost(models.Model): user = models.ForeinKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) tags = TaggableManager() class Comment(models.Model): comment_by = models.ForeignKey(User, on_delete=models.CASCADE) on_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) views.py def examplePage(request): query = Tag.objects.filter(blogpost__user=request.user) context = {'query': query} return render(request, 'examplePage.html', context) This view is showing tags which are used in post which were …