Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying into App Engine + Cloud SQL + Cloud Storage - How to keep costs low?
Context I'm deploying a website made with Django, to App Engine + Cloud SQL + Cloud Storage. Right now, with the website being used only by me and a few friends, the daily costs are between 0,5-1 dollar. When releasing this i would like to keep the costs within the same range. Also, im still doing use of the free trial. I have like 170 dollars left for 69 days. Question Question 1: If i understand [this][1] correctly, while i don't upgrade my Cloud Billing Account, i won't get any charge to my card? Then it is completely safe to do a deploy while you are using your free credits. Is that right? Worst case scenario: I use all my free credits and my website goes down. I won't get any charge to my card. Current configuration - setup App Engine This is the app.yaml file used by my instance: runtime: python38 env: standard instance_class: F1 handlers: - url: /static/(.*) static_files: static/\1 require_matching_file: false upload: static/.* - url: /.* script: auto secure: always - url: .* script: auto env_variables: DJANGO_SETTINGS_MODULE: project.settings.prd automatic_scaling: min_idle_instances: automatic max_idle_instances: automatic min_pending_latency: automatic max_pending_latency: automatic min_instances: 1 max_instances: 1 network: {} Questions Within the automatic_scaling … -
I need to create html and android app button can run python script (image processing)
I am using framework django my input is only a image and output is the processed image (after using image processing) this is my html. It is ok but I have problem with android app code html Please help me !!! -
Unable to redirect to recently created detailview
I hope you're doing well. I am getting the below error when attempting to redirect to my newly created conversation detail page. The slug works perfectly when I type the url manually so it I think it has to do with the return reverse logic on the StartConversationView view. Please let me know of anything else I could try (I've tried what's commented below). Thanks so much. NoReverseMatch at /conversations/start/ Reverse for 'conversation_detail' with no arguments not found. 1 pattern(s) tried: ['conversations/(?P[-a-zA-Z0-9_]+)/$'] models.py class Conversation(models.Model): conversation = models.CharField(max_length=60, null=True, blank=False, unique=False) detail = models.CharField(max_length=600, null=True, blank=False, unique=False) slug = models.SlugField(max_length=80, null=True, blank=True) def __str__(self): return self.conversation def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.conversation+'-'+str(datetime.now().strftime("%Y-%m-%d-%H%M"))) super(Conversation, self).save(*args, **kwargs) def get_absolute_url(self): #return reverse('conversation_detail', args=[str(self.slug)]) return reverse('conversation_detail', kwargs={'slug': self.slug}) views.py class StartConversationView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): form = StartConversationForm() return render(request, 'conversations/start.html', {'form': form}) def post(self, request, *args, **kwargs): form = StartConversationForm(request.POST) if form.is_valid(): new_conversation = form.save(commit=False) new_conversation.starter = request.user new_conversation.save() messages.success(request, ('You have successfully started a new conversation.')) return redirect(reverse('conversation_detail'), slug=self.kwargs.get('slug')) #return redirect(reverse('conversation_detail'), kwargs = {'slug': self.slug }) #return redirect('conversation_detail'), self.slug=slug) #return HttpResponseRedirect(reverse('conversation_detail', kwargs={'slug': self.slug})) #return HttpResponseRedirect(reverse(self.get_absolute_url())) #return redirect('login') return render(request, 'conversations/start.html' , {'form': form}) class ConversationDetailView(LoginRequiredMixin, DetailView): … -
invalid literal for int() with base 10: b'permit_start'
I created model in Django.After added datefield to my model. models.py: ... date = models.DateField(blank=True, null=True, verbose_name="blablabla") But I got this error in admin panel. invalid literal for int() with base 10: b'date' -
ASGI errors when deploying Django project for production
how are you doing. I have an issue I hope can find a solution from experts. I want to deploy my django project and I used ASGI server I applied all steps from the official django website: https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ but it does not work I tried a lot of ways and solutions, but it all fails. BTW, I want to deploy the project on heroku hosting, it fails on heroku too. BTW, I did try some solutions from stackoverflow answers, but not worked. this is the output I get when trying to run the server using: Daphne Gunicorn Uvicorn Traceback (most recent call last): File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/uvicorn/workers.py", line 63, in init_process super(UvicornWorker, self).init_process() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ibrahim-pc/.local/share/virtualenvs/tests-IiD-aUH2/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/home/ibrahim-pc/.pyenv/versions/3.8.9/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File … -
Unable to Filter from database in DJango
this is my models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) this is my view.py def customer_dashboard(request,id): order = Order.objects.filter(customer=id) print(order) return render(request, 'accounts/customer_dashboard.html', {'user':user, 'customer':customer}) I tried to print the results,and I got this <QuerySet []> But I am very sure that the data is available in database, url is also working fine as other datas could be fetched -
How to delete file in minIO storage in Django?
I used the minIO storage in my Django app.I want to delete the object from DB and storage.What can I do? thanks in advance. this is my model: class FileStorage(models.Model): team = models.ForeignKey(Team, related_name = 'storage_team', null = True, on_delete = models.CASCADE) title = models.CharField(unique=True,max_length=255) video = models.FileField(verbose_name="Object Upload", storage=MinioBackend(bucket_name=priv_bucket), upload_to=iso_date_prefix) def __str__(self): return self.title -
How to save multiple objects from a script in django shell
Hello colleagues I would like to know if this list of objects can be saved from a script like the one I show, I want to execute it from the django shell python3 manage.py shell < script.py the following is my script from orders_management.models import Products objects = [ 'Products(name = "destornillador", section = "ferrreteria", price = 35)', 'Products(name = "balon", section = "deportes", price = 25)', 'Products(name = "raqueta", section = "deportes", price = 105)', 'Products(name = "muneca", section = "juguetes", price = 15)', 'Products(name = "tren electrico", section = "jugueteria", price = 135)', ] for object in objects: my_product = object my_product.save() the error it shows me File "<string>", line 15, in <module> AttributeError: 'str' object has no attribute 'save' -
How to make a Django return button point to the correct previous page?
I have a page (a.html) that the user may reach from different other pages in my Django application. And in this page there is a return button to return to the previous page. For instance: Page b.html contains a link to a view that presents a.html Page c.html contains a link to a view that presents a.html I need to implement a way of making the return button point to the correct view (b.html or c.html), depending on how it was reached. Fact 1: I can't simply put an action window.history.back(); because I need to reload the view it came from -
How to handle form with post method in Django?
I'm looking for a way to print my POST form using Django, my post form is multi-dimentional form: { first_name: '', last_name : '', email: '' } i'm sending my request using axios.post, just I want to know how can I handle the form on my backend(Django) i did request.POST['form']['email'] i got an error also i tried request.POST.get('form') and i got an error -
Django ORM queryset
I am learning about the Django ORM and how to make queries, Lets suppose i have two models class Company(models.Model): structure = IntegerField() class Customer(models.Model): created_at = DateTimeField(default=now) company = ForeignKey(Company) friend = BooleanField() I am writing a function where it can get all companies where their most recently created customer is friend=True. def get_companies_with_recent_friend(): """" Returns ------- `list(Company, ...)` """ raise NotImplementedError -
Django -- relation " " does not exist
There is some funny stuff going with my database. I am trying to create a new model but I get this error when trying to load the page: ProgrammingError at /posts/ relation "new_sites_topichome2" does not exist LINE 1: ...te_added", "new_sites_topichome2"."owner_id" FROM "new_sites... Here is the models.py class TopicHome2(models.Model): title = models.CharField(max_length = 200) text = models.TextField() image = models.ImageField(upload_to = 'image/set/', null = True, blank = True) urllink = models.CharField(max_length=5000, null = True, blank = True) date_added = models.DateTimeField(auto_now_add = True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title[:50] forms.py class TopicHomeForm2(forms.ModelForm): class Meta: model = TopicHome2 fields =['title', 'text', 'image','urllink'] def __init__(self, *args, **kwargs): super(TopicHomeForm2, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['placeholder'] = 'Enter title here' self.fields['text'].widget.attrs['placeholder'] = 'Enter text here' views.py def new_topichome2(request): if request.method == "POST": form = TopicHomeForm2(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit = False) new_post.owner = request.user new_post.save() form.save() return redirect('new_sites:index') else: form = TopicHomeForm2() context = {'form':form} return render(request, 'new_sites/new_topichome2.html', context) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I am using heroku and AWS buckets for static files. Is it possible that my database is actually stored in the AWS RDS? I have a model called Books which has many entries/objects … -
Django selected radio button giving only a single value (on) in view.py
I have 4 radio buttons indicating 4 answers for a particular question. How do I get the selected one to store in the boolean field of my model? With the current method, I get only the value on Thank you for your kind help html file for the js script part (Questions are added dynamically) for (var i = 1; i <= num_of_qu; i++) { html += `<div class="row"><div class="form-row"><div class="form-group col-md-6"> <label>Name of question</label><input type="text" class="form-control" name="question_text_${i}" id="question_${i}" placeholder="Question"></div></div></div>`; for (j = 1; j <= 4; j++) { //4 answers html += `<div class="row"> <div class="form-row"> <div class="form-group col-md-4"> <input type="text" class="form-control" name="question_${i}_answer_${j}" id="question_${i}_answer_${j}" placeholder="Answer" ><input type="radio" name="radio_question_${i}_answer" id="radio_question_${i}_answer_${j}" > </div> </div> </div>` views.py def add_test(request, pid): if request.method == 'POST': //i retrieved the variables here try: with transaction.atomic(): test = PsychometricTest.objects.create(internship=internship, name=test_name, description=test_description, number_of_questions=test_num_questions, time=test_duration, threshold=test_threshold, difficulty=test_diff_level, created=date.today(), scheduled_date_time=test_datetime) for i in range(1, int(q_num)+1): //ISSUE IS BELOW radio_check = request.POST.get('radio_question_{}_answer'.format(i)) print(radio_check) question = Question.objects.create(text=request.POST['question_text_{}'.format( i)], psychometric_test=test, created=date.today()) radio_check = request.POST.get( 'radio_question_{}_answer'.format(i)) for j in range(1,5): answer = Answer.objects.create(text=request.POST['question_{}_answer_{}'.format( i, j)], question=question, created=date.today()) for choice in radio_check: if (choice.checked): answer.correct = True answer.save() messages.success(request, "Psychometric test added") return redirect('view_internship') except Exception as e: print(e) messages.error(request, "An error happened!") return … -
How to give labels and title to plotly visuals in django website?
How to give labels and title to plotly visuals in django website? Purpose: Want to show interactive line plot in Django website with labels. views.py from django.shortcuts import render from plotly.offline import plot from plotly.graph_objs import Scatter def index(request): x_data = [0,1,2,3] y_data = [x**2 for x in x_data] plot_div = plot([Scatter(x=x_data, y=y_data, mode='lines', name='test', opacity=0.8, marker_color='green')], output_type='div') return render(request, "index.html", context={'plot_div': plot_div}) index.html <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test</title> </head> <body> {% autoescape off %} {{ plot_div }} {% endautoescape %} </body> </html> -
How to get data from Database with a range?
So i want to make a range from a specific date to current date. I make like this: context_data['newNotifications'] = Notification.objects.filter( emailStudent=request.user).filter(time=request.user.viewedNotifications).count() But i want from request.user.viewedNotifications to current date and hour. -
Django API permission decorator
Objective: I want to allow some endpoint only to users with specifics permission. For exemple to call the endpoint that allow the creation of users you need the permission "user.create" Problem: I tried to create a middle ware to use it with decorator_from_middleware_with_args class PermissionMiddleware: def __init__(self, view,permission): self.permission = permission def process_request(self, request): if not request.user.has_perm(permission_name): if raise_exception: raise exceptions.PermissionDenied("Don't have permission") return False return True Then inside my views i use the decorator_from_middleware_with_args class UtilisateurViewSet(viewsets.ViewSet): permission = decorator_from_middleware_with_args(PermissionMiddleware) @permission('view_utilisateur') def list(self, request): queryset = Utilisateur.objects.all() serializer = UtilisateurSerializer(queryset, many=True) return Response(serializer.data) But there is an error when i call the endpoint: AttributeError: 'UtilisateurViewSet' object has no attribute 'user' I think it's because the django.contrib.sessions.middleware.SessionMiddleware is not executed yet. Is there a way to define the order of the middlewares, or an other way to achieve what a want ? -
Celery Django Body Encoding
Hi does anyone know how the body of a celery json is encoded before it is entered in the queue cache (i use Redis in my case). {'body': 'W1sic2hhd25AdWJ4LnBoIiwge31dLCB7fSwgeyJjYWxsYmFja3MiOiBudWxsLCAiZXJyYmFja3MiOiBudWxsLCAiY2hhaW4iOiBudWxsLCAiY2hvcmQiOiBudWxsfV0=', 'content-encoding': 'utf-8', 'content-type': 'application/json', 'headers': {'lang': 'py', 'task': 'export_users', 'id': '6e506f75-628e-4aa1-9703-c0185c8b3aaa', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '6e506f75-628e-4aa1-9703-c0185c8b3aaa', 'parent_id': None, 'argsrepr': "('<email@example.com>', {})", 'kwargsrepr': '{}', 'origin': 'gen187209@ubuntu'}, 'properties': {'correlation_id': '6e506f75-628e-4aa1-9703-c0185c8b3aaa', 'reply_to': '403f7314-384a-30a3-a518-65911b7cba5c', 'delivery_mode': 2, 'delivery_info': {'exchange': '', 'routing_key': 'celery'}, 'priority': 0, 'body_encoding': 'base64', 'delivery_tag': 'dad6b5d3-c667-473e-a62c-0881a7349684'}} -
Rewriting windowing raw sql into django ORM
I have raw query, which I need to rewrite into django ORM. Lets say we have model like this: class exampleModel(models.Model): value1 = models.BigIntegerField(primary_key=True) value2 = models.CharField(max_length=255, blank=True, null=True) value3 = models.CharField(max_length=255, blank=True, null=True) value4 = models.CharField(max_length=255, blank=True, null=True) I want to compare filter of this model with number of occurences of primary key named value1 in other tables, is there any way to do it in django orm? Here is raw query I have as an example, I need to rewrite it into ORM. Thank you raw_query=f"SELECT value1,value2,value3,value4 (SELECT COUNT(*) FROM exampleTable2 l WHERE o.value1 = l.value1) AS count_occurences_table2, (SELECT COUNT(*) FROM exampleTable3 l WHERE o.value1 = l.value1 ) AS count_occurences_table3, FROM exampleModel o WHERE name LIKE '%example%' OR address LIKE '%example%'" Essentially what it does is that it writes back parameters from first table and checks for primary key occurence in other tables and sends back count of these occurences in other tables of each line in exampleTable.. -
Django: How to display Multiple Models in a single view through function approach?
what I want to execute that all my three models will be displayed through one view by a function approach. The fields I want to display in All fields of Cylinder Entry ,issue date(if exists) ,userName,Return date(if exists) (of that particular cylinderId) Eg: cylinderId | date | type | status |availability| issuedate | userName | returndate | 1 11/11 co2 fill available 12/11(if exists) xyz 13/11(if exists) Sorry for this messy table. but unable to write the logic please help me out here is my models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) super().save(*args,**kwargs) def __str__(self): return str(self.userName) class ReturnCylinder(models.Model): fill=[ ('Fill','fill'), ('Empty','empty'), ('refill','Refill') ] ava=[ ('yes','YES'), ('no','NO') ] cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE,unique=True) user_return=models.ForeignKey('IssueCylinder',on_delete=models.CASCADE) returnDate=models.DateTimeField(default=timezone.now) status=models.CharField(max_length=10,choices=fill) availability=models.CharField(max_length=20,choices=ava) def save(self,*args,**kwargs): if not self.pk: if self.availability=='YES' or self.availability=='yes': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Available') else: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Unavailable') if self.status=='refill' or self.status=='Refill': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Refill') super().save(*args,**kwargs) def __str__(self): return self.cylinder -
Why is it called signals.py and not receivers.py in Django?
I am aware that Django itself has not defined any guideline about where should the signal receivers live inside an app. But, in the online community, I have seen a general practice (Based on stackoverflow answers and various tutorials) to define a signals.py inside the app direcotry. What confuses me is that why should it be called signals.py and not receivers.py as we are defining receivers/listners there not signals. Please help me understand. -
Passing Django logged-in user information to Dash app
Is possible to pass the currently logged in user full name/group etc. into a Dash app created in Django? Assume you have a simple Dash table integrated into Django: import dash from dash.dependencies import Input, Output, State import dash_table import dash_core_components as dcc import dash_html_components as html import pandas as pd from django_plotly_dash import DjangoDash df = pd.read_csv('...') app = dash.Dash(__name__) app.layout = dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), ) if __name__ == '__main__': app.run_server(debug=True) [...] and assume you for instance want to pass the logged in name into the data table. How can this be done? For example, "name = request.user.get_full_name" or some type of similar statement does not work (of my knowledge). Thanks! -
Hello guys so when i clikc on django title i get django post and when i click on javascript title i get django post ether
when i clikc on django title i get django post and when i click on javascript title i get django post ether am not using any frame_work and this my blog page i really try every solution i know but Unfortunately nothing happend blog.html {% for blog in blogs %} <div class="col-xl-12 col-md-6 col-xs-12 blog"> <div class="right-text-content"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> <h2 class="sub-heading">{{blog.title|title}}</h2> </button> <!-- Modal --> <div class="modal fade align-self-end mr-3 " id="myModal" tabindex="1" role="dialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">{{blog.title|title}}</h5> <h6 class="float-right">{{blog.created_at}}</h6> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{blog.content|linebreaks}} </div> <div class="modal-footer"> <h5>Created by {{blog.name}}</h5> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <p> <br> <a rel="nofollow noopener" href="{{blog.name_url}}" target="_parent">{{blog.name}}</a> <br> {{blog.content|linebreaks}} </p> {{blog.created_at}} </div> </div> {% endfor %} views.py from django.shortcuts import render from .models import DigitalTeam, Blog def index(request): pers = DigitalTeam.objects.all() return render(request, 'index.html', {'pers':pers}) def blog(request): pers = DigitalTeam.objects.all() blogs = Blog.objects.all() return render(request, 'blog.html', {'pers':pers, 'blogs':blogs}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('blog', views.blog, name='blog'), ] So guys what am i missing -
In Django after loading {{form.media}} javascripts in the page stop working
I am trying to use the django-map-widgets in my project. However, after I load the map using {{location.media}} {{location.as_p}} , even though the map loads fine, the other javascript codes in the page stop working. For example the "logout link" which uses a javascript script: The Django form: class LocationDetails(forms.ModelForm): class Meta: model = Provider fields = ['location'] widgets = { 'lage': GoogleStaticOverlayMapWidget(zoom=12, thumbnail_size='50x50', size='640x640'), } The rendered HTML code <!DOCTYPE html> <html lang="en-US" dir="ltr"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Document Title ============================================= --> <title> Ihr Dashboard </title> <!-- Favicons ============================================= --> <link rel="apple-touch-icon" sizes="57x57" href="/static/assets/images/favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/static/assets/images/favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/assets/images/favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/static/assets/images/favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/assets/images/favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/static/assets/images/favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/assets/images/favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/static/assets/images/favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/static/assets/images/favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/static/assets/images/favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/static/assets/images/favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/static/assets/images/favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/static/assets/images/favicons/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/static/assets/images/favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!-- Stylesheets ============================================= --> <!-- Default stylesheets--> <link href="/static/assets/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Template specific stylesheets--> <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Volkhov:400i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet"> <link href="/static/assets/lib/animate.css/animate.css" rel="stylesheet"> <link href="/static/assets/lib/components-font-awesome/css/font-awesome.min.css" rel="stylesheet"> <link href="/static/assets/lib/et-line-font/et-line-font.css" rel="stylesheet"> <link href="/static/assets/lib/flexslider/flexslider.css" … -
Categorise using foreign key in django
i want to display the names of product having a particular foreign key at a time my models.py: from django.db import models class Company(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='comapny') name = models.CharField(max_length=200) def __str__(self): return self.name i want it to display company names as list heading followed by list of all products of that particular company but dont know how to filter it like that and display on html my views.py: class Hydraulic(ListView): template_name = 'hydraulics.HTML' context_object_name = 'hydraulic' model = models.Product can someone tell me how i can filter it for name of foreignkey and inject it in HTML THANKS -
What are differences between mixins and utils in programming?
As I have seen these two concepts in different programming languages like python, dart. Sometimes I mixed up these two as one thing. are these two are similar or different?