Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django crispy forms and bootstrap - adjust field height
I have a page where user inputs information into a number of inline formsets. these forms are styled with crispy forms and bootstrap. There is also some javascript to allow users to dynamcially add forms I have a slight issues in that one of the forms presents a range slider (concern in the SideEffectFormset which looks slightly off as it is a little shorter than the other input boxes and I havent been able to adjust this using the formset helper. Any advice on how to amend the formset helper or the html much appreciated! forms.py SideeffectFormSet = inlineformset_factory( Case, SideEffect, fields=("se_name", "concern"), widgets={'concern': RangeInput()}, extra=0, min_num=1, validate_min=True, ) class SideEffectFormSetSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = "post" self.form_id = 'id-SideeffectForm' self.form_class = 'blueForms' self.form_show_labels = False self.render_required_fields = True self.form_tag = False self.layout = Layout( Div( Div(Field("se_name", placeholder="Chickpeas"), css_class='col-4 col-lg-4 h-50'), Div(Field("concern", placeholder="concern"), css_class='col-8 col-lg-8 '), css_class="row", ), ) widgets.py from django.forms.widgets import NumberInput class RangeInput(NumberInput): input_type = 'range' html <div class='row mt-4' > <h6>Side Effects</h6> </div> <table id="sideeffects_table" border="0" cellpadding="0" cellspacing="5" width='100%'> <tbody> {% for form in sideeffect_formset %} <tr> <td> {% for fld in form.hidden_fields %}{{ fld }}{% endfor %} {% if form.instance.pk %}{{ form.DELETE … -
Django - Creating Keys that include calculated fields that are not saved to the database
I have a series of linked tables creating a django website. The user table has a calculated field which classifies people according to their age. This classification changes as the person gets older so I do not want to save this value to the database (unless it can be automatically updated as the age boundaries are reached). This age code needs to be used as part of a key to link to fields in another table. The classification table takes Value 1 and Value 2 from the Score table and the age code from the calculation in the User table which itself gets the code from the Age table. These provide a unique code that the classification table uses to provide a value back to the Score table.[Schematic image of tables here][1] I have been able to get the values for the score table, themselves links to other tables, it is just getting the calculated value back from the User table that is proving to be the problem. I don't really want to save the age code back to the User table unless this can be automatically updated when the age boundary is crossed. Any help would be greatly appreciated … -
Delete Django ImageField and FileField records whose files are not found on the server
I've recently lost some files in my media folder, and I want to delete the image field/FileField objects whose files have been removed. -
Terminal/Virtualenv may not be synchronized with github page
So I'm using a $5 droplet from digital oceans to host a django website and whenever I tried using python manage.py runserver 134.6.4.2:8000 it tells me to add 134.6.4.2 to ALLOWED_HOSTS even though I added it and pushed it into the master branch a while ago, also I added a new file into the folder and whenever I try to ls into the folder the file seems to be missing even though it can be seen on the github page through my profile. How do I solve this? I've been following this tutorial and this guide -
Custom alert not showing - React
I am currently following a tutorial for a Django+React project. When a user tries to login with the wrong credentials, an alert "error" should popup, and when the user manages to login a "success" alert should appear as well. The login logic works fine, but I don't get any alert (they are custom alerts btw). Here is the login part of the code : axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" axios.defaults.xsrfCookieName = "csrftoken" export const login = (email, password) => async dispatch => { const config = { headers: { 'Content-Type': 'application/json' } }; const body = JSON.stringify({ email, password }); try { const res = await axios.post('http://localhost:8000/api/token/', body, config); dispatch({ type: LOGIN_SUCCESS, payload: res.data }); dispatch(setAlert('Authenticated successfully', 'success')); } catch(err) { dispatch({ type: LOGIN_FAIL }); dispatch(setAlert('Error Authenticating', 'error')); } }; and here is the alert part : import { v4 as uuid } from 'uuid'; import { SET_ALERT, REMOVE_ALERT } from './types'; export const setAlert = (msg, alertType, timeout = 5000) => dispatch => { const id = uuid(); dispatch({ type: SET_ALERT, payload: { msg, alertType, id } }); setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout); } I have checked import and variables names, and I can't find an answer … -
How to set select all data up to data_upload_max_number_fields (example 500) in django admin listing page
First of all sorry if is there any question already please let me know that because I am fresh in this community And thanks in advance for your valuable responses In the below screenshot in Django admin, How can I override the select all 1005 with some custom number like select up to 500. As you know data_upload_max_number_fields has only a 1000 limit but I don't want to increase the limit every time. Because it might be possible I have 100000 data then how much will increase the data_upload_max_number_fields in django settings. So is there any way that I can override this select all thing to less than the upload max field for example select all up to first 500 data I don't want like the default one shown in the 2nd image -
Removing circular data in a dictionary of dictionaries
I've hit a challenge with my personal accounting app I can't even imagine how to approach. The script is generating some JSON for a Sankey diagram which shows cash moving through the ledgers: The issue is that the Sankey goes wrong if the cash moves in a circle, eg from Ledger A to Ledger B to C and back to A. I'm trying to write some code that will evaluate the data and if there's a circular movement then it should break that circle by removing one of the links. The code starts with a dictionary of dictionaries which contains the amount of cash that's moving between each possible pair of ledgers. The top dictionary contains the ledgers as keys and another dictionary of ledgers as the values. The inner dictionary contains the ledgers as keys and amount of cash moving as the value. Below is a print(str(dict)) of the dictionary. Zeros mean there's no cash moving between the two ledgers. Have had to truncate due to Stack Overflow charactor limit. Would you suggest how to even approach this? {<Ledger: Basic food>: {<Ledger: Basic food>: 0, <Ledger: Benefits>: 0, <Ledger: Books>: 0, <Ledger: Clothing>: 0, <Ledger: Coffee & Snacks>: 0, … -
python django challenge app and while passing url which contains numeric produce below error
views.py from http.client import HTTPResponse from django.shortcuts import render from django.http import HttpResponse,HttpResponseNotFound # Create your views here. def index(request,week): return HTTPResponse(week) def allweek(request,week): text=None if week=='sunday': text='Sunday is funday and also utilize well' elif week=='monday': text='start of week and after break' elif week=='tuesday': text='very long meetings' elif week=='wednesday': text='finished half of week' elif week=='thursday': text='preparing for weekend party day' elif week=='friday': text='weekend arrived' elif week=='saturday': text='wait is over enjoy tour day!' else: return HttpResponseNotFound('Entered wrong week of the day') return HttpResponse(text) urls.py from django.urls import path from . import views urlpatterns = [ path('<int:week>',views.index), path('<str:week>',views.allweek), ] Getting below error while executing the above code As i tried to use int and str values in the urls to map the respective views but while mapping the int values below error is encountered. AttributeError at /challenges/1 'int' object has no attribute 'makefile' while runni -
DRF - Auto generation code Field doesnot show in admin
I want to make autogeneration field in my model. I have create when i give request to post man it will create next code automatically. But, I want to show code autogeneration field when user add the data inttable. models.py class GeneralDocumentType(models.Model): code = models.CharField(max_length=10, null=False, unique=True) name = models.CharField(max_length=100, null=False, unique=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name In serializer I have written code for autogeneration only in code field(DOC001,DOC002,..) serializers.py def get_code(model, prefix): content = model.objects.all().last() last = None code_prefix = prefix if content: a_string = content.code split_strings = [] n = len(prefix) for index in range(0, len(a_string), n): split_strings.append(a_string[index: index + n]) last = int(split_strings[1]) if last is not None: suggested = last + 1 else: suggested = 1 return "{}{:03d}".format(code_prefix, suggested) class GeneralDocumentTypeSerializer(serializers.ModelSerializer): class Meta: model = GeneralDocumentType fields = ["id", "code", "name", "description"] read_only_fields = ['code'] def create(self, validated_data): validated_data["code"] = get_code(GeneralDocumentType, "DOC") return GeneralDocumentType.objects.create(**validated_data) what i did wrong, How can I show code field should be (DOC003) increased when user add the data. How can i acieve that??? -
Field 'id' expected a number but got '{user.id}'
what should be the reason ...why am i getting this error if request.user.is_authenticated: user=request.user user_id=request.GET.get('user') payment_request_id=request.GET.get('payment_request_id') payment_id=request.GET.get('payment_id') print(payment_id,payment_request_id) response = API.payment_request_payment_status(payment_request_id, payment_id) # Purpose of Payment Request status=response.get('payment_request').get('payment').get('status') user=User.objects.get(id=user_id) -
settings.DATABASES is improperly configured. Heroku
Trying to do some testing on my Heroku Local Server (http://0.0.0.0:8000/) - the index.html loads correctly but when I navigate away (for example to admin) from that page I get the following error: Traceback (most recent call last): File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 417, in login return LoginView.as_view(**defaults)(request) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/decorators/debug.py", line 90, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/contrib/auth/views.py", line 64, in dispatch return super().dispatch(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/generic/base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/generic/edit.py", line 135, in get return self.render_to_response(self.get_context_data()) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/contrib/auth/views.py", line 101, in get_context_data current_site = get_current_site(self.request) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/contrib/sites/shortcuts.py", line 13, in get_current_site return Site.objects.get_current(request) … -
update view inside detail view
Right now I have one class based detail view and one class based update view. They are completely separate and both are working fine. I wonder if it is possible to combine these two? So that the user can update their data directly from the detail view, just to make it easier for the user. This is my models.py file class geography(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE, null=False) title = models.ForeignKey(Title, on_delete=models.CASCADE, null=False, max_length=120) rep1 = models.DateField(blank=True, null=True) rep2 = models.DateField(blank=True, null=True) rep3 = models.DateField(blank=True, null=True) rep4 = models.DateField(blank=True, null=True) rep5 = models.DateField(blank=True, null=True) def __int__(self): return self.pk def get_absolute_url(self): return reverse('geography') This is my forms.py file class GeographyForm(forms.ModelForm): class Meta: model = Geography fields = ('title', 'rep1', 'rep2', 'rep3', 'rep4', 'rep5') This is my detailview class GeographyDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Geography def test_func(self): Geography = self.get_object() if self.request.user == Geography.elev: return True return False This is my updateview class GeographyUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Geography form_class = GeographyForm def form_valid(self, form): form.instance.student = self.request.user return super().form_valid(form) def test_func(self): Geography = self.get_object() if self.request.user == Geography.student: return True return False I tried "FormMixins" in the detail view, but I could not get it to work. -
How can I customise different views to the normal users and admin using django?
I tried out the below view function. But the normal user's page 'studenthpage' is never getting rendered, while the superuser is able to login. instead of 'elif user.is_active:' I even tried just else condition, still not successful. can anyone help def login(request): if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None : auth_login(request,user) if user.is_superuser: return redirect('adminhpage') elif user.is_active: return redirect('studenthpage') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'login.html', context) -
how can i convert html to pdf in django, cyrilic font
I am trying to convert html to pdf in django using xhtml2pdf, and successfully converted html to pdf in english alphabet and numbers but in russian alphabet(cyrilic) it is giving me black square box, enter image description here Here is what I tried: views.py def download(request): user = request.user template_path = 'faktura.html' context = {'user': user} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="contract.pdf"' template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response And html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {# <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"#} {# integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">#} <title>Document</title> </head> <body> <div class="container"> <div class="row"> <div class="col-12"> <h5 class="text-center py-5">ДОГОВОР № 0000, от 00.00.0000 г</h5> <div class="d-flex justify-content-between px-5"> <h6>г.Наманган</h6> <h6>«00» месяц 0000 г</h6> </div> <p> Общество с ограниченной ответственностью <b>Ўзбекистон бўйлаб бепул етказиб берамиз!</b>, г.Наманган, Республика Узбекистан, именуемое в дальнейшем «Продавец», в лице директора Юсупова М.М., действующее на основании Устава, с одной стороны, ООО «_____________________________________________», именуемое в дальнейшем «Покупатель», в лице_____________________________________ , действующего на основании_______________, с другой … -
No Leasson matches the given query. Django
The project structure is as follows: Category: Subcategory: Object. implemented the system next-prev(cat-sub-obj) with difficulty. how can i optimize this code when an object ends up in a subcategory. I can't immediately jump to the next item in the next subcategory. def leasson(request, course_slug, section_slug, leasson_slug): leasson = get_object_or_404(Leasson, course__slug=course_slug, section__slug=section_slug, slug=leasson_slug) section = get_object_or_404(Section, course__slug=course_slug, slug=section_slug) try: next_leasson = leasson.get_next_by_date_added(section__slug=section_slug) except Leasson.DoesNotExist: next_leasson = None try: next_section = section.get_next_by_date_added(course__slug=course_slug) except Section.DoesNotExist: next_section = None try: prev_section = section.get_previous_by_date_added(course__slug=course_slug) except Section.DoesNotExist: prev_section = None try: prev_leasson = leasson.get_previous_by_date_added(section__slug=section_slug) except Leasson.DoesNotExist: prev_leasson = None context = { 'leasson': leasson, 'next_leasson':next_leasson, 'prev_leasson':prev_leasson, 'next_section':next_section, 'prev_section':prev_section } return render (request, 'leasson.html', context) path('<slug:course_slug>/<slug:section_slug>/<slug:leasson_slug>/', leasson, name="leasson") {% if prev_leasson %} <a href="{% url 'leasson' leasson.course.slug leasson.section.slug prev_leasson.slug %}">{{ prev_leasson.title }}</a> {% else %} This is first leasson {% endif %} {% if next_leasson %} <a href="{% url 'leasson' next_leasson.course.slug next_leasson.section.slug next_leasson.slug %}">{{ next_leasson.title }}</a> {% else %} This is last leasson {% endif %} {% if prev_section %} <a href="{% url 'section' prev_section.course.slug prev_section.slug %}">{{ prev_section }}</a> {% else %} This is first section {% endif %} {% if next_section %} <a href="{% url 'section' next_section.course.slug next_section.slug %}">{{ next_section }}</a> {% else %} This is … -
One template for all errors. django
One template to catch all errors on the project and show the information to the user I would like to create a single template to catch and show, to the user, all or at least most of the errors that may occur on the website; but I don't find information about it, and maybe you can help me. -
Django channels not recalling old messages from channel
I am using Django channels to create a chat app. When the chat page is refreshed, the past messages disappear. Also, when I reconnect to the channel, the old messages do not show up. Everything else seems to work fine, messages can be sent and received by the other user, message data is being saved into the database for each specific channel. No error is thrown back. managers.py from django.db import models from django.db.models import Count class ThreadManager(models.Manager): def get_or_create_personal_thread(self, user1, user2): threads = self.get_queryset().filter(thread_type='personal') threads = threads.filter(users__in=[user1, user2]).distinct() threads = threads.annotate(u_count=Count('users')).filter(u_count=2) if threads.exists(): return threads.first() else: thread = self.create(thread_type='personal') thread.users.add(user1) thread.users.add(user2) return thread def by_user(self, user): return self.get_queryset().filter(users__in=[user]) models.py from django.db import models from app_users.models import User from app_chat.managers import ThreadManager class TrackingModel(models.Model): created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField( max_length=15, choices=THREAD_TYPE, default='group') users = models.ManyToManyField(User) objects = ThreadManager() def __str__(self): if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) def __str__(self) -> str: return f'From <Thread - … -
Is there a specific way to deny anyone else from logging in to an already logged in account?
I just created my website but facing some issues, is there a way to check if someone is already logged in to an account and if so, user should be redirected to login page so that he/she can log in to a different account if he/she wishes. I'm using python with Django. -
Django Html Raise ValidationError
In my models.py I have: class Post(models.Model): res_person_1 = models.TextField(max_length=40, verbose_name="User") When I load form I run script: $("#id_res_person_1").replaceWith("<select name='res_person_1' id='id_res_person_1' class='form-control' required></select>") $("#id_res_person_1").append("<option>" + '---------' + "</option>") //append options where I create dropdown menu and fill it with users from DB. Problem is, in my models.py and when I run script, I put that field as required. On all other required fields in the form, when I submit, I get error 'Required field', but never on that one. How can I raise an error or show any kind of message to tell the user that he should select something from the dropdown menu. So far I tried (but it did not work): def clean_res_person_1(self): if self.res_person_1 == '' or self.res_person_1 == '---------': raise forms.ValidationError("self.fields['res_person_1'].error_messages['invalid']") return self.cleaned_data -
For each item update database
I'm a total beginner with Python/Django and trying to understand why this isn't working. I have a function that contains a for loop, doing some logic and then updating a model. but when I have more than 1 item in the loop I get a UNIQUE constraint failed: app_token.token_name error. So I think I'm misunderstanding how the loop is working? function tokens = Token.objects.all() for item in tokens: if item.token_contract_address is not None: token = Token.objects.get(pk=item.id) parameters = { 'address':token.token_contract_address } session = Session() session.headers.update(headers) response = session.get(url, params=parameters) resp = json.loads(response.text) token_id = (resp['data'][next(iter(resp['data']))]['id']) logo = (resp['data'][next(iter(resp['data']))]['logo']) url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest' parameters = { 'id':token_id } session = Session() session.headers.update(headers) response = session.get(url, params=parameters) id = str(token_id) price = (json.loads(response.text)['data'][id]['quote']['USD']['price']) market_cap = (json.loads(response.text)['data'][id]['quote']['USD']['market_cap']) change = (json.loads(response.text)['data'][id]['quote']['USD']['percent_change_24h']) r = Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) I'm expecting the this Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) to update the model based on the item loop? The model is very simple: class Token(models.Model): token_name = models.CharField(max_length=50, blank=False, unique=True) token_slug = models.CharField(max_length=50, blank=True,null=True) token_price = models.FloatField(blank=True,null=True) token_capture_date = models.DateField(blank=True,null=True) token_contract_address = models.CharField(max_length=50, blank=True,null=True) def __str__(self): return str(self.token_name) I'm using the update on the objects and have tried removing the token_name, … -
Apache2: 'AH01630: client denied by server configuration' with referer?
I'm trying to setup a django website but for some reason when I try to access the admin page it shows up without an CSS, I dug a bit further and ensured that my file permissions where correct by just making the entire project directory accessible to everyone chmod -R 777 ./survey_server But it still just isn't working for me for some reason, I'm not sure what's going on. I've checked, rechecked, and triple checked my apache config file to no avail. This is my config file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com # ServerName crimjusticesurvey.org ServerAdmin webmaster@crimjusticesurvey.org DocumentRoot /home/ubuntu/Workspace/github/crimjusticesurvey/survey_server <Directory /home/ubuntu/Workspace/github/crimjusticesurvey/survey_server> Require all granted </Directory> <Directory /home/ubuntu/Workspace/github/crimjusticesurvey/survey_server/survey> Require all granted </Directory> # Available loglevels: … -
Return the category value as null in Django (json)
Why does my category return null when I receive Jason output? enter image description here enter image description here enter image description here enter image description here -
Faster way than .csv to upload data into Django app
Right now I copy a whole table from a website, paste it into a cell on an excel spreadsheet and it formats it into a .csv file. After the .csv is made I upload the file into my database via a Django app. I also have a model form if I wanted to enter the data manually. What I was wondering is if there is a way to skip a step to make the process faster. Maybe copy the table from the web and paste it into a form cell and it gets formatted like excel does. Any tips or ideas are greatly appreciated. -
accessing 2 foreign key fields at the same time in django serializers
I have the following models in my django rest framework project. in this project there are products and they have producers and importers. # models.py class Product(models.Model): name = models.CharField(max_length=255) producer = models.ManyToManyField(Company, related_name='producer') importer = models.ManyToManyField(Company, related_name='importer') class Company(models.Model): name = models.CharField(max_length=255) I need to make an API which retrieves an instance of the "Company" model and gives me a list of the products they have produced and another list for the products that they have imported Now I know to do this with only one manytomany field, I can do the following: class CompanyRetrieveSerializer(serializers.ModelSerializer): class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('name',) product_set = ProductSerializer(read_only=True, many=True,) class Meta: model = Company fields = '__all__' but since there are two fields in the product model that reference the company model, this doesn't work. Is there any way to fix this issue? -
Why isn't my javascript not working with django
I am a beginner in django. I have no problem with the back-end but my front-end has some problem with javascript (specifically addEventListener doesn't work). I've tried everything from adding External js to adding internal js nothing seems to work. But the js connect with django and its being loaded, but the function doesn't work and no error seems to log in the console. It is just a click function, which should toggle a classname in html while clicked. By the way I'm inheriting my nav file. i hope that doesn't cause any problem. My internal js file: <script type="text/javascript"> // EVENT LISTENER FOR NAV FUNCTION let nav_btn = document.querySelector('.user-pr') nav_btn.addEventListener('click', navfunc) function navfunc() { nav_btn.classList.toggle('active') console.log("click") } </script> My Settings.py file (Static Config): STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'Assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I've checked StackOverflow for similar questions, but nothing match my scenario.