Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make django work with a table in a different schema in a different database?
I have a django model which work with remote table in a remote database. class CampaignSpSdRequest(models.Model): asins = models.CharField(max_length=200000) skus = models.CharField(max_length=200000, null=True, blank=True) class Meta: managed = False db_table = 'search\".\"CampaignSpSdRequest' The issue is I get the following error: INFO:root:relation "search.CampaignSpSdRequest" does not exist INSERT INTO "search"."CampaignSpSdRequest" For some reason it ads quotas also on CampaignSpSdRequest. It works with other tables, only this one has the problem. Any idea what is going on? Correct insert statement should be like this: INSERT INTO "search".CampaignSpSdRequest -
Django form field for integer list and using it for ModelMultipleChoiceField
I would like to have a form field with TextInput widget (for example CharField) for recieving comma-separated positive integer lists, for example: 0, 1, 2,7, 645, 345, 1000. I want to use it with ModelMultipleChoiceField (so the integer values represent pk). How could I achieve this? From the documentation it is not obvious how to create such field and how to make it work with ModelMultipleChoiceField (how to use the integer list returned from TextInput in ModelMultipleChoiceField to get the objects queryset). -
Django render admin panel with markdown fields
I am having trouble with markdown on my Django application. I am writing an admin panel and want to use the markdown field. I did everything that is needed to install it: my settings: INSTALLED_APPS = [ 'django.contrib.staticfiles', 'rest_framework', 'markdownx', ] models.py class ProductDescription(models.Model): top_description = MarkdownxField(max_length=1500) bottom_description = MarkdownxField(max_length=1500, blank=True, null=True) urls urlpatterns = [ path('markdownx/', include('markdownx.urls')), ] admin.py class ProductDescriptionAdmin(admin.ModelAdmin): model = ProductDescription fields = ( 'top_description', 'bottom_description', ) admin.site.register(ProductDescription, ProductDescriptionAdmin) Then I executed these commands: python manage.py makemigrations python manage.py collectstatic python manage.py migrate I'm expecting that I will be able to see a preview of my markdown field as it showed here: https://miro.medium.com/v2/resize:fit:4800/format:webp/1*XD_0oQfMsIhmHS0MJ0LP2g.png it looks like everything works fine except the preview, it tries to load the preview from http://localhost:8000/markdownx/markdownify/ but it receives 404 all the time it looks like ulrs markdownx/* are not registered and I don't know why is that :( am I missing something here? -
Trying to display a table with Django restframework + Datatables, getting 500 Internal Server Error with Ajax
error page Hi, I am getting this Ajax error in the image when I try to display a table on my site. I've added the router and its urls to my urls file. Here are my other files. models.py: class Sites(models.Model): site_id = models.IntegerField(primary_key=True) site_name = models.CharField(max_length=20) site_description = models.TextField() class Meta: managed = False db_table = 'sites' views.py: class SitesViewSet(viewsets.ModelViewSet): queryset = Sites.objects.all() serializer_class = SitesViewSerializer serializers.py: class SitesViewSerializer(serializers.ModelSerializer): class Meta: model = Sites fields = ('site_id', 'site_name', 'site_description') Here's my full traceback. [02/May/2023 07:01:22] "GET /sites-directory HTTP/1.1" 200 10906 Internal Server Error: /api/sites/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/generics.py", line 150, in filter_queryset queryset = backend().filter_queryset(self.request, queryset, self) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework_datatables/filters.py", line 95, in filter_queryset … -
Booleanfield not saving to database
`I have tried a few different styles of saving in the view. None of them will save the booleanfield. However, all of them save the inlineformset with no problems. I feel like I'm missing something small here but cannot figure out where I am going wrong. -
Error: module 'inspect' has no attribute 'getargspec'
I am using python-3.11.2 with a Django project. I'm attempting to uploading my code to heroku and got the error: "Error: module 'inspect' has no attribute 'getargspec'" My requirements: asgiref==3.6.0 certifi==2022.12.7 charset-normalizer==3.0.1 distlib==0.3.6 dj-database-url==1.2.0 Django==3.2.18 django-heroku==0.3.1 filelock==3.9.0 idna==3.4 importlib-metadata==6.0.0 platformdirs==3.0.0 psycopg2-binary==2.9.5 pytz==2022.7.1 requests==2.28.2 sqlparse==0.4.3 typing-extensions==4.5.0 urllib3==1.26.14 virtualenv==20.20.0 whitenoise==6.4.0 zipp==3.15.0 django-bootstrap4 gunicorn I'm not sure what is off. Could someone assist? -
For cookiecutter-django if we are using docker setup how pre-commit will run?
There will be no setup in local regarding requirements and all how pre-commit will run there. It should go in docker container and run pre-commit as I think. -
Get the fields of Foreign key values in Django
I'm confused why the values I fetch in foreign key is missing or not pops in Ajax result , all I want is to get the value name through the foreign key id using ajax, I tried many ways like select_related() but it doesn't work. The image below shows the result of the ajax through consolelog which contains data from supplier table and supplier_type table but only the supplier table fetch the data and missing supplier name data which foreign key name? I just tried supplier_type__name but it seems doesn't work. Is there any problem with the implementation? ajax $('.get_supplier_details').click(function (event) { var patient_id = $('#selected-patient').find(":selected").val(); $.ajax({ type: "POST", url: "{% url 'supplier-details' %}", data:{ supplier: supplier_id } }).done(function(data){ console.log(data); // }); }); vies.py from main.models import (Supplier, SupplierType) def patientdetails(request): supplier_id = request.POST.get('supplier') clients = Supplier.objects.filter(id=supplier_id ).select_related() qs_json = serializers.serialize('json', clients, fields=['first_name', 'middle_name', 'supplier_type__name']) return JsonResponse({'data': qs_json}) models,py class SupplierType(models.Model): name = models.CharField(max_length=128, blank=True, null=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = True db_table = 'supplier_type' class Supplier(models.Model): supplier_type = models.ForeignKey(SupplierType, models.DO_NOTHING) first_name = models.CharField(max_length=128, blank=True, null=True) middle_name = models.CharField(max_length=128, blank=True, null=True) last_name = models.CharField(max_length=128, blank=True, null=True) class Meta: … -
select_related in view is not reducing queries with hybrid property in Django
I have included select_related and overall is reducing the number of queries and prefetching data as expected. However, I have a case which is querying separately. I am not sure if I am expecting a behaviour that would not be possible. I have the following view: list.py (View) where I am using select_related: class OpportunitiesList(generics.ListAPIView): serializer_class = OpportunityGetSerializer def get_queryset(self): queryset = Opportunity.objects.all() queryset = queryset.filter(deleted=False) return queryset.select_related('nearest_airport').order_by('id') I have four objects in the models: opportunity.py (Model): class Opportunity(models.Model): deleted = models.BooleanField( default=False, ) opportunity_name = models.TextField(blank=True, null=True) nearest_airport = models.ForeignKey(AirportDistance, on_delete=models.SET_NULL, db_column="nearest_airport", null=True) class AirportDistance(models.Model): airport_id = models.ForeignKey(Airport, on_delete=models.SET_NULL, db_column="airport_id", null=True) airport_distance = models.DecimalField(max_digits=16, decimal_places=4, blank=False, null=False) @property def airport_name(self): return self.airport_id.name location_assets.py (Model): class Location(models.Model): name = models.CharField(null=True, blank=True, max_length=255) location_fuzzy = models.BooleanField( default=False, help_text= "This field should be set to True if the `point` field was not present in the original dataset " "and is inferred or approximated by other fields.", ) location_type = models.CharField(null=True, blank=True, max_length=255) class Airport(Location): description = models.CharField(null=True, blank=True, max_length=255) aerodrome_status = models.CharField(null=True, blank=True, max_length=255) aircraft_access_ind = models.CharField(null=True, blank=True, max_length=255) data_source = models.CharField(null=True, blank=True, max_length=255) data_source_year = models.CharField(null=True, blank=True, max_length=255) class Meta: ordering = ("id", ) Lastly, I have the serializers to transform … -
Change Like button colour when a post is liked
i have this social media application and i want when a user has liked a post the colour is red and if not it is black. Here is my view: @login_required() def likes(request, post_id): user = request.user post = Post.objects.get(id=post_id) current_likes = post.likes liked = Likes.objects.filter(user=user, post=post).count() if not liked: liked = Likes.objects.create(user=user, post=post) current_likes = current_likes + 1 else: liked = Likes.objects.filter(user=user, post=post).delete() current_likes = current_likes - 1 post.likes = current_likes post.save() return HttpResponseRedirect(reverse('post_detail', args=[post_id])) my post-detail.html page and index.html look like: <a href="{% url 'like' post.id %}" class="post__button"> {% if post.likes %} <i class="fa fa-heart" style="color: red; font-size: 27px;"></i> {% else %} <i class="fa-regular fa-heart" style="color: black; font-size: 27px;"></i> {% endif %} </a> But saying "if post.likes" works if the post has any like even if not from the current user and makes the like button red and if the post has 0 likes it is black. But i want it like that with the current logged in user (user=request.user) i have tried the following in the html to no avail if user.post.likes if request.user.post.likes if not liked if liked urls.py path('<uuid:post_id>/like', views.likes, name="like"), model.py class Likes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_likes") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_likes") -
My Django/MySQL Login project don’t work, how can i fix it?
I created a login page, but I'm having trouble with an error message that says 'ModuleNotFoundError: no module named "login.settings".' I've checked my code and everything looks fine, but when I try to start the server, this error message appears. I've tried various solutions but I'm still not sure what's causing the issue. If you need more information or pictures, please let me know. I'm hoping to resolve this soon so I can get some rest. Thanks for your help! enter image description here -
thread '<unnamed>' panicked at 'zip: InvalidArchive("Could not find central directory end")',
I am new to using Django and am taking over a repo for my internship that no one currently at the company has worked on. I am working on installing the repo and getting the development environment to work at all. The instructions on the repo's README seem to be outdated. I am following them, but get the following errors when I run pipenv run python ./manage.py migrate I am not sure what "archive" refers to here and what the program is even attempting to do when it encounters this error, and have no idea how to go about fixing it. Loading .env environment variables... thread '<unnamed>' panicked at 'zip: InvalidArchive("Could not find central directory end")', /home/runner/.cargo/git/checkouts/divvunspell-1de7e297f42b53b7/474c74a/divvunspell/src/archive/zip.rs:75:51 note: run with RUST_BACKTRACE=1 environment variable to display a backtrace Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/_init_.py", line 381, in execute_from_command_line utility.execute() File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/_init_.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = … -
Workaround for lack of ArrayField/JSONField in sqlite?
I'm trying to make tests on a django project run faster by switching to sqlite instead of postgres for test runs, and am running into issues because some models use ArrayField or JSONField, which are postgres specific. Is there any workaround I could use to make this work? For instance something like a 3rd party library that could monkeypatch ArrayField and JSONField and rebuild them on top of CharField? - or some hack of this nature, not good for prod but good enough to speed up tests... I can't be the first one trying to make this work! -
How to redirect to frontend login page in react after account activation via email sent by Djoser in django and drf
I am in the process of implementing Djoser into my current project. On the front end I have a form for registration, onSubmit and onSuccess redirect to a page telling the user to check their email and click the activation link. This link and email are sent by Djoser. The email now prints in the console and it looks like this: <p>Please go to the following page to activate account:</p> <p><a href="http://127.0.0.1:8000/activate/OQ/bnjmpy-22a214344550a46e302c11411567af4e">http://127.0.0.1:8000/activate/OQ/bnjmpy-22a214344550a46e302c11411567af4e</a></p> <p>Thanks for using our site!</p> After clicking on this link, I am of course taken to the browser, to the exact link where the DRF page is displayed in the browser. I want to display the Login page in React instead. I was thinking of redirecting from the backend to the frontend and there wywowalać getrequest to the activation link, or somehow in APIView redirect to the frontend login page. However, I don't know how to do that and can't find info on how to solve it. DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { "user_create": "accounts.serializers.UserCreateSerializer", # custom serializer "user": "djoser.serializers.UserSerializer", "current_user": "djoser.serializers.UserSerializer", "user_delete": "djoser.serializers.UserSerializer", } } urlpatterns = [ path('activate/<str:uid>/<str:token>/', UserActivationView.as_view()), path('auth/', include('djoser.urls')), … -
SQL Server does not support unique constraints on expressions [closed]
Whenever I am trying to run the migrate command, I am getting is warning. Can someone tell me why it's occurring and how I can resolve this? chat.Thread: (models.W044) SQL Server does not support unique constraints on expressions. HINT: A constraint won't be created. Silence this warning if you don't care about it. Operations to perform: Apply all migrations: accounts, admin, auth, chat, contenttypes, sessions Running migrations: No migrations to apply. -
nginx reverse proxy does not sends the packages
I am having problems configuring docker compose, being more specific in the nginx configuration since when I want to consume the API it returns the following running docker logs webserver-callservices [01/May/2023:19:41:53 +0000] "\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03d\x1F\xC3\x01\x8D\xEF\xADz-\xD2Me\xA1\x01\x09Rbd\x93\xED\xCA\xEB\xD6" 400 157 "-" "-" But running docker logs callservicebackend-backendcallservices-1 I get Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 01, 2023 - 17:01:54 Django version 3.0, using settings 'callservices.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. From what I understand there is a problem in the nginx configuration this is the docker-compose.yml version: '3.8' services: webservercallservices: image: nginx:latest container_name: webserver-callservices restart: always depends_on: - backendcallservices ports: - "443:443" volumes: - ./:/var/www - ./Dockerfiles/nginx:/etc/nginx/conf.d - /etc/letsencrypt:/etc/letsencrypt networks: app-network: backendcallservices: build: context: ./Dockerfiles/python dockerfile: Dockerfile command: sh -c 'python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000' volumes: - ./:/code ports: - "8000:8000" environment: - CELERY_BROKER_URL=redis://redis:6379/0 - CELERY_RESULT_BACKEND=redis://redis:6379/0 depends_on: - databasecallservices - redis networks: app-network: celery: build: context: ./Dockerfiles/python dockerfile: Dockerfile command: celery -A callservices worker -l info volumes: - ./:/code depends_on: - databasecallservices - redis environment: - CELERY_BROKER_URL=redis://redis:6379/0 - CELERY_RESULT_BACKEND=redis://redis:6379/0 networks: app-network: redis: image: redis:latest container_name: redis restart: always ports: - "6379:6379" networks: … -
Can we assign query_param value to a field in serializer
I have a views.py class ProductImageAPIView(generics.GenericAPIView): serializer_class = ProductImageSerializer def post(self, request): query_params = self.request.query_params serializer = self.serializer_class(data = request.data, context = query_params) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py class ProductImageSerializer(serializers.ModelSerializer): image = serializers.ImageField() product = serializers.PrimaryKeyRelatedField(allow_null = False, read_only = True) class Meta: model = Image fields = ['id', 'image', 'product'] def validate(self, attrs): productParam = self.context.get('product') return super().validate(attrs) I'm sending the query_params as a context into the serializer. I want to know, how can I assign product field with the productParam value so that i can validate it and use it in fields section of Meta class. -
How can i write a python code to read the “cities.csv” file . Print the contents of Columns named “LatM”,”NS” ,”LonM” and “EW” where “State” is “CA”?
this is mt cities.csv file enter image description here import csv with open('cities.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row['LatM'], row['NS'], row['LonM'], row['EW']) -
Creating a model Vote to be able to vote on model Coin with assigning user to it
I m trying to write my first own REST API in django and i don't know how to properly create a model to be able to vote on Coin model with assigning User to this vote. User model in models.py in core app. class UserManager(BaseUserManager): """Manager for users.""" def create_user(self, email, password=None, **extra_fields): """Create. save and return a new user.""" if not email: raise ValueError('User must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Create and return a new superuser""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """User in the system.""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) gem_finder = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) votes_left = models.IntegerField(default=3) objects = UserManager() USERNAME_FIELD = 'email' Serializer for User model in user app. class UserSerializer(serializers.ModelSerializer): """Serializer for the user object.""" class Meta: model = get_user_model() fields = ['email', 'password', 'name', 'gem_finder'] extra_kwargs = { 'password': {'write_only': True, 'min_length': 5}, 'gem_finder': {'read_only': True} } def create(self, validated_data): """Create and return a user with encrypted password.""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update and return user""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if … -
Django select error: Select a valid choice. <choice> is not one of the available choices
I've 2 select fields. First one (brand) contains all car brands, second one is empty till we don't select any car brand. However, when I do, my JS file changes It's options (car_model), but only on front-end side. On the back-end side It's still empty. All work fine beside second field. So, how can I resolve this issue? My models.py: from django.db import models import uuid from PIL import Image class Car(models.Model): car_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) brand = models.CharField(max_length=60) car_model = models.CharField(max_length=60) def __str__(self): return f'{self.brand}: {self.car_model}' My forms.py: from django import forms from .models import Car class SellCarForm(forms.ModelForm): brand = forms.ChoiceField(choices=[('', "Select the brand"), ("bmw", 'BMW'), ("audi", 'Audi'), ("bentley", 'Bentley'), ("Bugatti", 'Bugatti'), ("Chevrolet", 'Chevrolet'), ("Citroen", 'Citroen'), ("Dacia", 'Dacia'), ("Ferrari", 'Ferrari'), ("Fiat", 'Fiat'), ("Ford", 'Ford'), ("Honda", 'Honda'), ("Hyundai", 'Hyundai'), ("Jeep", 'Jeep'), ("Kia", 'Kia'), ("Lambo", 'Lamborghini'), ("Lexus", 'Lexus'), ("Maserati", 'Maserati'), ("Mazda", 'Mazda'), ("McLaren", 'McLaren'), ("mercedes", 'Mercedes-Benz'), ("Mini", 'Mini'), ("Mitsubishi", 'Mitsubishi'), ("Nissan", 'Nissan'), ("Opel", 'Opel'), ("Peugeot", 'Peugeot'), ("Renault", 'Renault'), ("Rover", 'Land Rover'), ("Saab", 'Saab'), ("Seat", 'Seat'), ("Skoda", 'Skoda'), ("Subaru", 'Subaru'), ("Suzuki", 'Suzuki'), ("Tesla", 'Tesla'), ("Toyota", 'Toyota'), ("Volkswagen", 'Volkswagen'), ("Volvo", 'Volvo') ] ) car_model = forms.ChoiceField(choices=[('', "Select the model")]) class Meta: model = Car fields = [ 'brand', 'car_model', ] def save(self, … -
Django xhtml2pdf Arabic text not supporting
I am using Django xhtml2pdf to generate PDF, and it not supporting Arabic text I tried all possible ways which are suggested but still no luck <style> @import url(https://fonts.googleapis.com/css?family=Markazi+Text); .markazi-text{font-family:'Markazi Text',serif} *{ font-size: 12px; padding: 0px; margin: 0px; } table{ border: 1px solid #000; margin-bottom: 5px; } table tr th{ padding-top: 5px; -pdf-word-wrap: CJK; padding: 5px; } table tr td{ padding-top: 5px; padding-left: 5px; width: auto; word-break: break-all; padding: 5px; -pdf-word-wrap: CJK; } table tr td p{ word-break: break-all; } p{ margin: 0px; font-family:'Markazi Text'; } .vendor-sec{ border: 1px solid #000; width: 150px; padding: 5px; margin-bottom: 15px; } </style> Django code template_path = 'pdf.html' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="declaration.pdf"' html = render_to_string(template_path, data) result = io.BytesIO() pdf = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), dest=result,encoding='UTF-8') content = result.getvalue() encoded = base64.b64encode(content) encoded = encoded.decode('utf-8') I tried all below solutions solution 1 solution 2 solution 3 solution 4 On HTML I can see arabic text but when I try to convert this HTML to pdf the its show blocks -
Dj Rest Auth custom registration not working
I am using DJ-REST-AUTH for user registration API. I want the first_name and last_name to show in the API endpoint however right now it is just showing the default. I have tried to configure the settings and create CustomRegisterSerializer. I read that I need to have a def save(self, request) function as well and have tried to implement that as well. main app urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/authentication/', include('authentication.urls')),] settings.py INSTALLED_APPS = \[ 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'dj_rest_auth', 'dj_rest_auth.registration', 'authentication',] SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'authentication.serializers.CustomRegisterSerializer' } # Configure allauth to use email as username ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_VERIFICATION = 'none' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_LOGOUT_ON_GET = True authentication app urls.py from django.urls import path from dj_rest_auth.views import ( LoginView, LogoutView, PasswordResetView, PasswordResetConfirmView ) from .views import CustomRegisterView urlpatterns = \[ path('register/', CustomRegisterView.as_view(), name='register'), path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('passwordReset/', PasswordResetView.as_view(), name='password_reset'), path('passwordResetConfirm/\<str:uidb64\>/\<str:token\>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), \] serializers.py from rest_framework import serializers from allauth.account.adapter import get_adapter from django.contrib.auth.models import User from dj_rest_auth.registration.serializers import RegisterSerializer class CustomRegisterSerializer(RegisterSerializer): … -
Why the registeration.html form is not rendering in DJANGO?
New to DJANGO. I am having trouble with rendering my registeration.html page. This is my project structure auth_test | |-urls.py |-settings.py big_app | |-admin.py |-forms.py |-models.py |-urls.py |-views.py templates media static This is my application big_app. The auth_test folder urls.py is from django.contrib import admin from django.urls import path from big_app import views # from django.conf.urls import url, include ---> this is depreciated from Django 4.0 onwards from django.urls import include,re_path urlpatterns = [ re_path(r'^$', views.index,name='index'), re_path(r'^admin/', admin.site.urls), re_path(r'big_app/',include('big_app.urls')), ] now the urls.py of the big_app is from big_app import views from django.urls import include, re_path # TEMPLATE URLS app_name = 'big_app' urlpatterns = [ re_path(r'^register/$',views.register, name='register') ] The views.py has the code. from django.shortcuts import render from big_app.forms import UserForm, UserProfileForm # Create your views here. def index(request): return render(request, "big_app/index.html") def register(request): registered = False # breakpoint() if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() # hashing the password user.set_password(user.password) user.save() profile = profile_form.save(commit=False) # setting up the one to one relationship with the user present in the admin perspective profile.user = user if "profile_pic" in request.FILES: profile.profile_pic = request.FILES["profile_pic"] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form … -
what does ', '.join(genre.name for genre in self.genre.all()[:3]) precisely do?
Hi I'am lerning Django web framework and I came acros this line of code: return ', '.join(genre.name for genre in self.genre.all()[:3]) source I want to know what precisely everything in this line does. I know that .join joins a tuple into the string with ', ' as a separator. But I have no idea how genre.name for genre in self.genre loop works. What does .all() function do and how [:3] connects with all of this. I tried searching what .all() does but I only found documentation for all(parameter). I tried searching what a for b in c loop does but I only found documentation for a in b. I know that [:3] return 3 values but I don't know how this connects with the rest of the code. -
Factory boy connect models to existing users
Im populating my database with dummy data, I have separate Profile, User, Picture model. How can connect them to use same users? class UserFactory(DjangoModelFactory): class Meta: model = User email = factory.Faker('email') first_name = factory.Faker('first_name') birthday = factory.Faker('date_object') age = factory.Faker('pyint', min_value=18, max_value=100) is_staff = False is_active = True class UserPhotoFactory(DjangoModelFactory): class Meta: model = UserPhoto user = factory.RelatedFactory(UserFactory) #???? order = factory.Faker('pyint', min_value=0, max_value=4) url = factory.Faker( 'random_element', elements=[x for x in ['https://picsum.photos/seed/picsum/200/300', 'https://picsum.photos/seed/pssss/200/300', 'https://picsum.photos/seed/picwum/200/300']] ) class ProfileFactory(DjangoModelFactory): class Meta: model = Profile user = factory.SubFactory(UserFactory) bio = factory.LazyAttribute(lambda o: FAKE.paragraph(nb_sentences=5, ext_word_list=['abc', 'def', 'ghi', 'jkl'])) In this case I'm calling in shell ProfileFacotry.create_batch(10) And that creates users and their corresponding profiles. Now I want to add UserPhoto to the mix that is related to USER via ForeignKey like this class UserPhoto(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order = models.PositiveIntegerField(null=True) url = models.CharField(max_length=220) What I want to achieve is to get 10 users 10 profiles and let say 20 pictures 2 for each user