Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload photos to a fle in m'y computer using Django reste framework
I created a photo model, serializer and view, Users Can upload photos to m'y website. I learned that thé best solution to do it is to upload thé photo on thé computer and the path on data base. But how Can i upload thé photo to my computer via my website or my api ? Modèles.py ken authentification. So for adding an Announcement the user must be authenticated. Models.py class User(AbstractUser): username = None email = models.EmailField(max_length=100, verbose_name='email', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Announcement(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) photo = models.ManyToManyField(Photo, blank=True) class Photo(models.Model): name = models.CharField(max_length=100) content_type = models.CharField(max_length=100) path = models.CharField(max_length=100) Serializers.py class AnnouncementSerializer(serializers.ModelSerializer): author = UserSerializer(required=True) parameters = ParameterSerializer(many=True, required=False) photo = PhotoSerializer(many=True, required=False) class Meta: model = Announcement fields = ['id', 'name', 'author', 'parameters', 'photo'] class UserSerializer(serializers.ModelSerializer): photo = PhotoSerializer() class Meta: model = User fields = ['id', 'email','photo', ] class ParameterSerializer(serializers.ModelSerializer): class Meta: model = Parameter fields = '__all__' class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo fields = '__all__' Views.py class AnnouncementCreate(CreateAPIView): permission_classes = [IsAuthenticated] queryset = models.Announcement.objects.all() serializer_class = AnnouncementSerializer -
Django `LookupError: App 'accounts' doesn't have a 'User' model` causes AUTH_USER_MODEL fails with `accounts.User` has not been installed
I am trying to refactor an existing code base by creating new accounts app with new custom User model. When I try to do makemigrations, I get the following error: Traceback (most recent call last): File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/config.py", line 268, in get_model return self.models[model_name.lower()] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/auth/__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/config.py", line 270, in get_model raise LookupError( LookupError: App 'accounts' doesn't have a 'User' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dev/Projects/Foto-Dino/foto-dino/manage.py", line 22, in <module> main() File "/home/dev/Projects/Foto-Dino/foto-dino/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/dev/.virtualenvs/foto-dino/lib/python3.9/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen … -
Django_filters Reverse foreign key relationship lookup
I am working on an application and recently trying to figure out how to use the reverse foreign key relationship lookup in django filters. models.py class Units(models.Model): Unit = models.CharField(primary_key=True, max_length=200, null=False, unique=True) Type = models.CharField(max_length=200,null=True) Floor = models.CharField(max_length=200, null=True) Building = models.CharField(max_length=200, null=True) def __str__(self): return str(self.Unit) # Keeps track of the inventory updates class Inventory(models.Model): Unit = models.ForeignKey(Units, on_delete=models.CASCADE, null=True, to_field="Unit") Price = models.IntegerField(null=True) Status= models.CharField(max_length=200, null=True) Cancelations_Swaps = models.CharField(max_length=200, null=True) Date_of_update = models.DateField(default=timezone.now) Custumer = models.ForeignKey('Lead', on_delete=models.CASCADE, null=True, to_field="id") def __str__(self): return str(self.Unit) I am displaying in my template all the units with theire latest Status (filtering on Date of update) using the tag bellow @register.filter_function def fil(i): if i.inventory_set.all().order_by('-Date_of_update'): status=i.inventory_set.all().order_by('-Date_of_update')[0].Status return status else: return False and the template is as follows: template {% for i in Unit %} <tr> <td> {{i.Unit }}</td> <td> {{i.Type }}</td> <td> {{i.Floor }}</td> <td> {{i.Building }}</td> <td>{{i|fil}}</td> Where Unit is simply Units.objects.all() I also have built a filter in order to filter the data diplayed as follows: class Unitfilter(django_filters.FilterSet): class Meta: model = Units fields = '__all__' filter_overrides = { models.CharField: { 'filter_class': django_filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'icontains', }, } } I want to be able to filter the … -
For loop in Django templates
I want to display the center of a for loop, for example i for loop the 1-30 then i want to for loop the 11-20 here is the example of how i use the for loop in my html: this is method that i used when i for loop to 30-20 {% for category in category_list reversed %} {% if forloop.counter < 11 %} <li><a class="dropdown-item" href="home/category/{{category.name}}">{{ category.name|title }}</a></li> {% endif %} {% endfor %} this i the method when i for loop to 1-10 {% for category in category_list %} {% if forloop.counter < 11 %} <li><a class="dropdown-item" href="home/category/{{category.name}}">{{ category.name|title }}</a></li> {% endif %} {% endfor %} problem how to for loop the 11-20? thanks for the help! -
Django + PostgreSQL: pagination extremely slow for millions of objects
I have around 6 million objects in my database. For these objects, I need to have a structure page, where the users would browse through the aforementioned 6 million objects as paginated content. My code for the pagination is a total duplicate of what is given in the documentation of Django: def listing(request): movie_list = Movie.objects.all() paginator = Paginator(movie_list , 100) # Show 100 movies per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'movies.html', {'page_obj': page_obj}) Howevre, most of the resulting 60,000 pages with the movies are too long to open, and give 504 timeout errors, which also results in the content being unreadable for GoogleBot (which is actually the main aim of the structure page). What can be the turnaround to prevent these timeouts and ensure the normal load speed for the large paginated content in Django? The database I am using is PostgreSQL. -
send contents of csv from react to django backend
Any advise on how i can get my backend (django) to receive and further process the csv contents sent from react? FrontEnd- import Papa from "papaparse"; export default function App() { return ( <div className="App"> <input type="file" accept=".csv" onChange={(e) => { const files = e.target.files; console.log(files); if (files) { console.log(files[0]); Papa.parse( files[0], { header:true, skipEmptyLines: true, complete: function (results) { console.log("Finished:", results.data); } } ); } }} /> </div> ); } Backend - Standard Django framework -
Django admin how to order by model property?
I have a model with property and I want to be able to sort instances in the admin panel by that property. My model with _points property: class CustomUser(models.Model): inviter = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) @property def _points(self): res = TelegramUser.objects.filter(inviter_id=self.id).count() return res -
Form errors not displaying with Django Crispy Forms
I just started learning Django and Python some weeks back. Working on a project sign up page, everything works perfectly except that form errors are not displaying on the form itself but redirected to a debug error page with the below ValidationError at /register/ ['Username exists'] Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 3.2.5 Exception Type: ValidationError Exception Value: ['Username exists'] During a new user profile registration, i am checking if the username used to register already exists or not and if it exists, i want to display an error to user that Username already exists. Please see my code below: forms.py class RegistrationForm(forms.Form): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') username = forms.CharField(label='Username') password = forms.CharField( label='Password', widget=forms.PasswordInput(), min_length=8) password_confirm = forms.CharField( label='Confirm Password', widget=forms.PasswordInput()) email_address = forms.EmailField(label='Email') phone_number = PhoneNumberField(label='Phone Number') whatsapp_number = PhoneNumberField(label='WhatsApp Number', required=False) COUNTRY_CHOICES = [ ('', 'Choose...'), ] country = forms.ChoiceField(label='Country', choices=COUNTRY_CHOICES) referral_id = forms.CharField(label='Referral ID', required=False) license_agreement = forms.BooleanField( label='I agree to all the Terms and Conditions') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'create-account-form' self.helper.form_action = 'register' self.helper.form_show_errors = True self.helper.layout = Layout( Row( Column('first_name'), Column('last_name'), css_class='g-2' ), Row( Column( PrependedText('username', '@') ), Column('country'), css_class='g-2' ), … -
Python Django website for task Scheduling
I am creating a website for my College Project using Python Django Framework for Task Scheduling.Every user creates their own account.I am asked to add a functionality that when a user logs in with its credentials, the user must get suggestions from it's past experience for eg" you scheduled task for drinking water on sunday at 10:30 am, so would you like to add it to the schedule now?". So I want to know How I can achieve this ? and Feature is same for all users but each user gets suggestions based on it's own data.Please let me know about the same in Detail. -
How do I auto select group name in particular group post, i have done with authenticated user auto select
I am trying auto select group name based on in which group user want to post, if user in particular group details page. when he click post . the form will auto select group name... this is my post model: class Posts(models.Model): groups_name = models.ForeignKey(Groups, related_name='posts', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='my_posts', on_delete=models.CASCADE) post_body = models.TextField(blank=True,null=True) post_image = models.ImageField(upload_to='images/posts/', blank=True, null=True) post_created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) + ' |' + str(self.groups_name) def post_name(self): return self.post_body[:1000] def get_absolute_url(self): return reverse("groups:group_detail", kwargs={"slug": self.groups_name.slug}) class Meta: ordering = ["-post_created"] this is my view: class CreateGroupPost(LoginRequiredMixin, CreateView): model = Posts form_class = GroupPostCreateForm login_url = '/account/login/' template_name = 'groups/addpost_group.html' this is my urls.py: app_name = 'groups' urlpatterns = [ path('', GroupListView.as_view(), name='group_list'), path('create_group/', GroupCreateView.as_view(), name='create_group'), path('<str:groups_name>/create_grouppost/', CreateGroupPost.as_view(), name='create_grouppost'), path('group_detail/<slug>', GroupDetailView.as_view(), name='group_detail'), path('group_update/<slug>', GroupUpdateView.as_view(), name='group_update'), path('join/<slug>/', Joingroup.as_view(), name='join_group'), path('leave/<slug>/', LeaveGroup.as_view(), name='leave_group'), ] this is group_details.html i gave url link to add post: {% if user in groups.members.all %} <div class="d-grid gap-2 mt-3"> <a href="{% url 'groups:create_grouppost' groups.groups_name %}" class="btn btn-primary">Create Post</a> </div> {% else %} <div class="d-grid gap-2 mt-3"> <a class="btn btn-primary" href="{% url 'groups:join_group' groups.slug %}">Join Group</a> </div> {% endif %} this is my add_post.html page add post page -
image not updating in django from form post request
I am trying to edit an object through the form All fields are edited but the image field does not change What is the problem? model created with signals when user create account template <div> <form action="{% url 'user:profile' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="submit"> </form> </div> model class Profile(models.Model): CHOICES = ( ('RE', 'مشاور املاک'), ('S', 'فروشنده'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) real_estate = models.OneToOneField(Business , related_name='business' ,on_delete=models.CASCADE, blank=True , null=True) image = models.ImageField(blank=True) type_of_user = models.CharField(max_length=300, choices=CHOICES) phone_number = PhoneNumberField(unique = True, null = False, blank = False) form class ProfileForm(ModelForm): class Meta: model = Profile fields = ['type_of_user' , 'phone_number' , 'image'] views def profile(request): profile = Profile.objects.get(user=request.user) if request.method == 'POST': form = ProfileForm(request.POST , instance=profile) profile = form.save(commit=False) profile.user = request.user profile.save() redirect('busi:index') else: form = ProfileForm() context = { 'profile':profile, 'form':form } return render(request , 'user/profile.html' , context) -
is there anyway to accept dogecoin or TRX to website (django)
I am on project where I have to implement crypto Wallet to perform dogecoin or tron transactions but I have never worked with crypto wallets nor I have any idea , so can someone suggest me how to integrate it with some steps please. thank you -
django.core.exceptions.ValidationError: ['“Undergraduate” is not a valid UUID.']
I'm trying to add a way for a user to select if they are a undergrad or grad student in my models.py. Everything works except when I added this code below: undergrad_or_grad = models.OneToOneField( 'StudentStatus', default="Undergraduate", on_delete=models.CASCADE) Basically my thought process was, if the user doesn't select an option, they'll just be defaulted as an undergrad type student. Below is my full models.py file. from django.db import models from django.contrib.auth.models import User import uuid from django.db.models.signals import post_save, post_delete class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) profile_picture = models.ImageField( null=True, blank=True, upload_to='profiles/', default='profiles/defaultProfile.jpeg') username = models.CharField( max_length=200, null=True, blank=True, unique=True) name = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=1000, null=True, blank=True) undergrad_or_grad = models.OneToOneField( 'StudentStatus', default="Undergraduate", on_delete=models.CASCADE) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) class StudentStatus(models.Model): STUDENT_TYPES = ( ('undergrad', 'Undergraduate'), ('grad', 'Graduate'), ) title = models.CharField(max_length=200, null=True, blank=True, choices=STUDENT_TYPES) date_created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.title) Here's my full error after I run python manage.py makemigrations and then python manage.py migrate. I tried getting rid of default="Undergraduate" but the error still persists. (env) PS D:\Django Projects\StudentArchive> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, users Running … -
Raw Query to Django ORM Query
I have these two models: class Project(models.Model): name = models.CharField(max_length=200) class ProjectAdditionalInfo(models.Model): project = models.OneToOneField(Project) info = models.TextField() The Raw SQL is: select * from project_projectadditionalinfo A left join project_project B on A.project_id=B.id where B.id is null What will be the django query in response to the raw sql provided? Thanks in Advance. -
Deletion of an object in SQLite3 outputs a different error than Postgres
I have a Django and pytest-django project and I'm encountering a weird issue. My prod env has a Postgres DB and when running local tests I use SQLite3. Our DB schema look like this class A(BaseModel): # Some properties class B(BaseModel): a = models.ForeignKey(A, on_delete=DO_NOTHING, null=False) # Some other properties Assuming I have 2 objects (a which is an instance of A, and b which is an instance of B), deleting object a before deleting b will raise the following error on Postgres: django.db.utils.IntegrityError: update or delete on table \"db_a\" violates foreign key constraint \"db_a_id_32c056c8_fk\" on table \"db_b\" However, running the same code locally, using the (in-memory version of) SQLite, will raise: django.db.utils.IntegrityError: The row in table 'db_b' with primary key '453c667321254983915068259f6a999f' has an invalid foreign key: db_b.a_id contains a value 'b8fd641710be466ca8eab451faaed757' that does not have a corresponding value in db_a.id. So, in both cases, the deletion operation will output an error - but not the same one. I have no issues with the fact that an error is raised, but I would like my local unit tests to have the same error outputted as my remote one without changing the DB locally to PG. Any insights into this behaviour, … -
Image Gallery paginate through pure JavaScript
Django Here is my Django Template, to fetch images from database through {% for Nslide, Products, range in allProducts %}, now I want to pagination for each three Carousel using pure JavaScript no jQuery, how it's possible? I searched a lot but all the solution are based on Array, or tables not for Gallery. Thanks.. {% for Nslide, Products, range in allProducts %} <div id="carousel{{forloop.counter}}" class="carousel slide carousel-fade" data-bs-ride="carousel"> <ul class="carousel-indicators"> <button type="button" data-bs-target="#carousel{{forloop.counter}}" data-bs-slide-to="0" class="active"></button> <!-- Start of Range forloop --> {% for i in range %} <button type="button" data-bs-target="#carousel{{forloop.parentloop.counter}}" data-bs-slide-to="{{i}}"></button> {% endfor %} <!-- End of Rang forloop --> </ul> <!-- Start of Div => pricing --> <div class="pricingdiv" id="slider-wrapper"> <div class="carousel-inner "> <!-- Start of Carousel-item Active --> <div class="carousel-item active"> <!-- Start of (Product) forloop --> {% for i in Products %} <!-- Start of Div (Col) --> <div class="col-xs-3 col-sm-3 col-md-3 p-2 mt-3 reveal"> <!-- Start of Div (productHover) --> <div class="productHover gallery-items"> <div class="card card-body"> <img src='{{i.Product_Image}}' class="xzoom rounded-circle border card-img-top" /> <!-- start Div (card-body) --> <div class="card-body"> <h5> <strong> <a class="dark-grey-text">{{i.Product_name}}</a> </strong> </h5> <p class="card-text">{{i.Product_Description}}</p> <div class="row"> <div class="col-sm-12 "> <button id="pr{{i.id}}" class="btn btn-primary btn-sm shoppingCart" onclick="('productId = {{i.id}}')">Add to Cart</button> </div> … -
Why Django Channels test suites and consumers are using different databases?
Today, I ran into a problem with Django channels. I noticed that my test suites and and my consumers are using different databases. For example if I create a fake User object (for authentication) in my test suites, My consumer doesn't have access to that fake user. When I inspected the value of User.objects.all() inside my test suite, I got my fake user in the queryset but when I evaluated the same expersion inside my consumer's connect method, I got my real users in the original database which clearly shows that my consumer is not using the test database but it is using the original database. I wanted to know why my consumer is using the original database instead of the test database which is supposed to contain fake data for testing purposes? Here are all the packages I have installed: aioredis==1.3.1 asgiref==3.4.1 async-timeout==3.0.1 attrs==21.2.0 autobahn==21.3.1 Automat==20.2.0 autopep8==1.5.7 certifi==2021.5.30 cffi==1.14.6 channels==3.0.4 channels-redis==3.3.0 charset-normalizer==2.0.4 constantly==15.1.0 cryptography==3.4.7 daphne==3.0.2 Django==3.2 django-cors-headers==3.7.0 django-crum==0.7.9 django-extensions==3.1.3 django-filter==2.4.0 django-random-queryset==0.1.3 django-schema-graph==1.2.0 django-spaghetti-and-meatballs==0.4.2 djangorestframework==3.12.4 djangorestframework-recursive==0.1.2 djangorestframework-simplejwt==4.6.0 drf-spectacular==0.15.1 factory-boy==3.2.0 Faker==8.10.2 gunicorn==20.1.0 hiredis==2.0.0 hyperlink==21.0.0 idna==3.2 incremental==21.3.0 inflection==0.5.1 jsondiff==1.3.0 jsonschema==3.2.0 Markdown==3.3.4 msgpack==1.0.2 Pillow==8.2.0 psycopg2-binary==2.8.6 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.7.0 pycparser==2.20 PyJWT==2.1.0 pyOpenSSL==20.0.1 pyrsistent==0.18.0 python-dateutil==2.8.2 python-dotenv==0.15.0 pytz==2021.1 PyYAML==5.4.1 requests==2.26.0 service-identity==21.1.0 six==1.16.0 sqlparse==0.4.1 text-unidecode==1.3 toml==0.10.2 Twisted==21.7.0 … -
django custom tags that returns a boolean - using in a boolean expression in template results in "Unused 'foo' at end of if expression."
I am using Django 3.2 I am writing custom template tags for my project. This is some of my code: /path/to/myapp/templatetags/wanna_be_starting_something.py @register.simple_tag(name='can_dance_with', takes_context=True) def can_dance(context, danceable_object): request = context['request'] user = request.user if isinstance(danceable_object, Danceable): return danceable_object.can_dance(user) return False /path/to/myapp/templates/myapp/dancing.html {% load wanna_be_starting_something %} {% if can_dance_with nicegirl %} <div class="col">Nice!</div> {% else %} <div class="col">Oh Dear!</div> {% endif %} When I run the HTML above, I get the error message: Unused 'nicegirl' at end of if expression. If I remove the if conditional - it runs fine. How can I write a custom tag that returns a boolean that can be used in conditional expressions in the calling template? -
Overriding templates with Django 3.2.6
I am new to python and working through a Zero to Hero course by Mosh on YouTube. I am getting stuck on a problem, and even after going through all the Django documents (https://docs.djangoproject.com/en/3.2/howto/overriding-templates/) I just can't see where I am going wrong. I have tried pasting the file path for the base.html file directly, as well as other methods such as os.path.join(BASE_DIR, 'templates') to try find the right path. But I still get an error. Here is what I think all the code someone would need to understand the problem. Sorry if I have copied too much, but I am not sure what I actually need to show for someone to fully understand where I might have gone wrong. The overall project is call PyShop and I have a file called index.html which is located in PyShop\products\templates\index.html which is trying to call the base.html file by {% extends 'base.html' %}. The base.html file is located here PyShop\templates\base.html. When I run I get the below error. If I move the base.html file out from under the templates folder and just have it on it's own like this PyShop\base.html ie not in any subfolder then it works no problem. TemplateDoesNotExist at … -
Django importing CSV into model: matching query does not exist
I have the following Django project called Auditor, with 2 apps called main and backend. I am trying to upload csv content into a model, everything seems to be working fine until i try to upload the file, resulting in the following error: DoesNotExist at /upload/1 Csv_dv matching query does not exist. I created the model for CSV file, model for the CSV content and Form to contain the csv fields. Here is my Models.py: class Csv_dv(models.Model): file_name = models.FileField(upload_to='main') #The media folder will contain CSV file uploaded = models.DateTimeField(auto_now_add=True) # The uploaded time activated =models.BooleanField(default=False) # If file successfully uploaded to return true def __str__(self): return f"File id: {self.id}" class dv_model(models.Model): Defect_Area_dv = models.CharField(_('Defect Area dv'), max_length=200 ) Key_Driver_dv = models.CharField(_('Key Driver dv'), max_length=200) Sub_Key_Driver_dv = models.CharField(_('Sub Key Driver dv'), max_length=200 ) QS_Login_dv = models.CharField(_('QS Login dv'), max_length=200) QS_Name_dv = models.CharField(_('QS Name dv'), max_length=200) Status_dv = models.CharField(_('Status dv'), max_length=200) Correct_Associate_Action_dv = models.CharField(_('Correct Associate Action dv'), max_length=200) Correct_investigator_Action_dv = models.CharField(_('Correct investigator Action dv'), max_length=200) Action_Correctly_Captured_dv = models.CharField(_('Action Correctly Captured dv'), max_length=200) Audit_Outcome_dv = models.CharField(_('Audit Outcome dv'), max_length=200) Document_Name_dv = models.CharField(_('Document Name dv'), max_length=200) Document_Type_dv = models.CharField(_('Document Type dv'), max_length=200) Type_of_Audit_dv = models.CharField(_('Type of Audit dv'), max_length=200) If_Correctly_Captured_No_dv =models.CharField(_('If Correctly Captured … -
how to display the contents displayed in another html inside a div of the parent html file
The below code shows that when the anchor tag is clicked the content related to that specific title is retrieved and shown in another html page name doc1.html. The link that redirects it to next page in present in this file. judge_civil.html file <div class="container-middle"> <div id="limitations" class="tabcontent"> {% for data in law_data %} {% if data.law_type == 'civil' and data.law_category == 'limitations' %} <div class="tab"> <!--<button class="tablinks" onclick="openLawtype(event,'title')">{{data.title}} &nbsp<i class="fas fa-chevron-circle-right"></i></button>--> <a href="{% url 'doc1' data.pk %}" target="_blank">{{data.title}}</a ><br /><br /> </div> {% endif %} {% endfor %} </div> </div> Here when the link is clicked the content that is associated with {{data.title}} is opened and displayed in a new html file dynamically using the primary key that i have passed along with it. The code in doc1.html is below <p>{{ object.judgements|safe}}</p> But now I want to display this content that is being displayed in doc1.html in the judge_civil.html inside the below : <div class="container-right"></div> I assume that this can only be done with javascript. I don't know javascript at all so if you can provide me the code to this task it will be really helpfull. I am also providing the models and viwes and urls code if … -
how to access to through field in ManyToMany relation to convert to json django
i'm trying to change my object to json response but the database has some relations class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,related_name='rooms') takes_by = models.ManyToManyField('vistors.Vistor',through='BookingVisitor',related_name='vistors') class BookingVisitor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT,related_name='visitor_admin') visitor = models.ForeignKey('vistors.Vistor',on_delete=models.PROTECT,related_name='visitor_booking') booking = models.ForeignKey(Booking,on_delete=models.PROTECT,related_name='booking_bookingvisitors') reason = models.CharField(max_length=50) class Vistor(models.Model): full_name = models.CharField(max_length=150) city = models.ForeignKey(City,on_delete=models.CASCADE) gender = models.CharField(max_length=10,choices=genders,default=male) date = models.DateTimeField(auto_now_add=True) and my views.py def booking_detail(request,id): obj = get_object_or_404(Booking.objects.annotate(no_persons=Count('takes_by')),id=id) visitors = [] for i in obj.takes_by: print(i.full_name,i.city,i.visitor_booking.reason)#'RelatedManager' object has no attribute 'reason' visitors.append({ 'full_name':i.full_name, 'reason':i.visitor_booking.reason }) but it returns this error : 'RelatedManager' object has no attribute 'reason' i also tried this print(i.full_name,i.city,i.visitor_booking.get(visitor__id=i.id,booking_bookingvisitors__id=i.vistors.id)) it returns this error : 'ManyRelatedManager' object has no attribute 'id' thank you for helping .. -
Weasyprint not Showing images after deployment of Django Project
I have recently deploy a Django project, weasyprint was not loading properly it was returning several errors, now that they are fixed I am facing an image issue which is not showing on the PDF: The image is parked in: static/img/report-cover.jpg I also added it to be dynamic with the following models: class Info(models.Model): logo = models.ImageField(null=True, blank=True) Here is the settings.py to have a full picture of my trials: STATIC_URL = '/static/' #if DEBUG: # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] #else: #STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static' )] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here is the pdf.html trial 1: {% load static %} <link rel="stylesheet" href="{% static '/css/report.css' %}" /> <style> @page :first { background: url('/static/img/report-cover.jpg') no-repeat center;} </style> Trial 2: <style> @page :first { background: url('{{ info.logo.path }}') no-repeat center;} </style> Trial 3: <style> @page :first { background: url('{{ info.logo.url}}') no-repeat center;} </style> Here is the views.py def admin_order_pdf(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/pdf.html', {'info': info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(info.id) # response['Content-Disposition'] = 'attachment; filename="order_{}.pdf"'.format(info.id) weasyprint.HTML(string=html,base_url=request.build_absolute_uri()).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '/css/report.css')], presentational_hints=True) return response From this answer I have changed the following but still didn't work: weasyprint.HTML(string=html,base_url=request.build_absolute_uri("/")).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '/css/report.css')], presentational_hints=True) I … -
Django annotate field with queryset of objects
Supponse I have two models: ModelA and ModelB How can I annotate a queryset of ModelB with objects from ModelA? queryset = ModelB.objects.filter(...).annotate(models_a=Subquery(ModelA.objects.filter(...))) In order to have queryset.models_aas a Queryset of objects ModelA. Thanks you all! -
How can we paginate the older messages in Django channels?
I have an interface with Flutter that requests connection to a websocket using Django channels. The websocket is frequently sending real time data. When the connection is made to the websocket, all the older messages are currently sent at once. I want to paginate the older messages. What is the best way or best practice to make the pagination for the interface. The current consumer code is like this: def fetch_messages(self, data): messages = get_last_10_messages(data['chatId']) content = { 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): user_contact = get_user_contact(data['from']) message = Message.objects.create( contact=user_contact, content=data['message']) current_chat = get_current_chat(data['chatId']) current_chat.messages.add(message) current_chat.save() content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'id': message.id, 'author': message.contact.user.username, 'content': message.content, 'timestamp': str(message.timestamp) } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message } def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) self.commands[data['command']](self, data) def send_chat_message(self, message): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) def send_message(self, message): self.send(text_data=json.dumps(message)) def chat_message(self, event): message = event['message'] self.send(text_data=json.dumps(message))