Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upgrading to Django 3 from Django 2.2.x
I'm trying to upgrade Django 2.2.7 to Django 3. I have an Exception with the load of static library in my template when it's called by tag {% load static from staticfiles %}. Stacktrace: Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py", line 1021, in find_library return parser.libraries[name] KeyError: 'staticfiles In the settings.py, staticfiles is config like this: STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = '/static/' And when requested by browser, Django answered: 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log' Github code is here, PR is here Many thanks ! -
how do I connect my Django app with telegram to fetch channel messages?
I need some help in getting telegram messages in my Django app. I want to connect my django app with telegram user account and get the list of all channel. After user selects a specific channels, the messages of that channel should be displaying in my application The application should have the real-time messages. I'm using Mysql database to store the channel list and messages. Any help would be appreciated for this project. -
DataTable (JQuery): how to switch language with browser language?
I use DataTable in my Django project and currently doing internationalisation of my apps I would like DataTable change with browser language as for my templates. I have found the way to change language with DataTable option var table = $('#table_id').DataTable({ lengthMenu: [5,10], "language": { "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json" } }); is their a simple way doing it? or should I test for browser language and have a switch to initialize var table? something like that (pseudocode): if browser.lang == 'english'{ var table = $('#table_id').DataTable({ lengthMenu: [5,10], }); } else { var table = $('#table_id').DataTable({ lengthMenu: [5,10], "language": { "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json" } }); }``` -
Post a file to Django REST Framework without Headers/Footers
I am attempting to store a .csv file uploaded to Django REST Framework in its original format. I am following the instructions and the Django REST Framework page for uploading files. When I PUT a .csv file to a defined endpoint I end up waith a file with additional headers and footers. I am trying to save this file into a FileField in its original format so I can run some post-processing steps more easily. Steps I've taken: I created a model to store the file. from django.db import models class OriginFile(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to="origin_files/") And I created an APIView to handle the upload. from rest_framework import views from rest_framework.parsers import FileUploadParser from rest_framework.response import Response from reference.reference_model.models import OriginFile class OriginFileView(views.APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): f = request.data["file"] load_origin_file = OriginFile() load_origin_file.file.save(filename, f, save=True) return Response(status=204) What I am seeing: The first couple of lines of my original file look like: SPID,SA_ID,UOM,DIR,DATE,RS,NAICS,APCT,0:15,0:30,0:45,1:00,1:15,1:30,1:45,2:00,2:15,2:30,2:45,3:00,3:15,3:30,3:45,4:00,4:15,4:30,4:45,5:00,5:15,5:30,5:45,6:00,6:15,6:30,6:45,7:00,7:15,7:30,7:45,8:00,8:15,8:30,8:45,9:00,9:15,9:30,9:45,10:00,10:15,10:30,10:45,11:00,11:15,11:30,11:45,12:00,12:15,12:30,12:45,13:00,13:15,13:30,13:45,14:00,14:15,14:30,14:45,15:00,15:15,15:30,15:45,16:00,16:15,16:30,16:45,17:00,17:15,17:30,17:45,18:00,18:15,18:30,18:45,19:00,19:15,19:30,19:45,20:00,20:15,20:30,20:45,21:00,21:15,21:30,21:45,22:00,22:15,22:30,22:45,23:00,23:15,23:30,23:45,0:00 5001,5001,KWH,R,05/20/2018,A6,722000,100.0,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000200,0.022600,0.058100,0.100500,0.148500,0.251400,0.295800,0.359500,0.321400,0.365300,0.509800,0.571900,0.734700,1.121900,1.312700,1.358400,1.573900,1.270300,1.512500,1.359400,1.735500,1.759900,1.806400,1.501400,1.343900,1.396900,1.660400,1.924500,2.074300,2.037100,1.409000,1.371600,1.646600,1.591100,1.674500,1.751400,1.366200,1.404300,1.449400,1.405700,1.197900,0.679400,0.793800,0.772400,0.768200,0.969800,0.967400,0.833900,0.623500,0.474100,0.446600,0.368700,0.233500,0.133600,0.043800,0.011100,0.000300,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000 The first handful of lines of the stored file look like: ----------------------------434117419534676393692068 Content-Disposition: form-data; name="file"; filename="filename.csv" Content-Type: text/csv SPID,SA_ID,UOM,DIR,DATE,RS,NAICS,APCT,0:15,0:30,0:45,1:00,1:15,1:30,1:45,2:00,2:15,2:30,2:45,3:00,3:15,3:30,3:45,4:00,4:15,4:30,4:45,5:00,5:15,5:30,5:45,6:00,6:15,6:30,6:45,7:00,7:15,7:30,7:45,8:00,8:15,8:30,8:45,9:00,9:15,9:30,9:45,10:00,10:15,10:30,10:45,11:00,11:15,11:30,11:45,12:00,12:15,12:30,12:45,13:00,13:15,13:30,13:45,14:00,14:15,14:30,14:45,15:00,15:15,15:30,15:45,16:00,16:15,16:30,16:45,17:00,17:15,17:30,17:45,18:00,18:15,18:30,18:45,19:00,19:15,19:30,19:45,20:00,20:15,20:30,20:45,21:00,21:15,21:30,21:45,22:00,22:15,22:30,22:45,23:00,23:15,23:30,23:45,0:00 5001,5001,KWH,R,05/20/2018,A6,722000,100.0,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000200,0.022600,0.058100,0.100500,0.148500,0.251400,0.295800,0.359500,0.321400,0.365300,0.509800,0.571900,0.734700,1.121900,1.312700,1.358400,1.573900,1.270300,1.512500,1.359400,1.735500,1.759900,1.806400,1.501400,1.343900,1.396900,1.660400,1.924500,2.074300,2.037100,1.409000,1.371600,1.646600,1.591100,1.674500,1.751400,1.366200,1.404300,1.449400,1.405700,1.197900,0.679400,0.793800,0.772400,0.768200,0.969800,0.967400,0.833900,0.623500,0.474100,0.446600,0.368700,0.233500,0.133600,0.043800,0.011100,0.000300,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000 And the last couple of lines of the stored file look like this. 5090,5090,KWH,D,11/04/2018,A6,713910,104.2,0.333000,0.319000,0.332000,0.309000,0.326500,0.321000,0.322500,0.320000,0.296000,0.322000,0.323000,0.334000,0.321000,0.334000,8.098000,7.043000,1.422000,0.322000,0.323000,0.335000,0.322000,0.322000,0.322000,0.334000,0.336000,0.340000,0.392000,0.584000,0.200000,0.054000,0.176000,0.156000,0.090000,0.000000,0.002000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.002000,0.001000,0.009000,0.014000,0.020000,0.032000,0.054000,0.055000,0.086000,0.127000,0.151000,0.168000,0.220000,0.245000,0.299000,0.282000,0.317000,0.328000,0.314000,0.327000,0.315000,0.328000,0.316000,0.328000,0.318000,0.323000,0.328000,0.319000,0.327000,0.325000,0.320000,0.332000,0.319000,4.420000,3.531000,2.584000,0.458000,1.001000,0.263000,0.263000,0.261000,0.260000,0.258000 ----------------------------434117419534676393692068-- Is there a way … -
Upgrading Python 3.6 to 3.8
I downloaded python 3.8 expecting it to update python 3.6 with all my packages intact. instead it installed as a separate version so i now have two python versions installed on windows 10. -
How to create model objects of one model automatically when a model object of another has been added in django
Say for example I have a Model called Player. I want Model objects of Player created when new Users are added in django (from django.contrib.auth.models.User) such that each User object in User model has its own object in Player model. I know that I would technically have to use models.ForeignKey() to create a field in Player model and relate it to the User model and that I don't have to worry about deletion of users if I use the on_delete=models.CASCADE parameter in models.ForeignKey() but how do I automatically create these objects with like default values and such. Initially this was my code to do so: for name in User.objects.all().values_list('username', flat=True): if name not in Player.objects.all().values_list('player_name', flat=True): new_player = Player(player_name=name, current_level_no=None, no_of_moves=None) new_player.save() else: pass But this would give me a DatabaseIntegrityError that "Models aren't loaded yet". So I am confused about what to do or how to go forward. As always, I greatly appreciate all answers! -
Django POST error: tuple has no attribute get, despite similar code working previously
I'm working on a page that autofills an html dropdown with data from a Django model, then on submit, sends that data to another page that will do things with it. I have the html dropdown populated, but am having issues POSTing to another page. I keep getting "AttributeError at /battleSim/ 'tuple' object has no attribute 'get' as my error despite similar code working in my characterCreator template. I get this error as soon as I attempt to navigate to battleSim.html on the development server, despite the fact it shouldn't be trying that until a POST method runs. (I think?) Below is the relevant code: views.py: class CharacterCreatorView(TemplateView): template_name = "characterCreator.html" # this solution courtesy of Eliakin Costa on StackOverflow: https://stackoverflow.com/a/59112612/12352379 def post(self, request, *args, **kwargs): userID = 'testUser' addCharacter( userID, str(request.POST.get('characterName')), str(request.POST.get('race')), str(request.POST.get('class')), str(request.POST.get('strength')), str(request.POST.get('dexterity')), str(request.POST.get('constitution')), str(request.POST.get('intelligence')), str(request.POST.get('wisdom')), str(request.POST.get('charisma')) ) return render(request, self.template_name, {}) class battleSimView(TemplateView): template_name = "battleSim.html" def get(self, request, *args, **kwargs): character = characterTable.objects.all() # use filter() when you have sth to filter ;) monster = monsterTable.objects.all() return render(request, self.template_name, {'characters':character, 'monsters':monster},) def post(self, request, *args, **kwargs): if(request.method == "POST"): characterID = str(request.POST.get('character_id')) monsterID = str(request.POST.get('monster_id')) return(render(request, template_name ="battle.html"), {'characterID': characterID, 'monsterID': monsterID},) battleSim.html form: <div … -
Highcharts graph not displaying in Django template html
I am making a website using Django/python/sqlite3. I am also using the ebay-python-sdk to query ebay database and get back information based off of keywords. I am trying to convert the timestamp into milliseconds and pass those values into a Highcharts x-axis, and the final sell price of the item to the y-axis. The graph is not displaying in the Django template (called 'graphs.html'). My code is below: display_graphs/views.py from django.shortcuts import render from ebaysdk.finding import Connection as finding import xmltodict from json import loads, dumps import pandas as pd import datetime import matplotlib.pyplot as plt import io from matplotlib.backends.backend_agg import FigureCanvasAgg from django.http import HttpResponse content_df = pd.DataFrame() def display_the_graphs(request): keywords = request.POST.get('search') api = finding(appid='JohnHein-homepage-PRD-392e94856-07aba7fe', config_file=None, siteid='EBAY-US') api_request = {'keywords':keywords, 'itemFilter':[{'name':'SoldItemsOnly', 'value':True},]} response = api.execute('findCompletedItems', api_request) content = response.content xml_dict = xmltodict.parse(content) content_dict = to_dict(xml_dict) count = content_dict['findCompletedItemsResponse']['searchResult']['@count'] item_dict = content_dict['findCompletedItemsResponse']['searchResult']['item'] print('count:', count) content_df = extract_values(item_dict) x_values = content_df['endPrice'].tolist() y_values_b = content_df['endTime'].tolist() y_values = convert_datetime(y_values_b) context = { 'response': content_df.to_html(), 'content_df': content_df, 'x_v': x_values, 'y_v': y_values } return render(request, 'display_graphs/graphs.html', context) ''' def get_time_graph(request): fig, ax = plt.subplots() ax.set_title('Scatter plot of prices over time') ax.set_xlabel('dates') ax.set_ylabel('sell prices') ax.scatter(content_df.endDate.values, content_df.endPrice.values, s=10, label='sell prices over time') canvas = FigureCanvasAgg(fig) buf … -
How to add two fields of django model and save the sum in another field?
class example(models.Model): var1 = models.IntegerField(default=0) var2 = models.IntegerField(default=0) var3 = models.IntegerField(default=0) sum = var1 + var2 + var3 Can anyone help me to save the sum of the three field and save it in the sum field of the model? -
How do I fix Django changes made outside of my virtual environment?
I am new to Django and new to the virtualenv scene. I have been working on a Django project for a couple of days and completely forgot to activate my venv on my second day. I am using this tutorial to guide me and I have been working from within my activated environment up until this point.... Is it enough to just re-run manage.py after activating my venv? -
Simple operations with data requested from a Django model
I am trying to write a simple web application, where i can upload csv files and return the headers from each file. Everything is working fine. The id, the path to the file, gets saved in a database. This is the response i am getting: { "id": 1, "filefield": "http://127.0.0.1:8000/api/merged/1/uploads/header_body_test_zZr4Cea.csv" } What i do not understand is, where or how can i actually work with the data i request from the database? What i am imagining is a different url route, where i can specify an id and the response would be something like this: { "id": 1, "filefield": "http://127.0.0.1:8000/api/merged/1/uploads/header_body_test_zZr4Cea.csv" "headers_of_csv": "Date;Amount" } Its hard for me to explain (or google) what my problem actually is. I dont understand where or how the code to do this would actually be (is it part of the serializer, or the view, or in the model?). Or even in simpler terms, lets say i have a model, that had an id and a 3 digit number and returns this: { "id": 1, "number": 567 } How or where could i create a respone like this: { "id": 1, "number": 567 "first_digit_or_number": 5 } Any help is greatly appreciated, i just dont understand what … -
How to use crud operation in django?
I facing the issue in the Django crud operation. I tried to create a crud operation using Django. All operations are working fine but update operation only is not working. because I tried to click the edit button and show the data in the edit form and also change the data in the form and click the update button in the URL is changing this type (http://localhost:8000/show/6/update/6) . I need this URL (http://localhost:8000/update/6). I tried many ways but I could not get an error where is occurred.any one can run my code and give comments. How to solve this issue. Project urls.py from django.contrib import admin from django.conf.urls import url,include urlpatterns = [ url('admin/', admin.site.urls), url(r'^',include('olcapp.urls')) ] Application urls.py from django.conf.urls import url from olcapp import views urlpatterns = [ url(r'^$',views.get), url(r'^post/$',views.post), url(r'^show/([0-9]+)/$',views.getId), url(r'^update/([0-9]+)/$',views.update,name='update'), url(r'^delete/([0-9]+)/$',views.delete), ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import CrudOperation from .forms import CrudForm # Create your views here. def get(request): form = CrudForm() data = CrudOperation.objects.all() return render(request,'index.html',{'form':form,'data':data}) def getId(request,id): form = CrudForm() data = CrudOperation.objects.get(id=id) return render(request,'edit.html',{'form':form,'data':data}) def post(request): form = CrudForm(request.POST) if form.is_valid(): form.save() return HttpResponse('<h1>post Method</h1>') def update(request,id): print(id) data = CrudOperation.objects.get(id=id) form = CrudForm(request.POST,instance=data) if(form.is_valid()): form.save() … -
How to properly serialize a Django querySet into json format
I use a QuerySet to fetch data from PostgreSQL database in Django. To serialize the returned Object into json I use the built-in from django.core import serializers. Estimated Outcome: Get a json object to work with Issue: Though the object doesn't look that bad (like the example in the docs), it seems I end up with a str rather than a json format. def getAccountInfo(): account_information = serializers.serialize('json', AccountInformation.objects.all()) print(account_information) print(type(account_information)) profit = account_information[2].fields[0].account_information print(profit) return HttpResponse() getAccountInfo() Print: [{"model": "Dashboard.accountinformation", "pk": "30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f", "fields": {"version": "1.00", "accountNumber": 1925323, "broker": "Activtrades Plc", "leverage": "100", "account_balance": 99943.49, "account_profit": -245.4, "account_equity": 99698.09, "account_margin": 328.59, "account_margin_free": 99369.5, "account_margin_level": 30340.73, "account_currency": "EUR"}}, {"model": "Dashboard.accountinformation", "pk": "8b46c7c7-1bc8-4736-8dc5-7d5f012d594b", "fields": {"version": "1.00", "accountNumber": 1925323, "broker": "Activtrades Plc", "leverage": "100", "account_balance": 99943.49, "account_profit": -247.42, "account_equity": 99696.07, "account_margin": 328.59, "account_margin_free": 99367.48, "account_margin_level": 30340.11, "account_currency": "EUR"}}] <class 'str'> Traceback (most recent call last): File "C:/Users/Jonas/Desktop/Dashex/Dashex/Dashex/urls.py", line 28, in <module> from Dashboard.views import getAccountInfo File "C:\Users\Jonas\Desktop\Dashex\Dashex\Dashboard\views.py", line 22, in <module> getAccountInfo() File "C:\Users\Jonas\Desktop\Dashex\Dashex\Dashboard\views.py", line 17, in getAccountInfo profit = account_information[2].fields[0].account_information AttributeError: 'str' object has no attribute 'fields' Process finished with exit code 1 Human-eye-version of account_information object: -
Django: return count of items after filter is applied in ListView
I want to render the total items for a filtered queryset. I've a model UnitaryProduct and I can return the total of items with: context['total_stickers'] = UnitaryProduct.objects.all().count() Inside get_context_data, but I wouldlike to also return the particular amount of items when users apply a filter by category. This is how I filter items based on user selection: This is the ListView, get_queryset I've a condition to use the captured filter_val: class CatalogoListView(ListView): model = UnitaryProduct template_name = "shop/catalogo.html" paginate_by = 10 def get_queryset(self): filter_val = self.request.GET.get('filtro', 'todas') order = self.request.GET.get('orderby', 'created') if filter_val == "todas": context = UnitaryProduct.objects.all().filter(available=True).order_by('-created') return context else: context = UnitaryProduct.objects.filter( subcategory2=filter_val, ).filter(available=True).order_by('-created') return context def get_context_data(self, **kwargs): context = super(CatalogoListView, self).get_context_data(**kwargs) context['filtro'] = self.request.GET.get('filtro', 'todas') context['orderby'] = self.request.GET.get('orderby', 'created') context['category'] = Category.objects.get(slug="catalogo") context['total_stickers'] = UnitaryProduct.objects.all().count() return context I've tried to put add stickers_por_categoria to the queryset but nothing gets rendered in template: def get_queryset(self): filter_val = self.request.GET.get('filtro', 'todas') order = self.request.GET.get('orderby', 'created') if filter_val == "todas": context = UnitaryProduct.objects.all().filter(available=True).order_by('-created') return context else: context = UnitaryProduct.objects.filter( subcategory2=filter_val, ).filter(available=True).order_by('-created') context['stickers_por_categoria'] = UnitaryProduct.objects.filter( subcategory2=filter_val, ).filter(available=True).order_by('-created').count() return context template: <div class="margin-bottom5"> <h2> Actualmente contamos con {{ total_stickers }} stickers en nuestro catálogo</h2> <span>Revisa todos utilizando nuestro filtro por categoría y … -
Files getting erased whenever i run deployment
whenever i run a new deployment on heroku, all already uploaded files will be removed, It's a Django application which i deployed on heroku through my github repository, please how can i stop this from happening? Any help will be appreciated. -
Django - What are the advantages and disadvantages of using unique_togueter vs. using a queryset in the view?
Suppose we have the next model: class Publications(models.Model): author = .......... post = .......... and we don't want duplicate records to be stored in the database. This could be done with unique togheter on the model: Meta: unique_together = (author, post) or it could be done in the view with something like: register_exist = Publications.objects.filter(...).exists() if register_exist == False: #Code to save the info What are the advantages or disadvantages of using these methods? -
Django 2.2.6 (Python 3.6) + Apache + Ubuntu 18.04.3 error
I made a django project and I tried deploying it with apache and wsgi, however I'm getting the following error in error.log: Current thread (most recent call first): [Wed Dec 04 17:14:02. 2019] [core:notice] [pid :tid ] AH00051: child pid 27347 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' I'm using python 3.6.9, I've installed every necessary library using pip3 and I've installed ibapache2-mod-wsgi-py3 using apt. This is my mysite.conf in /sites-available WSGIPythonHome /var/www/projectenv/lib/python3.6 WSGIPythonPath /var/www/projectenv/bin/python3 WSGIScriptAlias / /var/www/project/project/project/wsgi.py <VirtualHost *:80> # adjust the following line to match your Python path <directory /var/www/project/site> <Files wsgi.py> Require all granted </Files> </directory> </VirtualHost> Django 2.2.6 is only compatible with python 3, so I'm not sure what to do. I'm not married to the idea of using apache, so if you have any recommendations for other webservers, that will serve as well. Thanks! -
Ajax returns 500 Internal server error but there is no error in django rest framework api request
This is my Ajax requesting function: function updateAPI(key, bool) { console.log(key, bool) console.log('updating...') var data = { 'completed': bool } var url = '/api/todo/' + key + '/update' console.log(url) console.log(data) $.ajax({ url: url, method: 'POST', data: JSON.stringify(data), dataType: 'application/json', success: function (data) { console.log('SUCCESS') console.log(data) }, error: function (data) { console.log('ERR') console.log(data) }, }) } But when i send request manually djangorestframework is working fine. What is the wrong did i do? -
What is the correct way to get translations from Django's *.po/mo files?
Currently I activate each language and then use ugettext but it looks ugly. from django.conf import settings from django.utils.translation import activate, ugettext # settings.LANGUAGES looks like: settings.LANGUAGES = [ ('en', 'English'), ('ru', 'Russian') ] class Profile(models.Model): ACTIVE = 1 INACTIVE = 2 CLOSED = 3 PROFILE_STATUS_CHOICES = ( (ACTIVE, _('Active')), (INACTIVE, _('Inactive')), (CLOSED, _('Closed')), ) def choices_serialize(choices): """ Convert choices to format suitable for Front End's tree-select. :param choices: :return: [{'id': 1, 'text': {'en': 'Active', 'ru': 'Действующий'}}, {'id': 2, 'text': {'en': 'Inactive','ru': 'Недействующий'}}, {'id': 3, 'text': {'en': 'Closed', 'ru': 'Закрыт'}}] """ data = {} for lang in [t[0] for t in settings.LANGUAGES]: activate(lang) for choice in choices: data.setdefault(choice[0], {}) data[choice[0]].setdefault(lang, ugettext(choice[1])) return [{'id': k, 'text': v} for k, v in data.items()] choices_serialize(Profile.PROFILE_STATUS_CHOICES) Is there a better approach? -
Parse Data into HTML Bootstrap modal (Django)
I have downloaded a bootstrap theme. In one of the HTML documents there is a modal. Basically a Popup that contains like a detail page. My question is how I can parse data into that detail page from the specific object I tapped. So some kind of id. Before I used to have the detail page on a separate page. Through a URL I did this: {% url 'URL' object.id %}. This is a part of the modal and lets say I want to change the modal-title depending on the object.id: <div class="modal modal-task" id="task-modal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Create Brand Mood Boards</h5> This is the loop of cards, all with different urls: When I tap one the detail pop-up shows. And I want the data of that card inside the pop-up. like a detail view: <div class="modal modal-task" id="task-modal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Create Brand Mood Boards</h5> Here are the cards: This is the pop-up: -
How to require dependent drop down whenever there are options to choose from in Django?
I have a form with a dependent drop-down. Currently, I have it set so that the second drop-down only appears if there are options available in it, otherwise is hidden. What I am having trouble with is that, whenever you choose a primary(Work Area) option that has a secondary(Station) drop-down, you can submit the form without having selected an option from the dependent (secondary) drop-down, which is supposed to be required whenever there are options in it. How can I modify this so that the dependent drop-down is required whenever it appears? models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Station(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE, related_name="stations") name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = Station.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = Station.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name') views.py def enter_exit_area(request): enter_without_exit = … -
How to add images and document as sub menu item of common menu item on admin panel in wagtail
I want to remove images and documents from menu in admin panel of wagtail. Create a new menu element and add bother as submenu item in wagtail. Please have any idea about it so help me. Thanks in advance! -
See all the items created by the logged in user
novice here trying to get an ebay style e-commerce project finished! When a user checks their profile, I want it to list all the items they have for sale. The owner in the Item model stores the username, so, essentially, I want to check the owner field of all items, then pull the ones that are == username. Here's the code I got so far: views.py def user_profile(request): """The users profile page""" user = User.objects.get(email=request.user.email) user_items = Item.objects.filter(owner__icontains=request.GET[user]) return render(request, 'profile.html', {"profile": user, "items": user_items}) I'm then using {% for item in user_items %} in the html. Apologies if this is an easy one, but I'm struggling to get this right. -
How do i set session storage on angular from a django token?
There is an application(app A) currently on ground which i want to make an integration(app B) for. App A is developed with Django. App B is going to be developed using Angular. So when a user is already logged in to app A, then he clicks the link to app B, a token should be generated for that user when redirected to App B. i need to store the token in storage and get data like email, username e.t.c. from it. -
Need to capture user pk who is posting a tweet
The problem I'm having is somewhere between my views.py and serializers.py, To start this is the error I'm getting. It happens when I try and create a new tweet. The parameter it is having an issue with is from the views TweetAPIView: perform_create. The TweetSerializers doesn't have a 'user' field but I've also tried setting author=self.request.user The goal is to have this new tweet being posted attached to the user posting it. FYI building basic Twitter functionality with this project. Tweet() got an unexpected keyword argument 'user' Views.py from django.shortcuts import render from django.contrib.auth.mixins import UserPassesTestMixin from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework import status from rest_framework.response import Response from rest_framework import generics, mixins from .models import Tweet, User from .serializers import TweetSerializer from .permissions import IsOwnerOrReadOnly class TweetAPIView(generics.CreateAPIView, mixins.CreateModelMixin): lookup_field = 'pk' serializer_class = TweetSerializer def get_queryset(self): return Tweet.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) Models.py class User(AbstractUser): email = models.EmailField(verbose_name='email', max_length=255, unique=True) REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] USERNAME_FIELD = 'email' def get_username(self): return self.email class Tweet(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="tweets") tweet_text = models.CharField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet_text Serializers.py class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): …