Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running python IBM Cloud Apps Cloud Foundry with error in ModuleNotFoundError: No module named 'matplotlib'
After deployment in IBM Cloud - App Cloud Foundry using Python - Django I found the follow error running the container: APP/PROC/WEB 0 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "<frozen importlib._bootstrap_external>", line 678, in exec_module 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "<frozen importlib._bootstrap>", line 665, in _load_unlocked 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 callback, param_dict = resolver.resolve_error_handler(500) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 141, in handle_uncaught_exception 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 103, in response_for_exception 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = response_for_exception(request, exc) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 49, in inner 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = self._middleware_chain(request) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in get_response 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 response = self.get_response(request) 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 File "/home/vcap/deps/0/python/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ 13 de mar. de 2021 10:43:24 APP/PROC/WEB 0 respiter = self.wsgi(environ, … -
create a model in django with conditions
I want to create an appointments model with Django, but with 2 conditions the first if the profile already exists than the appointments model use the information from the profile model, but if the profile dose doesn't exist than the user should fill the information in the appointments model this is my profile model class Profile(models.Model): GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) phone_number = PhoneNumberField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) def __str__(self): return f'Profile for user {self.user.username}' and this is my appointments model class Appointments(models.Model): GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) profile = models.OneToOneField(Profile, on_delete=models.CASCADE)# if profile dose not exist this will be none date_of_birth = models.DateField(blank=True, null=True)# and the user should fill this information gender = models.CharField(max_length=1, choices=GENDER_CHOICES) # and the user should fill this information phone_number = PhoneNumberField(blank=True)# and the user should fill this information date_time = models.DateTimeField() so if the one who wanted to make the appointments have already a profile the information about the gender and date of birth come from his profile if there is no profile the user should be fill those information -
Allowing user to rename the django model field names visible to him
I have a model like below. I want the user to be able to change the "external" field names (i.e. what is visible to the user) using some form of Legend (the internal field names should be the same: Product.rating1 should not change). The user opens the Product form he sees the default name of the fields (e.g. 'Rating 1' is called 'Rating 1'). But the user should be able to change this in a different form (e.g. 'Rating 1' to 'Some random name'). This new rating name should now be changed for all Products. class Product(models.Model): name = models.CharField(max_length=200) rating1 = models.IntegerField(default=0) rating2 = models.IntegerField(default=0) rating3 = models.IntegerField(default=0) class Legend(models.Model): rating1_name = models.CharField(max_length=200, default='Rating 1') rating1_abbr = models.CharField(max_length=2, default='R1') rating2_name = models.CharField(max_length=200, default='Rating 2') rating2_abbr = models.CharField(max_length=2, default='R2') rating3_name = models.CharField(max_length=200, default='Rating 3') rating3_abbr = models.CharField(max_length=2, default='R3') Desired result: The Product's database table will contain several products. However, the database table of Legend will just contain one entry that is created from the start (automatically) and it will never be deleted, the fields will just be changed. What I want is basically to in one place of my app have a form that creates these Products and another form … -
why do developers still create separate dashboard for login to perform CRUD functions instead of using the inbuilt Admin that is shipped by Django
I am a novice in Django I am just wondering why most developers would create separate dashboards to login and logout to perform all the CRUD functions. Why go through all that trouble instead of using the shipped Admin panel and create your users and assign permissions/roles to them to perform basically all the CRUD functions. -
Extract only the last 7 days of data in Python
If I have such data and I want to extract only the last 7 days of data, how can I do that? I tried to use Pandas examples, but I got errors such as module 'pandas' has no attribute 'example' or 'list' object has no attribute 'example', so I could not get the data for seven days. Also, I'm using React for the frontend. When processing data like this, is it best to do it on the frontend side or the backend side? "daily_report": [ { "date": "2020/03/27", "count": 999 }, { "date": "2020/03/28", "count": 0 }, { "date": "2020/03/29", "count": 0 }, { "date": "2020/03/30", "count": 0 }, { "date": "2020/03/31", "count": 0 }, { "date": "2020/04/01", "count": 0 }, { "date": "2020/04/02", "count": 0 }, { "date": "2020/04/03", "count": 0 }, { "date": "2020/04/04", "count": 0 }, { "date": "2020/04/05", "count": 0 }, { "date": "2020/04/06", "count": 0 }, { "date": "2020/04/07", "count": 0 }, { "date": "2020/04/08", "count": 0 }, { "date": "2020/04/09", "count": 0 }, { "date": "2020/04/10", "count": 0 }, { "date": "2020/04/11", "count": 0 }, { "date": "2020/04/12", "count": 0 }, { "date": "2020/04/13", "count": 0 }, ] def get_daily_report(self, obj): data = Entry.objects.all().values( … -
how do I send a text field input from the frontend to the backend
I have made a website, it uses react as the frontend and Django as the backend. I am trying to get an input from the frontend and send it to the backend, it doesn't seem to be working. here's the code: searchSong(e) { this.setState({ search: e.target.value }); console.log(this.state.search) } this is what takes the text field input : <TextField id="outlined-basic" label="Song" variant="outlined" value={this.state.search} onChange={this.searchSong} /> <Button variant="contained" color="secondary" onClick={this.addButtonPressed}>Search Song</Button> these are the functions that send the text input from the frontend to the backend and the states : addButtonPressed() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ search: this.state.search, }) }; fetch("/spotify/search-song/", requestOptions) } } searchSong(e) { this.setState({ search: e.target.value }); console.log(this.state.search) } the state : this.state = { search: "" } here's the function that I made which will test if I got the correct text field input : def search_song(session_id, song_name): search_letters = "playlist/?type=" + song_name print(search_letters) this is the view that uses the function : class SearchSong(APIView): lookup_url_kwarg = 'search' def post(self, request, format=None): if not request.session.exists(request.session.session_key): request.session.create() room_code = self.request.session.get(self.lookup_url_kwarg) music = str(request.data.get(self.lookup_url_kwarg)) room = Room.objects.filter(code=room_code)[0] search_song(room.host, music) this is the endpoint being called by the frontend : from … -
Django custom registration form html
New to Django and I am attempting to create a customer registration form and was successful. However the tutorial I followed showed me how to iterate through a loop, the contents of my registration_form which doesn't really give me much flexibility from a UI perspective, or so it seems. Can someone tell me how to customize this form based on the code I've got? HTML: <h1>This is the register.html</h1> <div class="col-md-4 offset-md-4"> <form method="post"> {% csrf_token %} {% for field in registration_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color: grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: grey;">{{error}}</p> {% endfor %} </p> {% endfor %} <button type="submit">Register</button> </form> </div> views.py def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form print(context) return render(request, 'accounts/register.html', context) forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=100, help_text='Required. Add a valid email address') class Meta: model = Account fields = ('email', 'username', 'password1', 'password2', 'first_name', 'last_name') the form renders and works fine with registration, just looks kinda crappy. thanks! -
Changing language with React Native and django-modeltranslation
I would like to add option to mobile app to change language. Im using django on backend and RN as mobile. So I installed django-modeltranslation and added my model I want to translate. On mobile I display available languages. When user clicks on specific language I would like to get translated data. I have huge problem to create logic how to do it. I'm not asking about code just some hints and idea -
Make a dang form field read only after initialised
I have a ModelForm in forms.py as follows: class OrderDetailForm(forms.ModelForm): class Meta: model = OrderDetails fields = ( 'OrderID', 'ProductCode', 'Location', 'UnitPrice', 'Quantity', 'Discount', ) def __init__(self, *args, **kwargs): super(OrderDetailForm, self).__init__(*args, **kwargs) locations = self.initial['ProductCode'].productqtys_set.values_list('Sublocation', flat=True) locationslist = list(locations) locationsQueryset = SubLocations.objects.filter(id__in=locationslist) print("locations queryset in form") print(locationsQueryset) self.fields['Location'].queryset = locationsQueryset In my views.py I have the function that uses it: def AddOrderDetail(request, pk): Product = Products.objects.get(ProductID=pk) order = Orders.objects.last() locations = Product.productqtys_set.all() if request.method == "POST": form = OrderDetailForm(request.POST, initial={"ProductCode": Product, "OrderID": order}) if form.is_valid(): form.save() return redirect('orders:subslistCreate') else: form = OrderDetailForm(initial={"ProductCode": Product, "OrderID": order}) template_path = 'orders/orderdetail_form.html' context = { "form": form, } return render(request, template_path, context) now as you can read, I initialised the ProductCode and OrderID fields, of course when it's time to fill in data for the other fields, the user can edit the values in ProductCode and OrderId. I don't want the user to be able to do that. I tried setting disabled to True but that didn't allow me to initialise the fields anymore, and I also tried to set readonly to true by adding the following lines in the definition of the init function: self.fields['OrderID'].widget.attrs['readonly'] = True self.fields['ProductCode'].widget.attrs['readonly'] = True sadly that changed … -
Server Error (500) arised on django project
My Project is a website is 'learning_log' same as in the book Python Crash Course. Learning Log works fine in local machine but when I go out of local machine it shows Server Error (500). I used heroku to deploy it and renamed it 'trak-your-learnin' you can go to https://trak-your-learnin.herokuapp.com/ to view the error page. I've posted some important file so you can easily figure out the error; sorry i've posted too much code. This deploying process is really difficult for a beginner so hmp. settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3kiqlq&v(^09b5ba3xp1krc#z0uu_2ji=eqe7t=cb)-n-^^%bz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ '*', 'https://warm-taiga-24464.herokuapp.com/', '127.0.0.1', ] # Application definition INSTALLED_APPS = [ # My apps 'learning_logs', 'users', # Third party apps. 'bootstrap4', # Default django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': … -
Django Two Databases: Default User Auth + Legacy Database
I want to put all of the default Django authentication backend on a separate database from my legacy database. I created a new database named 'AUTH_DB' and ran the migration. As expected, it put all of the tables (auth, admin, contenttypes, sessions, etc.) on AUTH_DB. However, now I am only able to render my login.html page. After I attempt to login, I receive a connection does not exist error. I'm having trouble understanding The connection 'auth' doesn't exist at / DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'AUTH_DB', 'USER': '', 'PASSWORD': '', 'HOST': 'lvn-gc.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server' }, }, 'data_db': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'CRM', 'USER': '', 'PASSWORD': '', 'HOST': 'lvn-gc.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server' }, }, } DATABASE_ROUTERS = ['CRM.routers.DataRouter'] In CRM/routers.py class DataRouter: db_apps = ( 'CRM' ) def db_for_read(self, model, **hints): if model._meta.app_label in self.db_apps: return 'data_db' return model._meta.app_label def db_for_write(self, model, **hints): if model._meta.app_label in self.db_apps: return 'data_db' return model._meta.app_label def allow_relation(self, obj1, obj2, **hints): return True def allow_syncdb(self, db, model): if model._meta.app_label in self.db_apps: return db == 'data_db' return False Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/ Django … -
Django Templates Formsets with Foreign Key Lookup
hoping for some guidance around my below problem with displaying reverse lookup field in a template inside formsets. Maintenance Item Model class Maintenance_Item(CommonInfo): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) name_description = models.CharField(max_length=255) is_active = models.BooleanField(default=True) def __str__(self): return self.name Checklist Model class MaintenanceCheckList(CommonInfo): CHOICES = ( ('P','Compliant'), ('F','Non-Compliant'), ) id = models.AutoField(primary_key=True) item = models.ForeignKey(Maintenance_Item, on_delete=PROTECT, related_name='item_name') is_compliant = models.CharField(max_length=20, choices= CHOICES, default=CHOICES[0][0]) def __int__(self): return self.item The current template <form class="" method='post'> {% csrf_token %} {{ form.management_form }} <table class="table my-0" id="dataTable"> <thead> <tr> <th>Maintenance Items</th> </tr> </thead> <tbody> {% for sub_form in form %} <tr> {% for i in sub_form.item_name.all %} <td>Item: {{ i.name }}</p> {% endfor %} {{ sub_form.item|add_class:"form-select" }}<p> </p>{{ sub_form.is_compliant }}</td> </tr> {% endfor %} </table> <div class="divider"></div> <div class="col-md-12"> <p class='pt-sm-2'> <button type="submit" class="btn btn-primary">Submit</button> </form> Currently, I have generic formset view which creates an row for each item in the Maintenance_Item which works brilliant and generates the formset view as shown. The challenge, I have is I want to hide the ModelChoice fields (I can do that easily with a Widget), and just display the friendly name in the ModelChoice field as a simple Text Label in the template. Note setting disabled … -
Django 'dict' object has no attribute '_mutable'
I am testing Django Rest Framework code with Postman I called http://127.0.0.1:8000/api/users/1/documents/ But received error message 'dict' object has no attribute '_mutable' What is the right way to create request via Postman? (it seems that problem with postman) I read this topic, but didn't find solution DRF request.data has no attribute _mutable My code class UserDocumentCreate(generics.CreateAPIView, generics.RetrieveAPIView): serializer_class = UserDocumentSerializer permission_classes = (UserIsOwner, IsAuthenticatedDriver) queryset = Document.objects.all() def get_serializer_class(self): if self.request.version == "1.0": return UserDocumentSerializer def create(self, request, *args, **kwargs): request.data._mutable = True request.data["owner"] = kwargs.get("pk") serializer = self.get_serializer(data=request.data) ... -
Why does django print the traceback of an exception even though I catch it?
I'm creating a django web app and am currently in the process of writing tests for it. I want to check that my URL paths are working. In order messages that clutter the screen when testing, I tried catching the exceptions that get thrown, but this doesn't seem to work. Here's my method where I'm testing the path of the home URL: def test_home(self): path = '/' try: response = self.client.get(path) except Exception: assert False, ("There seems to be a problem with the view corresponding to the path", path) self.assertEqual(response.status_code, 200, ("Couldn't load page with page", path)) And this is the output: <a lot more exceptions> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 395: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/Documents/project/project/app/tests/test_urls.py", line 16, in test_home response = self.client.get(path) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 395: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/Documents/project/project/app/tests/test_urls.py", line 18, in test_home assert False, … -
Django AllAuth URL patterns configuration
I created a sample view to display the detail of the user. In my project, I have 2 apps, the Accounts that contain all the details of the user and the Core for the web application. I've done configuring the Django AllAuth for Google Login and here is the outcome. Models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField(max_length=254, null=True, blank=True) member_since = models.DateTimeField(auto_now_add=True) phone_number = PhoneNumberField(null=True, blank=True) street_address = models.CharField(max_length=50, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) zip_code = models.IntegerField(null=True, blank=True) slug = models.SlugField(null=True, blank=True, unique=True) def __str__(self): return str(self.first_name) def get_phone_number(self): return self.phone_number @property def get_full_address(self): return f"{self.street_address}, {self.city}, {self.country}, {self.zip_code}" @receiver(user_signed_up) def populate_profile(sociallogin, user, **kwargs): user.profile = Profile() user_data = user.socialaccount_set.filter(provider='google')[0].extra_data first_name = user_data['given_name'] last_name = user_data['family_name'] email = user_data['email'] user.profile.first_name = first_name user.profile.last_name = last_name user.profile.email = email user.profile.save() def get_absolute_url(self): return reverse("profile", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify("{obj.first_name}-{obj.last_name}".format(obj=self)) super(Profile, self).save(*args, **kwargs) Views.py class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile template_name = 'accounts/profile.html' Accounts Urls.py app_name = 'accounts' urlpatterns = [ path('profile/<slug>', ProfileDetailView.as_view(), name='profile') ] Main Urls.py from django.contrib import admin from django.urls import path, include urlpatterns = … -
template inheritance is not working in my django application
My base.html Template <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <title>MyResume Bootstrap Template - Index</title> </head> <body> {% block content%} {% endblock content%} </body> </html> My content block template {% extends "base.html" %} {% block content %} <h1>hello world</h1> {% endblock content %} I don't know what the issue is kindly help me with a solution -
Page keeps reloading after adding a new channels consumer and route
hope you all are doing well. I have been working on creating an asynchronous notification system, I already have a chat system but it is directed only towards the /inbox/ url. The problem that I'm facing is when I add a new consumer and access the home page the home page keeps reloading again and again and the terminal doesn't show any error. this is what my code looks like: Consumers.py async def websocket_connect(self,event): print("connected",event) await self.accept() async def websocket_receive(self,event): print("received",event) async def websocket_disconnect(self,event): print(event,"closed") class ChatConsumer(AsyncWebsocketConsumer): async def websocket_connect(self,event): print("connected") self.channel_layer = channels.layers.get_channel_layer() ..... await self.accept() async def websocket_receive(self,event): print("received2",event) ..... async def websocket_disconnect(self,event): print("disconnected",event) Routing.py from . import consumers from django.urls import re_path,path websocket_urlpatterns = [re_path(r"^a/inbox/(?P<username>[\w.@+-]+)", consumers.ChatConsumer.as_asgi()), re_path(r"a/(?P<username>[\w.@+-]+)",consumers.NotificationConsumer.as_asgi()), ] I'm trying to create a notifications websocket, any leads or any correction would be much appreciated. -
How do i find one tag with multiple text Content with Beautifulsoup
Am trying to scrap a website with multiple 'p' tags with beautifulsoup and I find it very difficult. please I need help. I want to get all posts associated with p tags. the find_all on beautifulsoup will not get this done and the image is not saving I get an error that the file cannot be saved and tell me how to retrieve, add or scrap all the text in p tags and the image on the HTML code below. Can you check out my code below kompas = requests.get('https://url_on_html.com/') beautify = BeautifulSoup(kompas.content,'html5lib') news = beautify.find_all('div', {'class','jeg_block_container'}) arti = [] for each in news: title = each.find('h3', {'class','jeg_post_title'}).text lnk = each.a.get('href') r = requests.get(lnk) soup = BeautifulSoup(r.text,'html5lib') content = soup.find('p').text.strip() images = soup.find_all('img') arti.append({ 'Headline': title, 'Link': lnk, 'image': 'images' }) let's take this HTML code as a scrapping sample <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p>Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <script></script> <p>the emergency of our matter is Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <p> … -
Displaying checked and unchecked ManyToMany choices in DetailView
I'm looking for an elegant way to show all available items (not just checked ones) in a Django DetailView, while stylizing the checked ones. Given following model: class Topping(models.Model): title = models.CharField(max_length=200) class Pizza(models.Model): topping = models.ManyToManyField(Topping, blank=True, null=True) I'm rendering toppings in my form with a CheckboxSelectMultiple (=rendered as multiple checkboxes), like: toppings = forms.ModelMultipleChoiceField( required=False, queryset=Toppings.objects.all(), widget=forms.CheckboxSelectMultiple, ) It is also relevant which toppings were not selected, hence I'd like to render something in my DetailView like the following (showing a checked checkbox when selected; showing an empty checkbox and light gray text when not selected, respecting the same order as seen in the form, i.e. alphabetically in this example): Chosen pizza toppings: ☑ Bluecheese ☐ Green peppers ☐ Onions ☑ Red peppers I currently go through the toppings as follows, but this only shows the selected ones: {% for option in object.toppings.all %}☑ {{ option }}<br />{% endfor %} I have a whole bunch of different ManyToManyFields on my main model. -
No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it
After hosting my Django application on Heroku while I try to download dynamic pdf my Django app's wkhtmltopdf causes this error. In local machine(Ubuntu) I've applied sudo apt-get install wkhtmltopdf I've also added Aptfile with my project directory so that Heroku installs those dependency and requirements while building the application. Aptfile: wkhtmltopdf But unfortunately Heroku don't even builds the app with the given dependency. I've also tried to install it by running Heroku bash but Heroku prevents. W: Not using locking for read only lock file /var/lib/dpkg/lock-frontend W: Not using locking for read only lock file /var/lib/dpkg/lock E: Unable to locate package wkhtmltopdf My code for generating pdf is: def pdf_generation(request, pk): ''' Will generate PDF file from the html template ''' template = get_template('bankApp/print_view.html') withdraw_obj = get_object_or_404(Withdraw, id=pk) year_month_day = withdraw_obj.withdrawn_on.split('-') day = year_month_day[2] month = year_month_day[1] year = year_month_day[0] word_amount = f'{num2words(withdraw_obj.withdrawn_amount)} Only' date = f'{day}{month}{year}' html = template.render({ 'pay_to': withdraw_obj.paid_to, 'date': date, 'amount': withdraw_obj.withdrawn_amount, 'amount_word': word_amount }) options = { 'page-size': 'A4', 'margin-top': '0.0in', 'margin-right': '0.0in', 'margin-bottom': '0.0in', 'margin-left': '0.0in', 'encoding': 'UTF-8', } pdf = pdfkit.from_string(html, False, options=options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment;\ filename="print.pdf"' return response Server Error: OSError at /bank/pdf/print/2 No wkhtmltopdf executable found: … -
Unable to save multiple value with Select2 in Django
I try to post multiple value selected from ajax response. But when I specify name of 'Select' tag as array - <select name="item_ids[]" nothing is saved. I use Select2 v 4.1.0 But if I set name="item_ids" without array brackets and choose 2 or more values, only last selected value is saved. For now it's an array field in the model but may be a char filed should be. models.py class Selected_items(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') item_ids = ArrayField(models.CharField(max_length=100), blank=True) file.html <select multiple="multiple" type="text" name="item_ids[]" class="form-control" autocomplete="off" required></select> forms.py class UserItemForm(forms.ModelForm): class Meta: model = Selected_items fields = ('item_ids',) def save(self, commit=True): selected_items = super(UserItemForm, self).save(commit=False) selected_items.item_ids = self.cleaned_data['item_ids'] if commit: selected_items.save() return selected_items views.py if request.POST and 'btn_save_user' in request.POST: form_7 = UserProfileForm(request.POST, instance=Profile.objects.get(user=user)) form_8 = UserItemForm(request.POST, instance=Selected_items.objects.get(id=user_id)) if form_7.is_valid() and form_8.is_valid(): form_7.save() form_8.save() return redirect('user-page') Please, help to resolve it. -
How to pass the customer id dynamically in the tap payment method to save the card value
** I and sending the post request to the TAP PAYMENT Gateway in order to save the card, the url is expecting two parameters like one is the source (the recently generated token) and inside the url the {customer_id}, I am trying the string concatenation, but it is showing the error like Invalid JSON request. ** ifCustomerExits = CustomerIds.objects.filter(email=email) totalData = ifCustomerExits.count() if totalData > 1: for data in ifCustomerExits: customerId = data.customer_id print("CUSTOMER_ID CREATED ONE:", customerId) tokenId = request.session.get('generatedTokenId') payload = { "source": tokenId } headers = { 'authorization': "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ", 'content-type': "application/json" } *HERE DOWN IS THE url of TAP COMPANY'S API:* url = "https://api.tap.company/v2/card/%7B"+customerId+"%7D" response = requests.request("POST", url, data=payload, headers=headers) json_data3 = json.loads(response.text) card_id = json_data3["id"] return sponsorParticularPerson(request, sponsorProjectId) ** their expected url = https://api.tap.company/v2/card/{customer_id} their documentation link: https://tappayments.api-docs.io/2.0/cards/create-a-card ** Blockquote Blockquote -
Add product according to category in django
I am new in Django. I want to add product against the category which i select, but i don't know how can i do that. I select the category and add product but nothing happened. I don't know how can i do this. Thank u in advance Model.py class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=30) price = models.IntegerField() view.py class SelectCategory(TemplateView): template_name = 'purchase/selectCategory.html' def get(self, request, *args, **kwargs): categories = CategoryModel.objects.all() args = {'categories': categories} return render(request, self.template_name, args) def post(self, request): try: data = self.request.POST.get categoryId = ProductModel.category['category.id'].id product = ProductModel( category_id=data(categoryId), name=data('name'), price=data('price') ) product.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Temaplate {% extends 'auth/home.html' %} {% block content %} <form method="get"> {% csrf_token %} <label> Select Category <select name="Select Category"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value={{ category.id }}> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> </form> <form method="post"> {% csrf_token %} <label for="name">Name <input type="text" name="name" id="name" placeholder="Enter Product name"> </label> <label for="price">Price <input type="number" name="price" id="price" placeholder="Enter Price of Product"> </label> <button type="submit">Submit</button> <button><a href="{% url 'menu' %}">Menu</a></button> </form> {% endblock %} -
getting error cannot read file data: is a directory when making migration in django rest framework
hi i am making an app which takes a users location and compares it with other people to find the distance. When i added a installed gdal geos postgis and proj4 i then added a pointfield from django.contrib.gis.db import then i did a migration and it returned an error of Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/aarush/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/home/aarush/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/aarush/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/aarush/git_fudo/food1_back/food1_back/posts_v1/models.py", line 1, in <module> from … -
Django model with Charfield Count and Zero values
I have a Django database model that has some attributes, one of them is a Charfield 'category' with Choices. I now want to annotate a queryset of this model with the count of the rows of each category. The thing is, the way i know to do it, only categories present in the queryset are getting counted, but i want a queryset with all categories annotated with the count (0 if no rows with this category). This is what im doing at the moment: Model.objects.all().values('category').annotate(total=Count('category')) Is there a way to display all categories, including such with count 0?