Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vue Js and Django get fields from ForeignKey Objects
I am using Django Rest Framework with Vue JS and currently unable to get the foreignkey fields from the actual model of the api. I want to be able to get the store name of a particular product. Whenever I try to call [[ product.store.name ]] in my vue template it returns nothing. Also my href does not return the slug of a store. This could be an easy fix, but I am hopeful to get a solution. Below is my code, thanks. models.py class Store(models.Model): owner = models.ForeignKey("account.Profile", null=True, on_delete=models.SET_NULL) category = models.ForeignKey("store.Category", null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=30, unique=True) slug = AutoSlugField(populate_from='name', unique=True, editable=True) description = models.CharField(max_length=255, blank=True) def __str__(self): return str(self.id) class Product(models.Model): store = models.ForeignKey("store.Store", null=True, on_delete=models.SET_NULL, related_name='product_store') category = models.ForeignKey("store.Category", related_name='product_category', on_delete=models.CASCADE) sub_category = models.ForeignKey("store.SubCategory", related_name='product_sub_category', on_delete=models.SET_NULL, blank=True, null=True) created_by = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='product_creator') title = models.CharField(max_length=255) description = models.TextField(blank=True) slug = AutoSlugField(populate_from='title', unique=True) price = models.DecimalField(max_digits=10, decimal_places=0) serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' views.py class ProductListAPIView(generics.ListAPIView): pagination_class = MyCustomPagination queryset = Product.objects.all().order_by('-date_created') # queryset = Product.objects.all() serializer_class = ProductSerializer products.js <script> new Vue({ el: "#blog", delimiters: ['[[', ']]'], data() { return { products: [], currentPage: 1, hasNext: true, loading: true, … -
Django ManyToMany MultipleChoice Field Edit Values Not Getting Checked
trying to show already selected items from Django many-to-many relationship in multiple choice field, but selected values aren't checked. this is what i've tried so far // models.py class Person(models.Model): name = models.CharField(max_length = 100, help_text = _('name required! maximum 100 characters')) class Team(models.Model): name = models.CharField(max_length = 100, help_text = _('name required! maximum 100 characters')) members = models.ManyToManyField(Member, related_name = 'teams') // forms.py class TeamForm(forms.ModelForm): teams = forms.MultipleChoiceField(choices = Team.objects.all(), widget = forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super(TeamForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['teams'] = [t for t in kwargs['instance'].teams.all()] // views.py class PersonEditView(View): team_form = TeamForm template_name = 'persons/edit.html' def get(self, request, person_id): """ """ person = get_object_or_404(Person, pk = person_id) return render(request, self.template_name, { 'team_form': self.team_form(instance = member, initial = {'teams': person.teams.all()}), }) // edit.html template <div class=""> <p class="">Team Information</p> {% for team in team_form.teams.field.choices %} <div class=""> <input id="{{ team.id }}" type="checkbox" value="{{ team.id }}" class=""> <label for="{{ team.id }}" class="">{{ team.name|title }}</label> </div> {% endfor %} </div> how do i get to show selected teams checked in the list of teams when editing the details of a Person? -
Django - Is it possible to prefetching multiple filters for queryset?
I know you can prefetch a single filtered queryset E.g. Parent.objects.all() .prefetch_related( Prefetch("child_set", queryset=Child.objects.filter(type="A") ) That way running obj.child_set.all().count() will return the count of related A Childs without running another query. But what if I wanted to have the B count too? So the following would take 2 queries - can I somehow prefetch them both? return { "a_count": obj.log_set.filter(type="A").all().count(), "b_count": obj.log_set.filter(type="B").all().count(), } -
Set inital value on django many to many fields
I would like to start a form with a default value sent on a request, but it seems not to be working: views.py """ ADD A NEW FILE IN CLIENT DETAIL """ @login_required def new_file_detail(request, id): user = request.user client = get_object_or_404(ClientPerson, pk=id) form = FilesForm(request.POST or None, request.FILES or None, user=user, instance=client, initial={'person_client': client}) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('files_list') return render(request, 'file_form.html', {'form': form, 'client': client}) Expected: Result: -
Why does my ModelFormSet keeps updating the same record instead of creating a new one?
I have these Models, this is all part of an app that registers events which have images through an ImageAlbum: class EventAlbum(models.Model): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='eventos') def get_main_image(self): return self.images.get(main=True) class EventImage(models.Model): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) image = models.FileField('imagen', upload_to=upload_path) main = models.BooleanField('principal', default=False) album = models.ForeignKey(EventAlbum, related_name = 'images', on_delete=models.CASCADE) And this FormSet for the Images: class BaseImageFormSet(BaseModelFormSet): def clean(self): """Checks that there is only one main image""" if any(self.errors): return boolean_arr = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue main_data = form.cleaned_data.get('main') main = main_data if main_data is not None else False if sum(boolean_arr) > 1: raise ValidationError('There can only be one main image.') boolean_arr.append(main) Here is in my Views: class NewEventView(BaseView): def get(self, request, *args): ImageFormSet = modelformset_factory( EventImage, fields=('image', 'main'), extra=5, max_num=5, formset= BaseImageFormSet) image_formset = ImageFormSet(prefix='images') context = {'forms': {'image_formset': image_formset, } return render(request, "events/events_add.html", context) def post(self, request): new_album = EventAlbum(event=new_event) ImageFormSet = modelformset_factory( EventImage, fields=('image', 'main'), extra=5, max_num=5, formset= BaseImageFormSet) image_formset = ImageFormSet(request.POST, request.FILES, prefix='images') if image_formset.is_valid(): new_album.save() images = image_formset.save(commit = False) for image in images: image.album = new_album image.save() image_formset.save() return HttpResponse('Ok', content_type='text') else: return Response((image_formset.errors, image_formset.non_form_errors()), … -
SES email being consistently hacked
I'm using Amazon SES email from the django-ses module. I have two SES-verified addresses; SES is restricted to sending only to those addresses. There's a DKIM string on my domain's DNS configuration. SES is accessed using django-ses from a contact form on my website that's protected by Recaptcha. Recently I've begun getting spam sent to those verified addresses coming from SES. Messages in Russian, messages containing website links, messages starting with "Hey guys...". I get about one per day. There are many questions on the net about SES emails going to the spam directory. That is NOT the issue here. The emails are received by my InBox; they are just bogus, hacked emails. I changed the SES API key and Secret key, to no avail. Where do I look next? (I don't have AWS Support, and find nothing in their Knowledge Base.) -
How to provide initial data to ForeignKey in ModelFormSet?
So I have this thing. These are the relationships of my models To define an event you have a Place, a QR Link and an ImageAlbum which have up to five Images. An event may or may not have a Place An event MUST have the main image which is marked by the main attr in the Image Form. All the forms are in the same page, they all are processed with a single Submit Now my troubles begin and end in the Forms Department, i have several Model Forms: #FORMS FILE class EventForm(ModelForm): date_time_start = forms.DateTimeField(input_formats=["%Y-%m-%d"], required=True, widget=forms.DateTimeInput(format="%Y-%m-%d", attrs={"id": "cal_start", "placeholder": "yyyy-mm-dd"})) has_place = forms.BooleanField() class Meta: model = Event fields = ['title', 'subtitle', 'phrase', 'date_time_start', 'prices', 'has_place'] class BaseImageFormSet(BaseModelFormSet): def clean_main(self): """Checks that there is only one main image""" if any(self.errors): return boolean_arr = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue main_data = form.cleaned_data.get('main') main = main_data if main_data is not None else False if sum(boolean_arr) > 1: raise ValidationError('There can only be one main image.') boolean_arr.append(main) class PlaceForm(ModelForm): class Meta: model = EventPlace exclude = ['uuid', 'event'] class QRForm(ModelForm): class Meta: model = EventQR exclude = ['uuid', 'event'] My headache is with the Images, … -
importing models into commands file causing Error module not found django
I'm trying to import my app's models into my update.py located inside website/management/commands knowing that website is my application, the problem that i get is that there is no module named 'website' even that I've mentioned it in my Installed_APPS in my settings.py: this is my update.py file : from django.core.management.base import BaseCommand import pandas as pd #from website.models import Product from website.models import Main_data class Command(BaseCommand): help='import booms' def add_arguments(self, parser): pass def handle(self,*args,**options): df=pd.read_excel('main.xlsx',engine='openpyxl') for P_N,P_P,P_L,P_I,P_Logo in zip(df.Product_Name,df.price,df.Link,df.Image,df.Logo): models=Data_Main(Product_Name=P_N,Product_Price=P_P,Product_Link=P_L,Product_Image=P_I,Product_Logo=P_Logo) models.save() this is the error that i get : Traceback (most recent call last): File "C:\Users\dell\Desktop\tam\website\management\commands\update.py", line 4, in <module> from website.models import Main_data ModuleNotFoundError: No module named 'website' this is my INSTALLED_APPS section located in my settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] -
The file is downloading in local but not in production server in Django Rest framework?
I have a simple API that downloads a file in the system. It works perfectly in the local server, but when I deploy the same code to production, it gives me a 500 server error. If I try with another id that doesn't exist, it will say the object is not found. My code is as follows. def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.request.query_params.get("download") == "file": return [] return [permission() for permission in self.permission_classes] def get(self, request, *args, **kwargs): if request.query_params.get("download") == "file": return self.download_file(request) /....other codes........./ def download_file(self, request, *args, **kwargs): instance = self.get_object() file_handle = instance.file.path document = open(file_handle, "rb") response = HttpResponse(FileWrapper(document), content_type="") response["Content-Disposition"] = ( 'attachment; filename="%s"' % instance.file_name ) return response My endpoint URL is this: {{prod}}api/v1/example/notes/12/?download=file When I call this api, putting local in place of prod, it works and I get a file downloaded, but not in production. Is it something to do with file being closed before getting a response?? -
Django complex query with a many to many field
Let's explain the problem. I am trying to filter out all Person that have certain attributes. These are my models: class Person(models.Model): community = models.ForeignKey( Community, on_delete=models.CASCADE, related_name="people" ) class Attribute(models.Model): community = models.ForeignKey( Community, on_delete=models.CASCADE, related_name="attributes" ) name = models.CharField(max_length=50) value = models.CharField(max_length=100) class Trait(models.Model): person = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="person_attributes" ) attribute = models.ForeignKey( Attribute, on_delete=models.CASCADE, related_name="traits" ) A person could have the following attributes: Attribute(name='head', value='big') Attribute(name='head', value='small') Attribute(name='head', value='medium') Attribute(name='hands', value='white') Attribute(name='hands', value='red') #... These attributes are linked to Person through the Trait entity. Now, I have the following dict, witch I use to dynamically build the query: { "head": ["small", "medium"], "hands": ["white", "red"], } I want to filter out all the Person that have the attribute "head" with the value "small" or "medium" and the "hands" "white" or "red" This is what I have done so far, but it doesn't works: # value is the dict like the one explained above from which # I will obtain the elements for filtering def routine(self, value): query = Q() for attr, traits in value.items(): if len(traits) > 0: query &= Q( Q(person_attributes__attribute__name=attr) & Q(person_attributes__attribute__value__in=traits) ) return Person.objects.filter(query) -
how to make use of the file field in django
what else do I need to add to that "file = models.FileField()" this is what I have done but am still not getting any results, why that? class Course(models.Model): TOPIC_CHOICES = ( ("History", "History"), ("Chemistry", "Chemistry"), ("Computer", "Computer") ) lecturer = models.ForeignKey(Lecturer, on_delete=models.CASCADE) category = models.CharField(choices=TOPIC_CHOICES, max_length=100) topic = models.CharField(max_length=250) file = models.FileField() date_created = models.DateTimeField(default=datetime.now) def __str__(self): return f"{self.lecturer}: {self.topic}" -
Django category dosent show up
Am making a django blog and i got problems with it displaying the posts when they are in categories. I got them to work on category_list.html to show the categories listed. But when you click in on a category you should be able to see the blog posts in that category from the categories.html I got no idea why the category posts dosent show up when you enter a category. anyone got any idea what the problem can be? I used {% for cats in cat_menu_list %} in the categories template to display it and ithink the code: def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'categories.html', {'cats': cats.replace('-', ' ').title(), 'cat_menu_list': cat_menu_list, 'page_obj': page_obj}) newsapp views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView) from .models import Post, Category, Comment from .forms import PostForm, EditForm, CommentForm from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.core.paginator import Paginator def LikeView(request, pk): post = get_object_or_404(Post, id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name … -
How to send multiple email invitations with django-allauth and django-invitations
I installed django-invitations to use it together with django-allauth, but it doesn't let me send several mails at the same time, which is inefficient for the correct functioning of the app. Maybe I installed something wrong. I only wrote in setting.py this: ACCEPT_INVITE_AFTER_SIGNUP = os.getenv('ACCEPT_INVITE_AFTER_SIGNUP', True) #I think allow json invites is for multiple emails, but doesn't work INVITATIONS_ALLOW_JSON_INVITES = True INVITATIONS_LOGIN_REDIRECT = os.getenv('INVITATIONS_LOGIN_REDIRECT', '/') ACCOUNT_ADAPTER = 'invitations.models.InvitationsAdapter' Or maybe exists another app who send invitations with allauth, if anyone have any advices please comment, thanks. -
creating django proejcts gets error ValueError: No closing quotation?
I want to create django project.The first thing which I did is install virtualenv for this; after run the following codes I get this error every time.And Pipfile.lock file doesn't create pipenv install virtualenv $ pipenv install virtualenv Creating a virtualenv for this project... Pipfile: C:\Users\Muhammed's\Desktop\django\kkk\Pipfile Using C:/Users/Muhammed's/AppData/Local/Programs/Python/Python39/python.exe (3.9.6) to create virtualenv... [ ] Creating virtual environment...created virtual environment CPython3.9.6.final.0-64 in 1130ms creator CPython3Windows(dest=C:\Users\Muhammed's\.virtualenvs\kkk-fuKJ3HTM, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\Muhammed's\AppData\Local\pypa\virtualenv) added seed packages: pip==22.0.4, setuptools==62.1.0, wheel==0.37.1 activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator [= ] Successfully created virtual environment! Virtualenv location: C:\Users\Muhammed's\.virtualenvs\kkk-fuKJ3HTM Creating a Pipfile for this project... Installing virtualenv... Adding virtualenv to Pipfile's [packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Locking...Building requirements... Resolving dependencies... Locking Failed! Traceback (most recent call last): File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 764, in <module> main() File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 758, in main _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write, File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 741, in _main resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 702, in resolve_packages results, resolver = resolve( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 684, in resolve return resolve_deps( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1397, in resolve_deps results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1110, in actually_resolve_deps resolver.resolve() File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line … -
cant load wsgi_mod on apache server centOS
im using httpd (apache) for rocky linux to develop a django application. I am currently stuck in this problem so I dont get why dont work. Does anybody knows? -
Django Class based view comment section
Blessings, I have a page where DetailView is is being displayed and I would like to add an option to comment on the same page without redirecting to /add-comment url I've tried everything from this Tutorial and the comments still do not work. (comments wont show or post upon submitting) models.py class Comment(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE, default=None) email = models.EmailField(max_length=100) content = models.TextField() post = models.ForeignKey(Movie, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return 'Comment by {}'.format(self.name) views.py class MovieDetail(DetailView): model = Movie def render_to_response(self, *args, **kwargs): self.object.refresh_from_db() self.object.views_count += 1 self.object.save() return super().render_to_response(*args, **kwargs) def get_context_data(self, **kwargs): context = super(MovieDetail, self).get_context_data(**kwargs) context['links'] = MovieLink.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(category=self.get_object().category) return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) self.object = self.get_object() context = super().get_context_data(**kwargs) post = Movie.objects.filter(slug=self.kwargs['slug'])[0] comments = post.comment_set.all() context['post'] = post context['comments'] = comments context['form'] = form if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] content = form.cleaned_data['content'] comment = Comment.objects.create( name=name, email=email, content=content, post=post ) form = CommentForm() context['form'] = form return self.render_to_response(context=context) return self.render_to_response(context=context) -
Advanced Search in Django with Multiple Fields and Keeping Filters in Pagination
I have this piece of code that is working already. It enables you to have a search form, to search in a specific table with multiple filters. The results are paginated, and this form allows you to keep these filters when you browse multiple pages. The problem I'm having now is that I am reusing this piece of code in another scenario, and it involved checking one filter in multiple fields in the database table. Example of a standard scenario: First Name Last Name City In this case, the view will be as such: def clean_filters(filters): filters = {k: v for k, v in filters.items() if v} return filters def search(request): filters = { "user__first_name__icontains": request.GET.get("fname_kw"), "user__last_name__icontains": request.GET.get("lname_kw"), "city__name__icontains": request.GET.get("city_kw"), } html_queries = { "fname_kw": request.GET.get("fname_kw"), "lname_kw": request.GET.get("lname_kw"), "city_kw": request.GET.get("city_kw"), } filters = clean_filters(filters) html_queries = clean_filters(html_queries) people = Person.objects.filter(**filters) page_num = request.GET.get("page", 1) p = Paginator(people.order_by("-pk"), 12) people = p.get_page(page_num) context = { "people": people, "cities": City.objects.all(), "filters": html_queries, } return render(request, "pages/index.html", context) And the HTML will be as such: <form method="GET" action="{% url 'search' %}"> <div class="row"> <div class="col-xl-3 col-lg-3 col-md-3 col-sm-12 col-xs-12"> <div class="row"> <div class="col-6"> <input class="form-control" name="fname_kw" id="search_fname" placeholder="First Name" /> </div> <div class="col-6"> … -
selinux is disabled and I'm still getting error 13
I'm running a django project on rhel7. Current selinux status: SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: permissive Mode from config file: permissive Policy MLS status: enabled Policy deny_unknown status: allowed Max kernel policy version: 31 Despite that, my application is still throwing this in the logs: [Mon Jun 06 17:09:12.573815 2022] [wsgi:error] [pid 34476] (13)Permission denied: mod_wsgi (pid=34476, process='graphite', application=''): Call to fopen() failed for '/opt/graphite/conf/graphite.wsgi'. -
update data using ajax with django and bootstrap modal
here is my views.py def update_article(request, pk): obj = Article.objects.get(pk=pk) if request.headers.get('x-requested-with') == 'XMLHttpRequest': new_designation = request.POST.get('designation') new_famille = request.POST.get('famille_id') new_quantite = request.POST.get('quantite') obj.designation = new_designation obj.famille = new_famille obj.quantite = new_quantite obj.save() return JsonResponse({ 'designation': new_designation, 'famille': new_famille, 'quantite': new_quantite, }) return redirect('/article') Here is my modal <div class="modal fade" id="UpdateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Update</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" > <form action="" method="post" id="update-form"> {% csrf_token %} {% for field in form %} <div class="form-group col-lg-12"> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update</button> </div> </form> </div> </div> </div> here is my Js const getData = () =>{ $.ajax({ type:'GET', url:'/load/', success: function(response){ console.log(response) const data = response.article console.log(data) data.forEach(element => { articleBox.innerHTML +=` <tbody> <tr> <td><div ><a data-bs-toggle="modal" data-bs-target="#detailModal" href="" data-pic=${element.designation} class="detail" >${element.designation}</a></div></td> <td>${element.famille}</td> <td><a href="#">${element.quantite}</a></td> <td>${element.date}</td> <td>Available</td> <td><a href="#" data-bs-toggle="modal" data-bs-target="#delete">Delete</a> |<div data-bs-toggle="modal" data-bs-target="#UpdateModal" id="update-article" >Edit</div></td> </tr> </tbody> ` }); }, error: function(error){ console.log(error) } }) } from this code I want to update my data by id,I've tried everything but when I click the edit button , the form modal … -
Can multiple values be assigned to one variable without brackets "[]" or parentheses "()" (Python)
From this django answer in SO, I found 3 variables "JAN", "FEB" and "MAR" in the class "Month" extending "models.TextChoices" as shown below: # "models.py" from django.db import models class MyModel(models.Model): class Month(models.TextChoices): JAN = "1", "JANUARY" # Here FEB = "2", "FEBRUARY" # Here MAR = "3", "MAR" # Here # (...) month = models.CharField( max_length=2, choices=Month.choices, default=Month.JAN ) And multiple values are assigned to each variable without brackets "[]" which creates Array or parentheses "()" which creates Tuple as shown below: JAN = "1", "JANUARY" FEB = "2", "FEBRUARY" MAR = "3", "MAR" Now, can multiple values be assigned to one variable without brackets "[]" or parentheses "()"? -
Undefined Json response from django backend to chrome extension alert
Hi i am trying to return a json file to the chrome extention to show it to the user, the query go to server without a problem, fetched url is also working and does return the json file when i try it directly, but the chrome extention shows "undefined" message in the alert instead of the json file. the returned json file have this type : JsonResponse(data) data is a dict[str, Union[str, list]], another question, is how can i show the json file in the popup html page? to my chrome extension code: Manifest.json: { "name": "Price Comparator", "description": "Compare prices across other websites!", "version": "1.0", "manifest_version": 3, "background": { "service_worker": "background.js" }, "icons": { "16": "images/logo16.png", "48": "images/logo48.png", "128": "images/logo128.png" }, "action": { "default_icon": "images/logo16.png", "default_popup": "popup.html" }, "host_permissions": ["XXX*"], "permissions": [ "XXX", "http://127.0.0.1:8000/", "storage", "activeTab", "scripting", "tabs", "background", "identity", "notifications" ], "content_scripts": [ { "matches": [ "https://www.google.com/*" ], "css": [ "main.css" ] } ] } popup.js: $(function(){ $('#keywordsubmit').click(function(){ var search_topic = $('#keyword').val(); if (search_topic){ chrome.runtime.sendMessage( {topic: search_topic}, function(response) { result = response.farewell; alert(result.summary); var notifOptions = { type: "basic", iconUrl: "icon48.png", title: "WikiPedia Summary For Your Result", }; chrome.notifications.create('WikiNotif', notifOptions); }); } $('#keyword').val(''); }); }); Background.js: chrome.runtime.onInstalled.addListener(() => … -
Django-tables2 exporting badly
I'm using django-tables2 for export my tables. When I export the table to excel format it seems like this: enter image description here. I can't see all of the cell. How can I set the width of excel columns before export? tables.py import django_tables2 as tables from .models import Customer class CustomerTable(tables.Table): export_formats = ['xls','xlsx','csv'] class Meta: model = Customer fields = ('orderorbarcode','item_barcode','order_id', 'full_name','company','email','phone_number','note') html part <div class="container"> {% for format in table.export_formats %} <a id="{{format}}" href="{% export_url format %}">.{{ format }}</a> {% endfor %} {% render_table table %} </div> -
Extend User model in Django with jwt authorization
I am trying to extend User model in Django. I already have authorization using jwt Token and I am currently trying to add another field to User model, such as phone number and address. My views.py looks like this: class MyObtainTokenPairView(TokenObtainPairView): permission_classes = (AllowAny,) serializer_class = MyTokenObtainPairSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer models.py like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.IntegerField(blank=False) address = models.CharField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() In here I'm trying to create another class that will store phone number and address. How can I incorporate my Profile class into User so that it will create new user model and what is more use earlier implemented Token authorization. -
Multiple nested choices in Django models
Forgive me if I'm not describing this correctly - I'm still learning and I've hit a wall with a problem I'm working on. I want to create a way (in the Admin backend for now) for users to show the books they like by fiction/non-fiction, age-range, genre(s) and sub-genre(s). So, a user who liked gothic horror books could select fiction>adult>horror>gothic. Or, a user who likes literally all YA books could select fiction>Young Adult and their selection would cascade down to every genre and sub-genre. I think the Choices field option and the MultiSelectField functionality might be a start, but there doesn't seem to be a way to add 'layers' to the choices beyond the categories below, and it seems like an inelegant solution when there could be hundreds of choices. I also don't know how it could be presented in the Admin - ideally with checkboxes that can 'open up' to show the sub-categories beneath them. GENRE_CHOICES = ( ('Fiction', ( ('FCH', 'Childrens'), ('FMG', 'Middle Grade'), ('FYA', 'Young Adult'), ('FAD', 'Adult'), )), ('Non-Fiction', ( ('NCH', 'Childrens'), ('FMG', 'Middle Grade'), ('FYA', 'Young Adult'), ('FAD', 'Adult'), )), ) genres = MultiSelectField(max_length = 100, choices=GENRE_CHOICES, null=True) I don't even know the name of … -
Django blog categories wont show up
I got a problem where my blog post categories dosent show up on my categories page with the code i used below from cat_menu_list and {% for post in cat_menu_list %}. How do i get the diffrent categories to show up in my categories.html? hope someone can help ithink below is all the code that does this if u need anymore tell me and i upload it asap. views.py def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'category_list.html', { 'cat_menu_list': cat_menu_list}) def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render( request, 'categories.html', { 'page_obj': page_obj, 'cats': cats.replace('-', ' ').title(), "cat_menu_list": cat_menu_list}) categories.html {% extends 'base.html' %} {% block content %} <h1 class="headerh1">{{ cats }}</h1> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in cat_menu_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title"><a href="{% url 'article-detail' post.pk %}" class="text-dark">{{post.title }}</a></h2> <p class="card-text text-dark h6">{{ post.author.first_name }} {{post.author.last_name }} | {{ post.post_date }} <a href="{% url 'category' post.category|slugify %}">{{ post.category }}</a></p> <div class="card-text">{{ post.body|safe|slice:":200" }}</div> <a href="{% url 'article-detail' post.pk %}" class="btn btn-info">Read More</a> {% if user.is_authenticated %} {% if user.id == …