Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send messages to django channel(websocket) by channel name
I'm trying to send message in to websocket knowing its channel name. await channel_layer.send( user_channel, { "type": "send", "text_data": json.dumps(message), }, ) But I'm getting error: Exception inside application: 'dict' object has no attribute 'encode' Traceback (most recent call last): File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/routing.py", line 150, in __call__ return await application( File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/generic/websocket.py", line 211, in send await super().send({"type": "websocket.send", "text": text_data}) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/consumer.py", line 81, in send await self.base_send(message) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/daphne/server.py", line 234, in handle_reply protocol.handle_reply(message) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/daphne/ws_protocol.py", line 202, in handle_reply self.serverSend(message["text"], False) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/daphne/ws_protocol.py", line 256, in serverSend self.sendMessage(content.encode("utf8"), binary) AttributeError: 'dict' object has no attribute 'encode' WebSocket DISCONNECT /ws/device_data/new/ [127.0.0.1:36296] Is it possible to send message like this, or I should always implement functions to handle and send messages in consumer class? Because now, when I'm trying to use such functions it works. async def send_message(self, message): # Send message to … -
How to write a v-if condition for comparing django accessed value "{{cust_package}}" and vue.js "<%radio_price%>"
And here I am trying to write if statement and also I have interpolated a value in vue.js like "{{cust_package}}" accessed In django and <%radio_price%> accessed in vue.js for both i am trying to write a if condition like "v-if="radio_price == {{cust_package}}" So this condition is not working so How can we write condition for both django and vue.js. The main issue is i want to write a if condition for both accessed value in django and vue.js I want to compare both the value by using v-if Django backend code return render(request, 'postad.html', {'user_type': user_type, 'cust_package': cust_package, 'package_value': price_value, 'cust_package_ads': cust_package_ads}) from above code I have accessed cust_package into below template. And here I am trying to write if statement and also I have interpolated a value in vue.js like "{{cust_package}}" accessed In django and <%radio_price%> accessed in vue.js for both i am trying to write a if condition like "v-if="radio_price == {{cust_package}}" So this condition is not working so How can we write condition for both django and vue.js <div> <div> <p> <input type="radio" name="price_Ads_package" class="price_1"v-model="radio_price" value="$2.99 - 6 Ads - Month"><span class="radio_price"> $2.99 - 6 Ads/Month</span> </p> <p> <input class="price2" type="radio" v-model="radio_price" name="price_Ads_package" class="price_1" value="$4.99 - 12 … -
CORS issue in Django?
Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'http://localhost:62570' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. I have tried adding django-cors-headers middleware and CORS_ALLOW_ALL_ORIGINS = True and I have also made ALLOWED_HOSTS = ['*'] but still getting same CORS error. I had the same error with NestJS but after adding app.enableCors(); it got resolved. Here is my settings.py file from pathlib import Path BASE_DIR = Path(__file__).resolve(strict=True).parent.parent DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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 = 'basic_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'basic_app.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' # CORS CORS_ALLOW_ALL_ORIGINS = True # CORS_ALLOWED_ORIGINS = [ # "http://localhost:62570", # "https://example.com", # "https://sub.example.com", … -
Django filter an already prefetched query set
I am using Django Rest Framework to get the data I use for the page. The Json is nested and contains a list of cards and their details. This use to create a table of cards on my page. I am trying to create a filter for this table and have manage to get it working if the user was to filter the data for one filter. However if the user wanted to filter by two fields it doesn't work and just filters by the last filter used. I know this is because when the code goes through the if statements I am using a new queryList of data rather than the already filtered queryList. However I cannot seem to filter the queryList. I would like to filter by card name and card type. Json: [ { "id": "e65a10a9-df60-4673-9c2d-3b0966545ac3", "code": "SS3", "keyruneCode": "SS3", "name": "Signature Spellbook: Chandra", "cards": [ { "name": "Chandra, Torch of Defiance", "type": "Planeswalker" }, ... ] } ] view: class SetsIndividualData(ListAPIView): serializer_class = SetSerializers def get_queryset(self): SQL_EXPRESSION = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" setCode = self.kwargs.get('setCode', None) queryList = Set.objects.filter(code=setCode.upper()).prefetch_related( Prefetch('cards', queryset=Card.objects.exclude(side='b').extra(select={'int': SQL_EXPRESSION}).order_by('int', 'number').prefetch_related( Prefetch('inventory', queryset=Inventory.objects.filter(user_id=self.request.user)) ))) name = self.request.query_params.get('name', None) types = self.request.query_params.get('types', None) if name: … -
What service do i need for hosting django (backend) + postgresql (database) on GCP
I want to know what service in Google cloud Platform that i need to deploy my backend django + postgresql ? Im developing a mobile app using flutter. -
Session Expiry Django
The session cookie age is set to five minutes and even after that the session is not getting expired in Django. Do we need to pass the session validity to frontend? The app works with Django (2.1.1) in backend and Angular in frontend. Provided the following details in the settings.py file SESSION_COOKIE_AGE = 5*60 DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions',] -
Django Registration form - first_name and last_name fields showing but data isn't passing to request.POST
I've used the inbuilt UserCreationForm to include email, first_name, and last_name fields. The email field works perfectly. But first_name, last_name fields are not working. They do show up on the front end, but after filling the form they aren't showing up in request.POST (which we use to create the User inside views.py). UserRegistrationForm in forms.py class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(label='First Name',widget=forms.TextInput(attrs={'placeholder': 'First Nameee', 'class':'form-control'}),max_length=150,required=True) last_name = forms.CharField(label='Last Name',widget=forms.TextInput(attrs={'placeholder': 'Last Nameee', 'class':'form-control'}),max_length=150,required=True) email = forms.EmailField(label='Email',widget=forms.EmailInput(attrs={'placeholder': 'Enter your email', 'id':'user_email', 'class':'form-control'}),max_length=50,required=True) username = forms.CharField(label='Username',widget=forms.TextInput(attrs={'placeholder': 'Enter your username', 'id':'user_name', 'class':'form-control'}),max_length=50,required=True) password1 = forms.CharField(label='Password',widget=forms.PasswordInput(attrs={'placeholder': 'Enter your password', 'id':'user_password', 'class':'form-control'}),max_length=50,required=True,help_text='Your password must contain at least 8 characters.') password2 = forms.CharField(label='Confirm Password',widget=forms.PasswordInput(attrs={'placeholder': 'Enter confirm password', 'id':'confirm_password', 'class':'form-control'}),max_length=50,required=True,help_text='Enter the same password as above') class Meta: model=User fields=['first_name','last_name','email','username','password1','password2'] UserRegisterView in views.py class UserRegisterView(View): template_name = 'authentication/auth-register.html' def get(self, request): if 'username' in request.session: return redirect('dashboard') else: return render(request, self.template_name, {'form': UserRegistrationForm}) def post(self, request): if 'username' in request.session: return redirect('dashboard') else: if request.method == 'POST': print(request.POST) first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if username == '': data={} data['error_message'] ='username field is empty' return JsonResponse(data,safe=False) elif email == '': data={} data['error_message'] ='email field is empty' return JsonResponse(data,safe=False) … -
I have issue generating report in Django Rest framework from both product and order
I to generate a report from this below code I have this in my model class Category(models.Model): name = models.CharField(max_length = 255, unique=True) description = models.TextField(blank=True, null=True) slug = models.SlugField(null=True, blank=True, unique=True) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) class Product(models.Model): name = models.CharField(max_length = 200, unique=True) description = models.TextField(blank=True, null=True) slug = models.SlugField(null=True, blank=True, unique=True) image = models.ImageField(upload_to='uploads/', blank=True, null=True) # thumbnail = models.ImageField(upload_to='uploads/thumbnails/', blank=True, null=True) category = models.ForeignKey(Category, related_name="products", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) class Order(models.Model): STATUS_CHOICES = ( ('Pending', 'Pending - Order is made but not delivered yet'), ('Arrive', 'Arrive - Order is made and arrive to store'), ) product = models.ForeignKey(Product, related_name="orders", on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) user = models.ForeignKey('auth.User', related_name='orders', on_delete=models.CASCADE) status = models.CharField(max_length=128, choices=STATUS_CHOICES, default='Pending') shop_name = models.CharField(max_length=255, null=True) total_price = models.DecimalField(max_digits=10, decimal_places=2, null=True) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) I have this in my serializer file class productReportSerializers(serializers.ModelSerializer): category = serializers.SlugRelatedField(queryset=Category.objects.all(), slug_field='name', required=True) class Meta: model = Product fields = "__all__" I want to get the sum of the product by month and group by year and category -
Django Stripe InvalidRequestError: Request req_******: Not a valid URL
I'm using Stripe with django, but while clicking the checkout it return the stripe.error.InvalidRequestError: Request req_N8rlEhXn42Cyxz: Not a valid URL (due to this question, First i tried my localhost:8000/payment/done then tried it using ngrok so that it could be accessible globaly, but still not working). it's my settings.py ..... STRIPE_PUBLIC_KEY = ( "pk_test_51J5kFsFfjIr2jaBwRlGyDJ9McmvvBGclXxkasIGggbh3Fz076sWsGv9z7pSWxy7WuncldIMXDFOq1U3j2bv2Zstu00lMmMnLjD" ) STRIPE_SECRET_KEY = ( "sk_test_51J5kFsFfjIr2jaBwg1Khel6tLkT70gTshaTeIwe0GjqaM57x6XvjZNxQE0udNk8BAVqjjEkCHtFs8KXBEglu2zbR005LkwAzaq" ) STRIPE_WEBHOOK_SECRET = "" and my views.py class CreateCheckOutSessoionView(View): def post(self, request, *args, **kwargs): ng = "https://localhost:8000" product_id = kwargs.get("pk") product = Product.objects.get(id=product_id) checkout_session = stripe.checkout.Session.create( payment_method_types=["card"], line_items=[ { "price_data": { "currency": "usd", "unit_amount": product.get_cent_price, "product_data": { "name": product.name, "images": [product.image.url], }, }, "quantity": 1, }, ], mode="payment", success_url=ng + "/payment/done", cancel_url=ng + "/payment/cancel", ) return JsonResponse({"id": checkout_session.id}) and it's how i'm sending post to this view <button type="button" id="checkout-button">Checkout</button> <script type="text/javascript"> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; // Create an instance of the Stripe object with your publishable API key var stripe = Stripe("{{ STRIPE_PUBLIC_KEY }}"); var checkoutButton = document.getElementById("checkout-button"); checkoutButton.addEventListener("click", function () { fetch("{% url 'payment:create-checkout-session' 1 %}", { method: "POST", headers: { 'X-CSRFToken': csrftoken, }, }) .then(function (response) { return response.json(); }) .then(function (session) { return stripe.redirectToCheckout({ sessionId: session.id }); }) .then(function (result) { // If redirectToCheckout fails due to a … -
Unable to login to Heroku admin panel after successfully creating superuser
I am trying to create a superuser for a Django website that I have deployed on Heroku via Github. I did this locally by running the console locally for my Heroku app as shown in the image below. I followed the prompts after typing the command 'python manage.py createsuperuser' and got a message stating that the superuser was created successfully. However, when I opened the app again and trying to access the admin panel using a staff account I got a message asking me to type the correct credentials for a staff account. The superuser credentials were not recognized when I tried to login as a regular user either. I ran migrations using the command python manage.py makemigrations; python manage.py migrate before creating the superuser and afterwards but every time I got a message saying that there are no migrations to apply. Can someone please help me fix this issue? Thank you. -
Tweets don't show up on Django webserver
Here's my html for my Django Twitter project. I am trying to display tweets in Django. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Twitter</title> </head> <body> <div> {% for tweet in tweets %} {{tweet.text}} {% endfor %} </div> </body> </html> Here's my views.py: import tweepy from tweepy.auth import OAuthHandler from .models import Tweet from .models import Dates from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.shortcuts import render from django.db import models, transaction from django.db.models import Q import os import tweepy as tw import pandas as pd consumer_key = 'IkzuYMak76UcXdnL9HabgIfAq' consumer_secret = 'Lt8wrtZ72ayMEcgZrItNodSJbHOPOBk5YnSpIjWbhXpB4GtEme' access_token = '1405021249416286208-GdU18LuSmXpbLTz9mBdq2dl3YqKKIR' access_token_secret = 'kOjGBSL2qOeSNtB07RN3oJbLHpgB05iILxT1NV3WyZZBO' def tweet_list(request): auth = tw.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tw.API(auth, wait_on_rate_limit=True) # Define the search term and the date_since date as variables searchword = Tweet.objects.get() date = Dates.objects.get() searchword.searchwordy # Collect tweets tweets = tw.Cursor(api.search, q=searchword.searchwordy, lang="en", since=date.datey).items(5) # Iterate and print tweets for tweet in tweets: print(tweet.text) return render(request, 'tweet/tweet-list.html', {'tweets': tweets}) My code works so far, but the HTML i am trying to render is to display my tweets. If anyone could find code to help me, comment below. -
How can I access images in my aws s3 bucket in a django html tag?
I'm not very knowledgeable about this topic so I'm going to keep this simple. I set up AWS S3 Storage with Django. When I upload images to one of my models, the image shows up in the appropriate bucket (good). I'm not sure how to access an object inside my storage already. I have an image, say 'apple.jpg' and I want to display it on the website. How do I get this to show? My research says it has to do with AWS_Location but I'm really not sure. Thanks in advance. -
django updating multiple instances with different foreignkey
I'm trying to duplicate multiple data I only need to change their related foreignkeymy problem is that I'm able to duplicate but with the same foreignkey below is my code any suggestions please from django.db import models class Category(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Client(models.Model): cat = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) age = models.IntegerField() married = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.fname + " " + self.lname + " " + str(self.cat) def show_category(request, cat_id): clients = Client.objects.filter(cat__id=cat_id) if request.method =='POST': for i in clients: i.id = None i.cat.id=3 i.save() return redirect('/') context = {'clients':clients} return render(request, 'app/home_cat.html', context) -
Saving API Information Into a Database - Using Django and Fetch API in Javascript
I'm new to APIs with Javascript and Django. I have a project where an API is called in Javascript, and it gets weather information for a specific location (the user types the location into a form first). Currently it does not save the weather info to the database. If the user clicks 'add to favorites' for the location, only then I want to save that info to the database. My question is, would I use a PUT request for this? Also, would I need a totally different fetch request for this, or would I be able to take the one I already have, and just get that data somehow. I'm assuming to save it to the database I would probably need a separate fetch request using PUT, because I only want it to save when the user clicks a button. Here is what I have for the API to get the weather data (this works correctly but this does not save to the database yet). function hi() { function temperature(input) { const myKey = "private"; const api = `https://api.openweathermap.org/data/2.5/weather? q=${input}&lang=en&appid=${myKey}&units=metric`; return fetch(api).then(function(response){ let data = response.json(); console.log(data); return data; }) .catch(error => { console.log('Error:', error); }) } Any guidance is … -
Get username who created/edited record in the Django table
I want to get username who created/edited records and pass this username to template in the table. I have the following code. Any suggestions how can I make this work? Models.py class Employee(ChangeloggableMixin, models.Model): name = models.CharField(max_length = 100) post = models.CharField(max_length = 100, default = '') work_place = models.CharField(max_length = 150, default= '') username = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.name Forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['name', 'post', 'work_place', 'username'] labels = { 'name':'name', 'post':'Post', 'work_place':'Work place', 'username': 'Author of the record', } Views.py def employee_list(request): context = {'employee_list': employees} return render(request, 'employee_register/employee_list.html', context) employee_list.html <table class="hover" id = "myTable" cellpadding="0"> <thead> <tr> <th>Name</th> <th>Post</th> <th>Work place</th> <th>Author of the record</th> </tr> </thead> <tbody id="target"> <tr> {% for employee in employee_list %} </td> <td>{{form.name}}</td> <td>{{form.post}}</td> <td>{{form.work_place}}</td> <td>{{form.username}}</td> </tr> {% endfor %} </tbody> </table> -
"sqlite3.OperationalError: attempt to write a readonly database" even after chmod 777
I' m running a Django application within a docker container. I'm getting this error sqlite3.OperationalError: attempt to write a readonly database. I've tried everything in the Dockerfile RUN chown username db.sqlite3 RUN chmod 777 db.sqlite3 I tried also to run the application as root user, but I still get the same error. -
How to solve pg_dump: aborting because of server version mismatch using docker
I am running a django server(image python:3.8.2-slim-buster) and a postgresql(image postgres:13) database on separate docker containers. I am trying to use django-dbbackup to back up data and ran into this error. # python manage.py dbbackup System check identified some issues: WARNINGS: account.EmailAddress: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the AccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. account.EmailConfirmation: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the AccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. socialaccount.SocialAccount: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SocialAccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. socialaccount.SocialApp: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SocialAccountConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. socialaccount.SocialToken: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the … -
django framework grpc and http
I have a project. I hope that based on Django framework, HTTP and grpc can be started in one process, and they can share variables. Django grpc framework can start a grpc port, how to open another HTTP port in this project -
how to transform XML file into PDF in python
The data coming from the remote server(Dynamically) in XML format(Response). I want to convert this XML Response into PDF Files. (I am doing manually XML --> HTML --> PDF). Any good approach to make this automatic instead of doing a manual process in python. -
Django Keycloak integration flow
Try to follow the follow steps to integrate keycloak with Django system without using the builtin contrib.auth app. My question is: If I am not using the built-in user objects, how do I determine if a user is authenticated or not, by using the SSO session Keycloak generated? Step 5, associate it with a session, what does it mean? -
how to transform XML to XSL using python
I have a sample XML file like this: <contents> <part title="Lucene Basics(or Fundamentals)"> <chapter title="Lucene Searching"> <section type="internal" title="Lucene Scoring"> <leaf title="How Lucene scoring works" seotitle="how-lucene-scoring-works"> </leaf> </section> <section type="terminal" title="" seotitle=""> <leaf title="hello world" seotitle="how-lucene-scoring-works"> </leaf> </section> </chapter> </part> </contents> Now I want to convert this XML into XSL format in python! any ideas? -
Django: Using a custom user model in django and unable to create a new model object with an associated user instance
I am using a custom user model in django and unable to create() a new object in an associated model that uses User as the unique identifier. I have tried: converting the user model instance to a string using the primary key of the instance (user.id, user.pk). using the commented out get instance of the user object using the user.email attribute Here is my relevant code below! settings.py AUTH_USER_MODEL = 'core.user' Model.py User = settings.AUTH_USER_MODEL def userprofile_receiver(sender, instance, created, *args, **kwargs): if created: breakpoint() #user = User.objects.get(email=instance.email) UserProfile.objects.create(user=instance) post_save.connect(userprofile_receiver, sender=User) class UserManager(BaseUserManager): def create_user(self, email, password1=None, password2=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password1) user.save(using=self._db) return user def create_staffuser(self, email, password1): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password1=password1, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password1=password, ) user.staff = True user.admin = True print("hi") user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, … -
Multiple product types in order/product model
I currently have something akin to the following: class ProductOne(Model): # product one specific fields class Order(Model): # order level details (supplier, date, etc ) class ProductOrder(Model): order = models.ForeignKey(WineOrder, on_delete=models.CASCADE) product = models.ForeignKey(ProductOne, related_name="product", on_delete=models.CASCADE) quantity = models.IntegerField("Order Quantity") But now I want to add more Product types (Product2, Product3, etc). Each order can only contain a single product type, but I need the user to select the product type before generating the order for it, and preferably using the standard Admin interface. Does anyone have an opinion about the easiest/cleanest way to achieve this? Cheers -
Docker image from python or linux for django?
I have Django project with postgresql. When dokerize it which base image should I use? FROM alipne:latest(linux) and Install pyenv. FROM PYTHON:tags and use it. -
Django database problem after trying implenet .env
I have a deployed app that I want to make the repository public, for this, I'm using a .env to store my data, but I am having an issue when I make a request do the database, like logging. psycopg2.OperationalError: FATAL: password authentication failed for user "$USER" FATAL: no pg_hba.conf entry for host "FOO", user "$USER", database "FOO", SSL off I runned: pip install django-environ on my setting.py import environ env = environ.Env() environ.Env.read_env() SECRET_KEY = env('SECRET_KEY') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env('NAME'), 'HOST': env('HOST'), 'POST': 5432, 'USER': env('USER'), 'PASSWORD': env('PASSWORD'), } } before that env change, I was able to connect on te site. *DEPLOYED ON HEROKU *I AM RUNNING THE SERVER WITH gunicorn mysite.wsgi