Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass multiple admin class with iterable in django admin
from django.contrib import admin from .models import Post, Comment, DataTracking myModels = [Comment, DataTracking] @admin.register(myModels, safe=True) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'created_on', 'active') list_filter = ('active', 'created_on') search_fields = ('name', 'email', 'body') actions = ['approve_comments'] def approve_comments(self, request, queryset): queryset.update(active=True) class DataTrackingAdmin(admin.ModelAdmin): list_display = ('blogtitle','country','viewcount') list_filter = ('blogtitle','country') search_fields = ('blogtitle','country','viewcount') class PostAdmin(admin.ModelAdmin): class Media: js=("injectjs.js",) list_display = ('title', 'slug', 'status','created_on') list_filter = ("status",) search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Post, PostAdmin) i am trying to this i want to register newly added DataTracking model with admin i tried passing both as seprate list admin class and itrables to admin register it gives me error -
AttributeError: module 'django.db.models' has no attribute 'ForeingKey'
Hi Guys: I´m new in Python. I'm having this error: AttributeError: module 'django.db.models' has no attribute 'ForeingKey' this is my code: from django.db import models from aplicaciones.adopcion.models import PersonaM class Vacuna(models.Model): nombre = models.CharField(max_length=50) class Mascota(models.Model): folio = models.CharField(max_length=10, primary_key=True) nombre = models.CharField(max_length=50) sexo = models.CharField(max_length=10) edad_aproximada = models.IntegerField() fecha_rescate = models.DateField() persona = models.ForeingKey(PersonaM, null=True, blank=True, on_delete=CASCADE) vacuna = models.ManyToManyField(Vacuna) Can anyone help me? Thks you all -
django heroku 1 year free vs heroku + AWS RDS 1 year?
i finich my django app and i want to deploy my app on heroku a want test it for 1 year i need free 1 year i now the limit for heroku free and its ok for me , only the limit 10000 row in database i want to avoid this limit by sit my database on AWS RDS so i can entre more than 10k row in database any one try this before and its easy or hard to conect database with heroku and the confing AWS RDS sit on setting.py or in heroku setting -
Save and duplicate an instance in django
I have to define a function in order to duplicate an instance of my class Scenario. I created an identically instance whose fields are identically except 'name' and 'id', but when I save the new instance the original is deleted. For example if I want to duplicate the scenario called s1 and to create the scenario s_dup_s1, and if I reproduce all lines of my duplicate function, then after I write s_dup_s1.save() the old instance s1 is deleted. What can I do if I want s1 and s1_sup_s1 at the same time? -
Set value for options in render_field, django-widget-tweaks
I have a render_field in my webpage which renders a "select" tag. I want to set the set the value of each option as they get rendered as indexes (1,2,3...) by default. This is my render_field. {% render_field form.type|append_attr:"oninput:this.className = ''"|append_attr:"onchange:update_make(this.options[this.selectedIndex])" class="form-control input-field" %} -
how to handle exception inside django middleware
What if middleware itself throw an error (for example some timeout error), how can I make this exception be handled by other middlewares with defined process_exception method? Do I need to throw some special django exception or return specific response? -
How to make a password access page with django model
I want to create access page for every groups in my models. this is my models.py file class TournamentGroup(models.Model): group_name = models.CharField(max_length=256, null=True) tournament_name = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) group_password = models.CharField(max_length=6, null=True) def __str__(self): return self.group_name class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) def __str__(self): return self.tournament_name and this is my views.py file def group_auth(request, pk): model = get_object_or_404(TournamentGroup, pk=pk) password = TournamentGroup.objects.filter(group_password=model) form = TournamentPassword() if request.method == "POST": form = TournamentPassword(request.POST) if form.is_valid(): accept = form.cleaned_data['password'] if accept == password: return redirect('ksm_app:groups') else: return HttpResponse("Hasło nieprawidłowe") return render(request, 'ksm_app2/allowed2.html', {'form': form}) I would like to create it in such a form that admin creates a tournament and assigns groups to it, each group has its own separate access code. I'm asking someone who can help me if I'm going in the right direction because now after going to the page where the user is asked for a password and after entering the page refreshes but nothing concrete happens. I would appreciate any hint -
Filter python list inside queryset
Django framework is being used. There is a model with many-to-many field. class Item(models.Model): special_category_id = models.CharField(max_length=100) categories = models.ManyToManyField(Category) and a list of category ids ids=[1, 2, 3] I need to check if at least one of categories is in ids. The problem is that special_category_id is in categories table and I need to exclude special_category_id from ids. The code bellow works, but it checks the special_category_id value too. queryset = queryset.annotate( categories_are_in_list=Case( When( Q(categories__id__in=ids), then=Value(1) ), default=Value(0), output_field=IntegerField(), ), Is it possible? -
django.db.utils.IntegrityError: Problem installing fixture UNIQUE constraint failed: users_profile.user_id
I have been trying to migrate from the default sqlite database in Django over to Postgres, and am running into problems moving the data from one to the other on my remote host. I am currently following this guide, and I have done the following: created a new postgres database, added it to my settings.py, installed psycopg2, created tables in the new database, and exported data from the old database. When I try to load the data: python manage.py loaddata alldata.json --database=pgsql I get the following error: django.db.utils.IntegrityError: Problem installing fixture '/home/amatlin/squishy/alldata.json': Could not load auth.User(pk=1): UNIQUE constraint failed: users_profile.user_id Below is the code for my file users/models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' I have also checked the contents of the users_profile table as follows: $ python manage.py dbshell SQLite version 3.31.1 2020-01-27 19:55:54 sqlite> select * from users_profile; id|image|user_id 1|profile_pics/strawberry.gif|1 Therefore there are no duplicate user_id values in the users_profile table. The postgres DB currently has the database structure of the sqlite DB because I migrated it up to the place where the sqlite DB is. … -
Serializer Multiple Models
class SupplierPO(models.Model): enterpriseId = models.IntegerField(null=True, blank=True) supplierId = models.IntegerField(null=True, blank=True) date = models.DateTimeField(null=True, blank=True) refNo = models.CharField(max_length=30,blank=True,null=True) billNo = models.CharField(max_length=30, null=True, blank=True) amount = models.FloatField(null=True, blank=True) deliveryStatus = models.CharField(max_length=20, null=True, blank=True) paymentStatus = models.CharField(max_length=20, null=True, blank=True) paymentMode = models.CharField(max_length=30,blank=True,null=True) balance = models.CharField(max_length=30,blank=True,null=True) totalQty = models.CharField(max_length=30,blank=True,null=True) noOfProducts = models.CharField(max_length=30,blank=True,null=True) deliveryDate = models.DateField(max_length=20,blank=True,null=True) receivedBy = models.CharField(max_length=20,blank=True,null=True) is_deleted = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.CharField(max_length=200, null=True, blank=True) updated_by = models.CharField(max_length=50, null=True, blank=True) class SupplierPOItems(models.Model): supplierPoId = models.ForeignKey(SupplierPO,on_delete=models.CASCADE, blank=True, null=True) productId = models.ForeignKey(ProductsEnterprise,on_delete=models.CASCADE, blank=True, null=True) warehouseId = models.ForeignKey(Warehouse, on_delete=models.CASCADE, blank=True, null=True) amount = models.CharField(max_length=30,blank=True,null=True) gstin = models.CharField(max_length=100, null=True, blank=True) mrp = models.CharField(max_length=30,blank=True,null=True) discount = models.CharField(max_length=30,blank=True,null=True) qty = models.CharField(max_length=30,blank=True,null=True) hsnNo = models.CharField(max_length=100,null=True, blank=True) gstRate = models.CharField(max_length=100, null=True, blank=True) sku = models.CharField(max_length=100, null=True, blank=True) upcNo = models.CharField(max_length=100, null=True, blank=True) is_deleted = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.CharField(max_length=200, null=True, blank=True) updated_by = models.CharField(max_length=50, null=True, blank=True) class SupplierPOViewSet(ModelViewSet): permission_classes = [IsAuthenticated,] queryset = SupplierPO.objects.filter(is_deleted=False).order_by('id') serializer_class = SupplierPOSerializer def list(self, request, *args, **kwargs): response = {'status_code': 200} try: queryset = SupplierPO.objects.filter(is_deleted=False).filter(enterpriseId=request.data.get('enterpriseId')).order_by('id') serializer = SupplierPOSerializer(queryset, many=True) response.update({ 'status': CommonResponse.STATUS_SUCCESS, 'message': "Supplier fetched successfully", 'data': serializer.data }) except Exception as e: response.update({ 'status_code': 204, 'message': str(e) }) … -
DateTimePicker in Django-Filters
since a few days I try to figure out how to use a DateTimePicker in my Django Project in Django 3.x. I found django-datetimepicker but its not working since in 3.0 the attribute renderer was removed and none of the solutions worked for me. My model.py class Log(models.Model): timestamp = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=30) project = models.CharField(max_length=30) status = models.PositiveIntegerField() def __str__(self): return str(self.timestamp) + " / " + self.name + " / " + str(self.status) The Table is filled from a generator and I get for each timestamp about 100 entries. my filter.py looks like this: class LogFilter(django_filters.FilterSet): project = django_filters.MultipleChoiceFilter(choices=get_choices(Log, 'project'), label='Project', field_name='project') name = django_filters.MultipleChoiceFilter(choices=get_choices(Log, 'name'), label= 'Name', field_name='name') date_range = django_filters.DateFromToRangeFilter( lookup_expr=('regex'), widget=django_filters.widgets.RangeWidget( attrs={ 'type':'date' } ), label='Date Range', field_name='timestamp' ) These filters do their job but the DateFromToRangeFilter just accepts 'date' as a datepicker object. I didn't find a solution yet to also pick a timerange. views.py def log_view(request,filterdict): obj = Log.objects.filter(**filterdict) context = { 'object' : obj, 'filter' : LogFilter(request.GET, queryset=Log.objects.all()), } return render(request, "widgets/tables/log_table.html", context) Btw: I'm using django-filters, because I want to safe the filter in the url. Thanks for helping. -
PYTHON CONVERT INT into PHONE NUMBER
I'm trying to import an excel file into my django project and create a Client object with the excel's data. this is my Client model: class Client(models.Model): client = models.CharField(max_length=255, null=False) name = models.CharField(max_length=255, blank=True, null=True) surname = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = PhoneNumberField(blank=True, null=True) i implemented this function to import the file: import phonenumbers def import_proj_excel(request): if request.method == 'POST': client_resource = ClientResource() dataset = Dataset() file = request.FILES['prog-file'] if not file.name.endswith('xlsx'): messages.info(request, 'invalid format') return render(request, 'excel.html') imported_data = dataset.load(file.read(), format='xlsx') for data in imported_data: if data[1] is None or data[2] is None or data[3] is None or data[4] is None or data[4] is None or data[5] is None: d1 = data[1] d2 = data[2] d3 = data[3] d4 = data[4] d5 = data[5] if d1 is None: d1 = "" elif d2 is None: d2 = "" elif d3 is None: d3 = "" elif d4 is None: d4 = "" elif d5 is None: d5 = str(data[5]) d5 = "" value = Cliente( data[0], d1, d2, d3, d4, d5, ) else: phone = phonemubers(data[5]) print(type(phone)) value = Client( data[0], data[1], data[2], data[3], data[4], phone, ) value.save() return render(request, 'excel.html') data[0] is the … -
how to display checkbox multi-select in django
if I select all checkbox then my checkbox display only one thing i want display multi select checkbox in django. what is problem in my code? in html <form action="" method="GET"> <label style="color: gray;" >&nbsp; 확장자 -</label> {% for extention in file_extention %} {% if extention.name == extention_name %} <input type="checkbox" name="extention_name" value="{{ extention.name }}" checked>{{ extention.name }} {% else %} <input type="checkbox" name="extention_name" value="{{ extention.name }}"> {{ extention.name }} {% endif %} {% endfor %} </form> in views.py if request.method == 'GET': png = {'name' : '.png'} jpg = {'name' : '.jpg'} gif = {'name' : '.gif'} file_extention = [png, jpg, gif] context = {} context['file_extention'] = file_extention extention_name = request.GET.get('extention_name',None) context['extention_name'] = extention_name return render(request, 'home/index.html',context)``` -
django model order the queryset with booleanfield field True/False
i have tow model as the following , first one is a user profile, which have a FK to User model : class Profile(models.Model): PRF_user = models.OneToOneField(User, related_name='related_PRF_user', on_delete=models.CASCADE) PRF_Priority_Support = models.BooleanField(default=False) and the second is ticket model which have a FK to User model : class ticket(models.Model): ticket_status_options = [ ('open', 'open'), ('wait_customer_reply', 'wait_customer_reply'), ('replied_by_staff', 'replied_by_staff'), ('replied_by_customer', 'replied_by_customer'), ('solved', 'solved'), ] TKT_USER = models.ForeignKey(User, related_name='TKT_USER', on_delete=models.CASCADE) TKT_DEB = models.ForeignKey('Site_departments', related_name='related_ticket_department', on_delete=models.CASCADE) TKT_SUB = models.CharField(max_length=50, db_index=True, verbose_name="ticket subject") TKT_BOD = models.TextField(verbose_name="ticket body") TKT_image_attachment = models.ImageField(upload_to='TKT_img_attachment', blank=True, null=True , default=None) TKT_CREATED_DATE = models.DateTimeField(auto_now_add=True) TKT_UPDATED_DATE = models.DateTimeField(auto_now=True) i want to sort the tickets based on user profile Priority_Support , if the user profile PRF_Priority_Support is True , i want to sort it first , if False sort it normal . kindly help -
CheckConstraint throwing a Pylint 'undefined variable F' error
I'm not sure if I need to import a particular module, I've had a look round and can't seem to find one? Pylint is showing an "Undefined Variable 'F' " error on both of the CheckConstraints. from django.contrib.auth.models import AbstractUser from django.db.models.fields import DateTimeField from django.db.models.query_utils import Q from django.utils import timezone from django.db import models class UserProfile(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="profileUser") user_following = models.ForeignKey("User", on_delete=models.CASCADE, related_name="following") user_follower = models.ForeignKey("User", on_delete=models.CASCADE, related_name="followers") class Meta: constraints = [ models.CheckConstraint(check=~Q(user=F('user_following', 'user_follower')), name="user_cannot_follow_themselves"), models.CheckConstraint(check=~Q(user_following=F('user_follower')), name="cannot_follow_and_be_following") ] -
Relative paths in django-meta module and twitter card config
I've tried to follow instructions of the django-meta module, everything works fine in absolute paths, using the view config in my project. from meta.views import MetadataMixin class MyView(MetadataMixin, View): title = 'Some page' description = 'This is an awesome page' image = 'img/some_page_thumb.gif' url = 'some/page/' ... and the configs in settings: META_USE_OG_PROPERTIES = True META_USE_TWITTER_PROPERTIES = True META_SITE_TYPE META_SITE_PROTOCOL = 'https' ... My problem is that I can't render in views the dynamic paths for image of my blog, etc... and also can't configure the twitter card ("twitter_type"). Any ideas would be appreciated -
Django webpage only shows a 0
When ever I start the the server it does start up the server. But when I open the page it just shows a 0 instead of the normal Django landing page. Ive tried opening the login page they provide but it still just shows a 0 Version: 2.0.2 -
Detect dead code which never gets executed
I am searching for code coverage, but not for tests, but for production code. Which lines of my code get executed often, and which lines gets executed hardly or never (in production)? Of course this measuring must not slow down the production system noticably. Is there a way to do this? To simplify this, I want to use this for our Python (Django) code first. How could get a code coverage from production code? -
Using AJAX with CBV in Django for posting without refreshing
I wanna upgrade my creating post functionality just to make new posts without refreshing the page. Example, which I found, uses function views as example, but I use class-based views in my own project. So i faced with problem of adapting example codes to my code. Currently by submitting the form new for new post appears but it doesn't save data to DB and in my .js file i try to prepend() some code to this div and call some variables from json, but all that i get - "undefined" in each call. As I understand the most of mistakes exist in views.py, but can't analize correctly. my .html template: {% block post_content %} <div class="post-form"> <form action="{% url 'posts:create' %}" method="POST" enctype="multipart/form-data" id='post-form'> {% csrf_token %} <textarea id='post-text' type="text" name='post_message' rows="8"></textarea><br> <input id='post-image' type="file" name="post_image" accept="image/*"><br> <input id='post-submit' type="submit" value="Post"> </form> </div> {% endblock %} {% block post_post %} <div class="post-container" > <div class="current-post-container" id='talk'> {% for post in post_list %} {% include 'posts/_post.html'%} {% endfor %} </div> </div> <script src='https://code.jquery.com/jquery-3.5.1.min.js'></script> <script src="https://d3js.org/d3.v6.min.js"></script> <script src="{% static 'simplesocial/js/main.js' %}"></script> {% endblock %} main.js: // Submit post on submit $('#post-form').on('submit', function(event){ event.preventDefault(); create_post(); }); // AJAX for posting function create_post() { … -
How to send normal JSON message from outside of consumer class in django channels
I am not using this Django channels for chat purpose, I am connecting the user through web socket via DRF AUTH token var ws = new WebSocket("ws://127.0.0.1:8008/ws/stream/<token>/") I want to achieve if the admin delete the User from backend then in mobile front end I will get the automatically response that user is deleted and then I will call the disconnect method, which will logout the user in front end for that below code I am using. But unable to send message from outside of consumer. Here below is my code:- class Consumer(AsyncJsonWebsocketConsumer): """ This chat consumer handles websocket connections for chat clients. It uses AsyncJsonWebsocketConsumer, which means all the handling functions must be async functions, and any sync work (like ORM access) has to be behind database_sync_to_async or sync_to_async. For more, read http://channels.readthedocs.io/en/latest/topics/consumers.html """ ##### WebSocket event handlers async def connect(self): """ Called when the websocket is handshaking as part of initial connection. """ # query_string = dict(self.scope).get('query_string') # keys = dict(parse.parse_qs(query_string.decode())) self.token_key = self.scope['url_route']['kwargs']['token'] try: if self.token_key: # access_token = keys.get('key') print(self.token_key) self.scope['user'] = await get_user(self.token_key) # self.chat_room = self.scope['url_route']['kwargs']['channel'] await self.accept() await self.send_json({'code':200, 'message': 'Connection establish successfully', 'error_message': '', 'data':{}}) except Exception as ex: print("Exception", ex) self.scope['user'] … -
When I do submit formset in Django why do it returns extra 5 fields in formset?
When I do submit formset in Django it returns extra 5 fields in formset. Suppose the initial queryset has 3 dictionary values. But when I do submit the formset its returns an extra 5 dictionary. Why? My form.py: class SbTitleForm(forms.Form): sb_title = forms.CharField(required=False) sb_permission = forms.BooleanField(required=False) SbTitleFormSet = formset_factory(SbTitleForm, extra=0) My view.py: def menuuser(request): sbtitle = SbTitle.objects.all().values() sbtitle_form = SbTitleFormSet(initial=sbtitle) if request.method == 'POST': sbtitle_form = SbTitleFormSet(request.POST, initial=sbtitle) if sbtitle_form.is_valid(): print(sbtitle_form.cleaned_data) context = { 'sbtitle_form':sbtitle_form, } return render(request, 'admins/user_role/user_permission.html', context) My HTML: {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} {{ sbtitle_form.management_form }} {{ sbitleelement_form.management_form }} <div id="DataTables_Table_2_wrapper" class="dataTables_wrapper no-footer"> <div class="datatable-scroll"> <table class="table table-bordered table-hover datatable-highlight dataTable no-footer" id="DataTables_Table_2" role="grid" aria-describedby="DataTables_Table_2_info"> <thead> <tr role="row" class="bg-teal-400"> <th class="sorting text-center h5" tabindex="0" aria-controls="DataTables_Table_2" rowspan="1" colspan="1" aria-label="Job Title: activate to sort column ascending">Sidebar Title</th> </tr> </thead> <tbody> {% for field in sbtitle_form %} <tr role="row" class="odd"> <td class="sorting_1 text-center"><h4>{{ field.sb_title.value }} {{ field.sb_permission }}<p class="text-danger">{{ field.errors.as_text }}</p></h4></td> {% endfor %} </tbody> </table> </div> <div class="card-footer"> <button class="btn btn-lg btn-primary" type="submit">Save</button> </div> </div> </form> </div> {% endblock %} when I try to print(sbtitle_form.cleaned_data) its return extra 5 field values like … -
Django inlineformset - jQuery add row
Hello I am trying to upload multiple images to the web via inlineformset. The inlineformset is working fine, but if I add feature to add more lines to upload the image, it upload only the original images and it does not upload the images which were added via jQuery Add row. I am not sure why it wont take it... Models.py class PostImage(models.Model): post = models.ForeignKey( Post, default=None, on_delete=models.CASCADE, related_name='postimages') class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) Views.py class PostCreateView(LoginRequiredMixin, CreateView): form_class = CreatePostForm template_name = 'blog/post_form.html' def get_context_data(self, *args, **kwargs): context = super(PostCreateView, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = PostImageFormSet(self.request.POST, self.request.FILES, instance=self.object) else: context['formset'] = PostImageFormSet() return context def form_valid(request): ---- template <form id="myForm" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form2 in formset.forms %} <div class="table"> <table class="no_error"> {{ form2|crispy }} </table> </div> <hr> {% endfor %} </fieldset> <div class="form-group"> <input class="btn btn btn-outline-primary btn-sm" type="button" value="Add Row" id="add_more"> <button class="btn btn-outline-info float-right" type="submit">Post</button> </div> </form> jQuery script: <script> $('#add_more').click(function() { cloneMore('div.table:last', 'service'); }); </script> <script> function cloneMore(selector, type) { var newElement = $(selector).clone(true); var total = $("#id_" + type + "-TOTAL_FORMS").val(); newElement.find(":input").each(function () { var name = $(this) .attr("name") .replace("-" + (total - … -
Django: How to add context variable as src to url?
I have a django model with a field for an external URL image_url = models.URLField(max_length=250) I want to then display an image associated with that image_url (say https://upload.wikimedia.org/wikipedia/commons/0/01/Pocky-Sticks.jpg) in an html img element like so <img src=image_url alt="didn't find image"> where i have passed image_url in as a context variable. When I try the naive method of just passing in a context variable <img src= "{{ model.image_url }}" alt="didn't find image"> I can never find the image. I have looked around and most answers for similar questions are related to loading an image from static (e.g. How to add django template variable in <img src>?. ) These haven't been helpful because I want to load an image from a path completely external to my app. Any ideas on how to pass in a context variable to src in this case? -
How does "template.Library()" and "get_related_name" work in django?
I'm working on a basic social media django project with the help of an udemy course. The following are the models i created: group : models.py register = template.Library() class Group(models.Model): name = models.CharField(max_length=255,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True,default='') description_html = models.TextField(editable=False,default='',blank=True) members = models.ManyToManyField(User,through="GroupMember") class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE) post : models.py class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True) And the part that does not make any sense to me is the following: post_list.html {% for member_group in get_user_groups %} <a href="{% url 'groups:single' slug=member_group.group.slug %}">{{ member_group.group.name }}</a></li> {% endfor %} {% for other_group in get_other_groups %} <a href="{% url 'groups:single' slug=other_group.slug %}">{{ other_group.name }}</a></li> {% endfor %} What does "get_user_groups","get_other_groups" and "register = template.Library()" mean here and how are they related? Also what are they trying to achieve here? I'm clueless guys, help me out. -
'Command errored out with exit status 1' getting this error message while installing mysql client in python
(env) C:\Users\shreya kumar\Documents\django website\audit_website>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\shreya kumar\documents\django website\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\shreya kumar\AppData\Local\Temp\pip-record-npl_lx21\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\shreya kumar\documents\django website\env\include\site\python3.9\mysqlclient' cwd: C:\Users\shreya kumar\AppData\Local\Temp\pip-install-7l4hf6a3\mysqlclient\ Complete output (23 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.9\MySQLdb creating build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.9\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\shreya kumar\documents\django website\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record …