Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prepopulate Values of Edit Form from Table Selection
I am trying to create an Edit for that allows the user to scroll through a table and click a button existing in each row to edit the data within a modal. The issue that I am running into is when I try to prepopulate the form with the existing values. How would I convert the EditCommunicationsForm below to display the current values of the row that you selected edit for? I know I can make the initial value a default value like "Testing" but I am not quite sure how to tell it to say "grab the project field from the row that you selected" What I want to do is ID = {{ communications.id }} for my table, but obviously that's wrong since it's half HTML. I need some sort of variable to change that definition for each row views def communications(request): comms_list = Communications.objects.order_by('id') if request.method == "POST": new_form = CommunicationsForm(request.POST, request.FILES) edit_form = EditCommunicationsForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('http://127.0.0.1:7000/polls/communications/',{"new_form":new_form,"edit_form":edit_form,'comms_list':comms_list}) else: comms = Communications.objects.get(id=1) new_form = CommunicationsForm() edit_form = EditCommunicationsForm(instance=comms) query = request.GET.get('search') if query: postresult = Communications.objects.filter(id__contains=query) comms_list = postresult else: comms_list = Communications.objects.order_by('id') return render(request,'polls/communications.html',{"new_form":new_form,"edit_form":edit_form,'comms_list':comms_list}) forms class CommunicationsForm(forms.ModelForm): class Meta: model = Communications fields … -
whitenoise does not serve the changes on static files in django
I am using whitenoise in my django app on production but i noticed that wtenoise cannot serve the changes in statis files during the app is running what should i do to launch the app on production and serve the changes on static files? I have been installed whitenoise using pip and make debug = False then added my whitenose middleware into the MIDDLEWARE list after the SecurityMiddleware then added the following line in settings.py file STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' -
ModuleNotFoundError: No module named 'mysite' import from wsgi.py
I'm trying to run a python file in a django project and I get this error : Traceback (most recent call last): File "data.py", line 2, in <module> from Spiders.vb_json_cleaner import * File "/home/debian/repay-moi/phones/Spiders/vb_json_cleaner.py", line 9, in <module> from mysite.wsgi import * ModuleNotFoundError: No module named 'mysite' Here is my wsgi.py file : import os from django.core.wsgi import get_wsgi_application path = '/home/debian/repay-moi/mysite' if path not in sys.path: sys.path.append(path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() And my vb_json_cleaner.py import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from mysite.wsgi import * application = get_wsgi_application() from phones.models import * -
Dynamic initial form data
I am attempting to add a button to the customer's page to add a new device but when rendering the form I would like to pass the customer's name as an initial value. This was my personal Christmas project to make my work projects a bit more centralized in 2021. Im almost over the finish line but I've hit this bump. Any help would be appreciated. Thanks. I have two models in separate apps. class Customer(models.Model): nameF = models.CharField("First Name", max_length=255, blank = True, null = True) nameL = models.CharField("Last Name", max_length=255, blank = True, null = True) nameN = models.CharField("Nickname", max_length=255, blank = True, null = True) address = models.CharField("Address", max_length=255, blank = True, null = True) phone = models.CharField("Phone", max_length=255, blank = True, null = True) email = models.EmailField("Email", max_length=254, blank = True, null = True) dateC = models.DateTimeField("Date Created", auto_now_add=True) dateU = models.DateTimeField("Last Updated", auto_now=True) note = models.TextField("Notes", blank = True, null = True) def __str__(self): return self.nameF def get_absolute_url(self): return reverse ("cfull", kwargs={"pk": self.id}) and class Device(models.Model): CONNECTION = ( ('Local', 'Local'), ('IP/DOMAIN', 'IP/DOMAIN'), ('P2P', 'P2P') ) TYPE = ( ('DVR', 'DVR'), ('NVR', 'NVR'), ('Router', 'Router'), ('WLAN Controller', 'WLAN Controller'), ('AP', 'AP'), ('Doorbell', 'Doorbell'), ('Audio Controller', … -
Access Data in MS Access via Django
I have information that is stored in MS Access and I need to display it through a web application(Django). Is there a way to include the connection in the settings.py of Django , like other databases, so as to use Django features? -
Reverse for 'teamEdit' with no arguments not found. 1 pattern(s) tried: ['teams/teamEdit/(?P<team_id>[0-9]+)/$']
Error : NoReverseMatch at /teams/teamEdit/12/ I'm a beginner in Django. I'm trying to make a team app. But while Edit the team I'm facing some error. Already I've tried some solutions from stackover flow but still showing the error. Here Is The Code : teamlist.html : <a class="font-w500 align-items-center text-primary btn btn-link" href="{% url 'team:teamEdit' team.id %}"> Edit <i class="fa fa-edit ml-1 opacity-50 font-size-base text-primary"></i> </a> urls.py: path('teamEdit/<int:team_id>/', teamEdit, name='teamEdit'), views.py: @login_required def teamEdit(request, team_id): print(team_id) team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) print(team.title) if request.method == 'POST': title = request.POST.get('title') if title: team.title = title team.save() messages.info(request, 'The changes was saved') return redirect('team:teamList') else: return render(request, 'teamEdit.html', {'team': team}) teamEdit.html: <h3 class="text-center">Eupdate Team</h3> <form class="mb-5" method="post" action="{% url 'team:teamEdit' team.id %}"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control form-control-lg form-control-alt" id="id_title" name="title" v-model="title" placeholder="Title"> </div> <div class="form-group"> <button type="submit" class="btn btn-block btn-success">Save</button> </div> </form> Error Traceback : Traceback (most recent call last): File "C:\Django\TaskTracker\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Django\TaskTracker\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Django\TaskTracker\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Django\TaskTracker\venv\ttm\apps\team\views.py", line 68, in teamEdit return render(request, 'teamEdit.html', {'team': team}) File "C:\Django\TaskTracker\venv\lib\site-packages\django\shortcuts.py", line 19, in render … -
Increase performance with prefetch and select related
I'm trying to export a csv with information from the model order which has a relation 1 to 1 with delivery channel and restaurant and a 1 to many relationship with orderlines. It is taking way too much time for download it (around 20 seconds for 10k lines). This is my code: orderlines = OrderLine.objects.select_related("product").only( "product__display_name", "quantity", "paid_amount", "discount_amount" ) return ( Order.objects.prefetch_related(Prefetch("orderlines", queryset=orderlines, to_attr="orderlines_list")) .select_related("delivery_channel") .select_related("restaurant") ) I thought about using only in the end but I can't use it on orderlines as it is a 1 to many relationship. I'm stuck on how to improve the performance. Many thanks. -
Django: How to enable users to delete their account
I am unsure of what went wrong but my I cannot delete my own account despite setting is_active=false I tried 3 different types of views in my views.py but to no avail.I'm not sure which view to use. Everytime i click delete account, i will be redirected to the homefeed page and nothing will happen as the account still remains. Please tell me if more information is required Views.py @user_passes_test(lambda account: account.is_superuser, login_url=reverse_lazy('login')) def delete_user_view(request, user_id): context = {} if not request.user.is_authenticated: return redirect("login") try: user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) account.is_active = False account.save() context['msg'] = 'The user is deleted.' except Account.DoesNotExist: context['msg'] = 'User does not exist.' except Exception as e: context['msg'] = e.message return render(request, 'HomeFeed/snippets/home.html', context) def delete_user_view(request, user): user = request.user user.is_active = False user.save() logout(request) messages.success(request, 'Profile successfully disabled.') return redirect('HomeFeed:main') class CustomUserDeleteView(DeleteView): model = Account success_url = reverse_lazy('login') urls.py from account.views import ( delete_user_view, CustomUserDeleteView,) path('deleteaccount/<pk>', CustomUserDeleteView.as_view(template_name='account/account.html'), name='deleteaccount'), account.html <a class="mt-4 btn btn-danger deleteaccount" onclick="return confirm('Are you sure you want to delete your account')" href="{% url 'account:deleteaccount' user_id=request.user.id %}">Delete Account</a> -
AssertionError: `child` is a required argument [closed]
when developing my application I ran into a problem that is, I tried to update and create in the database a record of this kind [ { cpNameID: {cpSubName: "[JK]린다", cpName: "[JK]린다(비오엠)"}, docNumber: "OT201912270971-001", dvClass: "반품", odNumber: "[162-191217-001]", odQuantity: -1, pdID: null, phPrice: -19500, productID: {erpID: "9810779001060", pdName: "바비리스‥에어 브러쉬‥AS100VK‥3in1 멀티 에어 스타일러 900W", pdOption: null}, shippingDate: "2020-01-01", spPrice: -22364 }, { cpNameID: {cpSubName: "[JK]리빙픽", cpName: "[JK]리빙픽"}, docNumber: "OT201912307179-001", dvClass: "반품", odNumber: "77384890", odQuantity: -1, pdID: null, phPrice: -4195, productID: {erpID: "9810779003068", pdName: "CHI‥케라틴‥케라틴 컨디셔너", pdOption: "240ml"}, shippingDate: "2020-01-01", spPrice: -10055, }, { cpNameID: {cpSubName: "[JK]별난맘", cpName: "[JK]별난맘"}, docNumber: "OT201912310095-001", dvClass: "반품", odNumber: "201911290009", odQuantity: -1, pdID: null, phPrice: -44182, productID: {erpID: "9810779005184", pdName: "EMK‥가습기‥EK-H3C40WH", pdOption: null}, shippingDate: "2020-01-01", spPrice: -52727, } ] here is my serializer.py class OrderListSerializer(serializers.ListSerializer): def create(self, validated_data): Orders = [OrderList(**item) for item in validated_data] return OrderList.objects.bulk_create(Orders) class ComMappingSerializer(serializers.Serializer): cpSubName = serializers.CharField() cpName = serializers.CharField() class ProductListSerializer(serializers.Serializer): erpID = serializers.CharField(required=True) pdName = serializers.CharField(required=True) pdOption = serializers.CharField() class OrderSerializer(serializers.Serializer): shippingDate = serializers.DateField(required=True) dvClass = serializers.CharField(required=True) cpNameID = ComMappingSerializer(required=True) odNumber = serializers.CharField() docNumber = serializers.CharField(required=True) pdID = serializers.CharField() productID = ProductListSerializer(required=True) odQuantity = serializers.IntegerField(required=True) spPrice = serializers.IntegerField(required=True) phPrice = serializers.IntegerField(required=True) def valldate_cpNameID(self, value): exam, _ = ComMapping.objects.get_or_create( cpSubName=value.cpSubName, … -
Why Button is not showing in javascript
In my project, button not showing in frontend. what can i do for showing the button??? please help me. <script> function updatePopover(product_cart){ console.log('we are in updatePopover'); var popStr = ""; popStr = popStr + "<h5>cart for your items</h5> <div class='mx-2 my-2'>"; var i =1; for (var item in product_cart){ popStr = popStr + "<b>" + i + "</b>. "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 25) + "... Qty: " + product_cart[item] + '<br>'; i = i+1; } popStr = popStr + "</div> <a href='/checkout' class='btn_1' id='checkout'>CheckOut</a> **<button class='btn_1' onclick='clearCart()'>Clear Cart</button><button class='btn btn-primary'></button>** " document.getElementById("popcarts").setAttribute('data-content', popStr); $('#popcarts').popover('show'); } <script> -
Django BooleanField if statement doesnt return content
For some reason when checking to see if BooleanField post.featured is true I get no output. If I remove that it works fine but not as I intend. <div class="carousel-inner"> {% for post in object_list%} {% if post.featured is True %} <!-- This post.featured is BooleanField --> {% if forloop.first %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <div class="col-md-6 px-0"> <h1 class="display-4 font-italic">{{ post.title }}</h1> <p class="lead my-3">{{ post.hook }}</p> <p class="lead mb-0"> <a href="{% url 'article-details' post.pk %}" class="text-white fw-bold"> Continue reading... </a> </p> </div> </div> {% endif %} <!-- and this --> {% endfor %} </div> Heres how it looks like when not checking if post.featured == true: Working However, content doesnt render with {% if post.featured is True %} or {% if post.featured %} Can someone please explain what im doing wrong -
Foreign Key with Django REST Serializers
I'm having trouble figuring out how to get the Foreign key relationship to work with my Django REST api. I have a model from django.db import models from django.core.validators import RegexValidator # Create your models here. class Hero(models.Model): alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') name = models.CharField(max_length=60, blank=True, validators=[alphanumeric]) alias = models.CharField(max_length=60) def __str__(self): return self.name class SideKick(models.Model): alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') hero = models.ForeignKey(Hero, related_name='sidekicks', on_delete=models.CASCADE) sideKick_name = models.CharField(max_length=60, validators=[alphanumeric]) def __str__(self): return self.sideKick_name Serializers from rest_framework import serializers from .models import Hero, SideKick class HeroSerializer(serializers.HyperlinkedModelSerializer): sidekicks = serializers.SlugRelatedField(many=True, read_only=True, slug_field='title') class Meta: model = Hero fields = ('name', 'alias', 'sidekicks') class SideKickSerializer(serializers.HyperlinkedModelSerializer): sideKick_name = HeroSerializer() class Meta: model = SideKick fields = ('sideKick_name') Here is what the api webpage looks like I'm fairly new to this and was wondering how I can get the option to select a Hero to create a sidekick through the API webpage. every time i create a hero the sidekick field is blank. Any help would be apperciated. -
Django get values from field after order_by
I am trying to get the shared values from a field after ordering my model based on one of its fields. So for example I have a model named Course: class Course(models.Model): code = models.CharField(max_length=100) university = models.CharField(max_length=100) instructor = models.CharField(max_length=100) and then for ordering based on instructor I do: Course.objects.all().order_by('instructor').distinct('instructor') Which will then give me for example ABC123, Uni1, Adamson EFG456, Uni1, Adamson HIJ789, Uni1, James KLM321, Uni1, James How can I retrieve the results as a dictionary with the keys being the instructor and the value being a query set of model object? So I will get something such as: result = { "Adamson":<QuerySet[]>, "James":<QuerySet[]> } I cannot find an aggregate function that does this is there any way to do this using a single method? -
is there a way to change the date format in django/html?
i am still new to django and i am following a tutorial but when the guy i had the error the method he used didnt work for me - i am get this error althogh the default format for date is yyyy- mm-dd - any help will be appreciated ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] this is my save function that inputs the data into the database def add_seniorEmployee_save(request): if request.method!="POST": return HttpResponse("Method Not Allowed") else: first_name=request.POST.get("first_name") last_name=request.POST.get("last_name") username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") Dob=request.POST.get("Dob") Nationality=request.POST.get("Nationality") Address=request.POST.get("Address") Postcode=request.POST.get("Postcode") Telephone=request.POST.get("Telephone") Wage=request.POST.get("Wage") Passportnumber=request.POST.get("Passportnumber") passportexpirydate=request.POST.get("passportexpirydate") gender=request.POST.get("gender") kinname=request.POST.get("kinname") kinrelation=request.POST.get("kinrelation") kinaddress=request.POST.get("kinaddress") kinphonenumber=request.POST.get("kinphonenumber") kinemail=request.POST.get("kinemail") #try: user = CustomUser.objects.create_user(username=username,password=password,email=email,first_name=first_name,last_name=last_name,user_type=2) user.senioremployee.Dob = Dob user.senioremployee.Nationality = Nationality user.senioremployee.Address = Address user.senioremployee.Postcode = Postcode user.senioremployee.Telephone = Telephone user.senioremployee.Wage = Wage user.senioremployee.Passportnumber = Passportnumber user.senioremployee.passportexpirydate = passportexpirydate user.senioremployee.gender = gender user.senioremployee.profile_pic="" user.senioremployee.kinname = kinname user.senioremployee.kinrelation = kinrelation user.senioremployee.kinaddress = kinaddress user.senioremployee.kinphonenumber = kinphonenumber user.senioremployee.kinemail = kinemail user.save() this is the model for my senior employee who i am adding to the database this is the model to create the customer user class CustomUser(AbstractUser): user_type_data=((1,"Admin"),(2,"senioremployee"),(3,"employee")) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) class senioremployee(models.Model): id = models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) Dob = models.DateField() Nationality = models.TextField() Address = models.TextField() Postcode = models.TextField() Telephone = models.TextField() … -
How to use OSMnx with Django?
I want to create app that will calculate route between given points on map. I'm using Conda for managing my environment. In my venv I have installed Django and OSMnx. After adding OSMnx server won't run. The stacktrace is pretty long and ends with this: with fiona._loading.add_gdal_dll_directories(): AttributeError: module 'fiona' has no attribute '_loading' In my Django project i have one app called planner and the view is using OSMnx (not sure if this code should go there) and it looks like this: from django.shortcuts import render from django.http import HttpResponse, JsonResponse import osmnx as ox ox.config(use_cache=True, log_console=True) # Create your views here. def index(request): # As for now it is ok to hardcode place and network type warsaw_streets = ox.graph_from_place("Warsaw", network_type="drive") return JsonResponse({}) Im new to Django and I don't know if I'm using external library wrong or what is the purpose of this error... -
configuring the urls.py gives problem in the url generation
I have an application running django 3.1. I do have problems with the urls. I guess there is either a problem with the urls.py or in my asociated view. In my application, the view (fil main.py) is called "main". If I go the the url http://127.0.0.1:8000/main/, I see a correct rendering of the view. My view includes a button to click on. When I click, the url is now: http://127.0.0.1:8000/main/**main/** which is an error (404 page not found). My url.py is: from django.urls import path from django.conf import settings from django.conf.urls.static import static from django.urls import re_path from django.views.static import serve from . import main urlpatterns = [ path('main/', main.main, name='main'), path('', main.main, name='main'), ] My view uses the following: return render(request,'main.html') Thanks. S/ -
What is the proper way to send a post with a file with createReadStream to a django server api?
I'm trying to send a large file with filestream over a post request this way m.request({ url: get_pam_url(kg('host')) + '/api/v1/arquivo_client/', method: 'POST', data: { content: fs.createReadStream(file_path), }, headers: { 'Authorization': 'Token ' + kg('token'), 'content_type': 'application/octet-stream', }, }) and on my django view, when i do. request.data it returns a json with this info. {u'content': {u'_readableState': {u'encoding': None, u'sync': True, u'paused': True, u'ended': False, u'autoDestroy': False, u'readableListening': False, u'objectMode': False, u'emitClose': False, u'destroyed': False, u'defaultEncoding': u'utf8', u'length': 0, u'reading': False, u'resumeScheduled': False, u'highWaterMark': 65536, u'buffer': {u'length': 0, u'head': None, u'tail': None}, u'flowing': None, u'readingMore': False, u'decoder': None, u'needReadable': False, u'awaitDrain': 0, u'endEmitted': False, u'pipes': None, u'pipesCount': 0, u'emittedReadable': False}, u'closed': False, u'end': None, u'readable': True, u'_eventsCount': 1, u'_events': {}, u'fd': None, u'mode': 438, u'autoClose': True, u'flags': u'r', u'path': u'\\Users\\my_folder\\project\\tmp\\2020aq.xlsx.gz', u'bytesRead': 0}} how can i get the complete .gz file correctly on my django view? -
SyntaxError while using XLSXWRITER
I'm using xlsx writer in django to write some data in an excel file for users to download, but I keep getting a syntax error in my views.py file. Here is the functions thats raising the error: def excelr(request): user = getuser(request) registrations = Registration.objects.filter(MUN = user) path = str(f"registrationsdb/{user.username}{str(datetime.now())}registrations.xlsx") workbook = xlsxwriter.Workbook(path) worksheet = workbook.add_worksheet() worksheet.write(0,0, 'Delegate Name') worksheet.write (0,1, 'Age') worksheet.write(0,2, 'Instiution') worksheet.write (0,3, 'Email - ID') worksheet.write(0,4, 'City') worksheet.write(0,5, 'Experience') experience=[] for row in registrations: dele = row.delegate exp = Experience.objects.filter(delegate = dele) experience.append(exp) for i in range(0, len(registrations)): worksheet.write(i+1,0, str(registrations[i].delegate.name)) worksheet.write(i+1,1, str(registrations[i].delegate.age)) worksheet.write(i+1,2, str(registrations[i].delegate.institution)) worksheet.write(i+1,3, str(registrations[i].delegate.email)) worksheet.write(i+1,4, str(registrations[i].delegate.city)) worksheet.write(i+1,5, str(expstring(exp[i])) workbook.close() return path In the abover expstring(arr) returns a string value. I'm having errors raised post the line with workbook.close() (This function returns a path to the views.py route function to create a download link for on my html) I've installed all the required packages but cant seems to figure out the fix. Looking for some help on the same. Thanks -
Single Click MultiFiles upload in Django Admin saves only the last file
Please safe my day. I am struggling to upload mulitple files in Django Admin Page but its saving only one file. I can select the multiple files but when I saving, its saving only one file and the Char field. Below are the codes models.py from django.db import models # Create your models here. class ProjectInfo(models.Model): project_title = models.CharField(max_length=30) class ProjectFiles(models.Model): projectinfo = models.ForeignKey(ProjectInfo, on_delete=models.CASCADE) uploaded_files = models.FileField() forms.py from django import forms class ShowProject(forms.ModelForm): uploaded_files = forms.FileField( widget=forms.ClearableFileInput(attrs={"multiple": True}), required=False, ) admin.py from django.contrib import admin from .models import ProjectFiles, ProjectInfo from .form import ShowProject # Register your models here. class InlineForm(admin.StackedInline): model = ProjectFiles form = ShowProject extras = 1 max_num = 1 class ProjectInfoAmin(admin.ModelAdmin): inlines = [InlineForm] def save_model(self, request, obj, form, change): obj.save() if (form.is_valid()): files = request.FILES.getlist('uploaded_files') for f in files: obj = ProjectFiles() obj.uploaded_files = f super().save_model(request, obj, form, change) admin.site.register(ProjectInfo, ProjectInfoAmin) Thanks for your support. -
Django OneToOne field, reverse not required
I want to have a OneToOne relationship between to models; class Pet(models.Model): name = models.CharField() class Collar(models.Model): color = models.CharField() pet = models.OneToOneField(Pet, related_name='my_collar', on_delete=models.CASCADE) class CollarSerializer(serializers.ModelSerializer): class Meta: model = Collar fields = ['id', 'collor', 'pet'] class PetSerializer(serializers.ModelSerializer): collar = CollarSerializer() class Meta: model = Pet fields = ['id', 'name', 'collar'] I run into a problem though: if I want to POST a new pet that doesn't have a collar, it won't let me, it says that field is required. I thought of using ForeignKeyField for this, but I want to make sure the system knows it is a one-to-one relationship so I don't get a list of one collar, but rather one collar. -
Django Filter ManyToManyField
I'm working on a django project, and as I'm quite new to this framework and backend in general, I'm having a hard time finding out how to do this. I'm building a ListView that is used to display a list of products in a template. However, I need it to only display the products made available on the site by the dealer who's currently logged in. So in other words, just a page where a dealer can see what products they've put on our site. Here's my view: class ArticleListView(ListView, LoginRequiredMixin): template_name = "accounts/list_articles.html" model = Product def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context["website"] = Website.objects.first() context["product_list"] = context["product_list"].filter(published=True) return context Here's the Products and Dealers models (only the relevant parts): class Product(models.Model, CloneMixin): published = models.BooleanField(null=True,blank=True, default=False) title = models.CharField(null=True,blank=True,max_length=100) subtitle = models.CharField(null=True,blank=True,max_length=200) (...) dealer = models.ManyToManyField(Dealer, null=True,editable=True,related_name="product_to_dealer") (...) # Not sure what this does: _clone_many_to_many_fields = ['parameter', 'tag', 'category', 'dealer','images'] (...) class Dealer(models.Model, CloneMixin): dealer_check = models.ForeignKey("self",null=True, blank=True, on_delete=models.SET_NULL) published = models.BooleanField(null=True,blank=True, default=True) (...) users = models.ManyToManyField(User,null=True,blank=True, related_name='dealers') (...) As it is, my ListView just displays every products there is in the db. From what I've understood, I need something like def get_queryset(self): return Product.objects.filter(user=self.request.user) or in the get_context_data, … -
how to join two Models (tables) Using Django ORM , when there is no relation ship between them
How to join two models using Django ORM, in simple how to write join queries in Django ORM like SQL join query , even though there is no relation between two models . and one special doubt , how to list the employees with the second highest salary from a employee table; using Django query -
Positions in CSS
I am making a blog posting site in Django. When users post something it looks great if the title of the post has 21 characters. If the title for instance has 35 characters it moves the author, date and thumbnail to the right and if less than 21 it moves it to the left. I don't want this scenario to happen! This is how it currently looks The HTML code {% for post in posts %} <div class="blogpost"> <a class="post-title"> {{post.title}} </a> <img class="thumbnail" src="{{post.author.imageURL}}"> <a class="date-author">{{post.date}} - {{post.author}}</a> <br> <hr> <br> <div class="blogpost-content">{{post.context|linebreaks}}</div> <br> <br> <br> </div> <br> {% endfor %} The CSS code .blogpost { /*Whole blogpost div*/ border: 5px solid #149414; background-color: black; color: #149414; width: 700px; margin:auto; border-radius: 40px; border-width: 1px; } hr{ /*The middle line in the blogpost*/ height: 1px; background-color: #149414; border: none; } .thumbnail{ /*The author's image of the blogpost*/ height: 120px; width: 120px; position: relative; right: -70px; bottom: 4px; border: 3px solid #149414; border-radius: 50%; } .blogpost-content{ /*Content in the blogpost*/ text-align: left; margin-left: 30px; margin-right: 30px; } .date-author{ /*The date and author div in the blogpost*/ font-size: 12; margin:10%; } .green_link{ /*Green link to the random key*/ color:#149414; } .post-title{ font-size: … -
Creating a like button in django social media network
I'm new to django and I'm trying to create a like button for my blog posts. In my HomeFeed app However, I received this error when i click on the like button that i have created: ValueError invalid literal for int() with base 10: I am given a pointer that the problem comes from this statement: post = get_object_or_404(BlogPost, id=request.POST.get('blog_post_slug')) Is it because they are expecting all integers in the url but it is getting character values? I am unsure of how to change it and have tried for multiple hours. Views.py def LikeView(request, slug): context = {} post = get_object_or_404(BlogPost, id=request.POST.get('blog_post_slug')) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) return HttpResponseRedirect(reverse('HomeFeed:detail',args=[str(BlogPost.slug)])) def detail_blog_view(request, slug): context = {} #need to import a package get_object_or_404. return object or throw 404 blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, 'HomeFeed/detail_blog.html', context) models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.chief_title def total_likes(self): return self.likes.count() urls.py from .views import( detail_blog_view, LikeView, ) urlpatterns = [ path('<slug>/detail/', detail_blog_view, name= "detail"), path('<slug>/edit/', edit_blog_view, name= "edit"), path('<slug>/like/', LikeView, name='like_post'), ] detail_blog.html <form action="{% url 'HomeFeed:like_post' … -
How to have a model field be based on another models fields?
Relatively new to Django. I think what I'm trying to do is very simple but I've never done this before. "irrelevant2" is an attribute in my class "one" that I want to refer to a direct element in the class "two" (this part is working fine). Additionally, I want there to be a field called RELEVANT_VARIABLE in my class "one" that is essentially a dropdown menu that chooses between two elements of the class "two" and can only pick one. I understand that I need a form but so far have not been successful. My hunch says RELEVANT_VARIABLE should be a ForeignKey but I'm not sure how to attach it to a dropdown of either attr1 or attr2 from class "two". class two(models.Model): attr1 = models.CharField(max_length=100) attr2 = models.CharField(max_length=100) class one(models.Model): irrelevant1 = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) irrelevant2 = models.ForeignKey(two, on_delete=models.CASCADE) RELEVANT_VARIABLE = models.ManyToManyField(two, related_name="team_selection") And then in forms.py class OneForm(forms.Form): def __init__(self, *args, **kwargs): super(OneForm, self).__init__(*args, **kwargs) self.fields[**not sure what to even put here**] = forms.ChoiceField( choices=[(o[**not sure**], str(o[**not sure**])) for o in Two.objects.filter(irrelevant2=self)] ) class Meta: model = two