Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got ModuleNotFoundError error while running app from docker-compose. How can i solve this?
I got following error while running from docker-compose but it works fine when I run docker run . Can some body help me to debug this. Error: File "/home/desktop/.local/bin/docker-compose", line 5, in <module> from compose.cli.main import main File "/usr/lib/python3.10/site-packages/compose/cli/main.py", line 19, in <module> from ..config import ConfigurationError File "/usr/lib/python3.10/site-packages/compose/config/__init__.py", line 3, in <module> from .config import ConfigurationError File "/usr/lib/python3.10/site-packages/compose/config/config.py", line 48, in <module> from .validation import match_named_volumes File "/usr/lib/python3.10/site-packages/compose/config/validation.py", line 8, in <module> from jsonschema import Draft4Validator File "/usr/lib/python3.10/site-packages/jsonschema/__init__.py", line 21, in <module> from jsonschema._types import TypeChecker File "/usr/lib/python3.10/site-packages/jsonschema/_types.py", line 3, in <module> from pyrsistent import pmap ModuleNotFoundError: No module named 'pyrsistent' My Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED=1 RUN apk update \ && apk add --no-cache --virtual .build-deps RUN pip install --upgrade pip ENV APP_DIR /home/myapp WORKDIR ${APP_DIR} ADD requirements.txt ${APP_DIR}/ RUN pip install -r ${APP_DIR}/requirements.txt COPY . . EXPOSE 8000 ENTRYPOINT sh -c "python manage.py runserver 0.0.0.0:8000" my docker compose file: version: "3.9" services: web: build: context: . volumes: - .:/home/myapp ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 container_name: django_myapp restart: always env_file: .env While I run docker-compose build I get above error. I have Tried adding pyrsistent in requirements.txt but error is still same. How to solve … -
Django get data in serializer from two steps away related table
I have the below models: class Campaign(Base): name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) class SubTopic(Base): name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) class CampaignSubTopicAssn(Base): campaign = models.ForeignKey(Campaign, related_name='subtopic_assn', on_delete=models.CASCADE) subtopic = models.ForeignKey(SubTopic, related_name='campaign_assn',on_delete=models.PROTECT) class Meta: unique_together = ('campaign', 'subtopic') class CampaignSubTopicAssnSerializer(serializers.ModelSerializer): class Meta: model = org_models.ContextualCampaignSubTopicAssn fields = ['subtopic'] In my campaign serializer I want to fetch all the subtopic_ids and their display_name as well: currently this serializer just gives the ids and not the name, basically the table is two steps away in relation. class CampaignSerializer(serializers.ModelSerializer): subtopic_assn = CampaignSubTopicAssnSerializer(many=True) -
Django Google News Sitemap
Does anyone know how to implement the google news sitemap standard on Django? https://developers.google.com/search/docs/advanced/sitemaps/news-sitemap I am struggling to find any mention of how its implemented with Django. Example of how it should look. <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"> <url> <loc>http://www.example.org/business/article55.html</loc> <news:news> <news:publication> <news:name>The Example Times</news:name> <news:language>en</news:language> </news:publication> <news:publication_date>2008-12-23</news:publication_date> <news:title>Companies A, B in Merger Talks</news:title> </news:news> </url> </urlset> What I currently have looks very simple. <url> <loc>https://mynewsite.net/news/this-news-article/</loc> <lastmod>2022-04-04</lastmod> </url> <url> -
ModuleNotFoundError how to import my flie in django.view
I want to import my python files in django app import myfile dct = myfile.myfunc() def index(request): context = dct return render(request, 'myapp/index.html', context) >>>ModuleNotFoundError: No module named -
Django how to prevent patched method running when created in super class
I have a model with a post-save method that I don’t want to run in test: class MyModel(models.Model): def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) self.post_save_method() def post_save_method(self): print("oh no!") return "real value" If I make a normal test everything works as I would expect. I can patch the method, and see that I get the mocked return value, and that the post_save_method does not run (nothing is printed from this method to the console): from django.test import TestCase from .models import MyModel from unittest.mock import patch class TestMakeObjectNormally(TestCase): @patch.object(MyModel, 'post_save_method') def test_something(self, post_save_mock): post_save_mock.return_value = "mocked value" my_model = MyModel.objects.create() print(my_model.post_save_method()) But the way the tests are set up is that the instance is created in a superclass. Following this gist I tried to patch at a class level: class BaseTest(TestCase): def setUp(self): self.my_model = MyModel.objects.create() @patch.object(MyModel, 'post_save_method') class TestMakeObjectInSuper(BaseTest): def setUp(self): super().setUp() def test_something(self, post_save_mock): post_save_mock.return_value = "mocked value" print(self.my_model.post_save_method()) This works in that the post_save_method return value is the mocked one, but unfortunately I can see that the method is running (“oh no!” is printed to the console). (I also tried patching both setUp() methods and the base class) Any advice appreciated! -
django mocking serializer __init__
I want in my test to mock the __init__ of a serializer as follow : serializer = MySerializer(data={'name':'yosi'}) serializer.data # will return {'name':'yosi'} and ignore default behavior, like requiring to call is_valid first I just want the serializer to store data as is, and not do the usual __init__ The method I want to test : MyDAO.py : from ..models import MyModel from ..serializers import MySerializer def getAll() -> list[dict]: entities = MyModel.objects.all() serializer = MySerializer(entities, many=True) return serializer.data I tried the following, with no success : def _mocked_seriailzer__init__(self, data, many): self.data = data @mock.patch('<PATH_TO_SERIALIZERS_FILE>.MySerializer.__init__', _mocked_seriailzer__init__) @mock.patch.object(MyDAO, 'MyModel') def test_getall(self, model): mockedData = ['mocked-data1', 'mocked-data2', 'mocked-data3'] model.objects.all.return_value = mockedData self.assertEqual(mockedData, MyDAO.getAll()) but it complains that the test is missing 1 required positional argument: 'many' def _mocked_seriailzer__init__(self, data, many): self.data = data @mock.patch.object(MyDAO, 'MySerializer.__init__', _mocked_seriailzer__init__) @mock.patch.object(MyDAO, 'MyModel') def test_getall(self, model): mockedData = ['mocked-data1', 'mocked-data2', 'mocked-data3'] model.objects.all.return_value = mockedData self.assertEqual(mockedData, MyDAO.getAll()) but it says that the MyDAO does not have the attribute 'CctSerializer.__init__' how to mock the serializer.init correctly? -
Python Fixtures:AttributeError: 'list' object has no attribute 'replace'
I am trying to load fixtures from a JSON file but get the above mentioned error when I run python3 manage.py loadfixtures /path/to/fixture.json. The fixture tries to model categories and their subcategories. Is this the most efficient way of loading default data on a database? My code and error logs are as shown below. Here are my models class SubCategory(BaseModel): description = models.TextField(null=True, blank=True) class Category(BaseModel): description = models.TextField(null=True, blank=True) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE, related_name="category_subcategory") Here are my sample fixtures [{ "model": "accounts.category", "pk": 1, "fields": { "description": "Agricultural Businesses and cooperatives", "sub_category": [ { "model": "accounts.subcategory", "pk": 56, "description": "Piece Goods, Notions, and Other Dry Goods" }, { "model": "accounts.subcategory", "pk": 158, "description": "Florists" } ] } }] And here is the error log Traceback (most recent call last): File "/django-project/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 2434, in to_python return uuid.UUID(**{input_form: value}) File "/usr/lib/python3.10/uuid.py", line 174, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'list' object has no attribute 'replace' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/django-project/venv/lib/python3.10/site-packages/django/core/serializers/python.py", line 134, in Deserializer value = base.deserialize_fk_value(field, field_value, using, handle_forward_references) File "/django-project/venv/lib/python3.10/site-packages/django/core/serializers/base.py", line 322, in deserialize_fk_value return model._meta.get_field(field_name).to_python(field_value) File "/django-project/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 2436, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: … -
Write permission nginx gunicorn
In my django/python code I have the following lines: f = open(os.path.join(DIRECTORY, filname), 'w') f.write(filecontent) f.close() when I have DIRECTORY='/tmp/' it all works fine, the file.txt is saved with owner=root and group=www-data. However, when I want to save the file in a subdirectory of my django-project, for example DIRECTORY='/project/subfolder' the file doesn't appear, although I have that subfolder set to the same owner/group. I suspect that it is a permission problem with nginx or gunicorn. Any suggestions? I tried to solve my problem by just mounting the /tmp/ directory to the docker container where I use the file afterwards. But I ran into the problem, that files in the /tmp/ directory do not appear in docker, while as when I mount another folder like /project/subfolder/, these files do appear in docker. So either way, half works, but never both. -
Creating multiple Profiles instead of one In Django
When logging in, create a profile, But when logging out and then logging in with that same username, It again says to me to create a profile and creates two profiles instead of one. #For Cystomer Registration class CustomerRegistrationView(View): def get(self,request): form = CustomerRegistrationForm() return render(request,'mp/register.html',{'form':form}) def post(self,request): form = CustomerRegistrationForm(request.POST) if form.is_valid(): messages.success(request,'Congratulations Registerd Succesfuly ') form.save() success_url = reverse_lazy('profilecreate') return render(request,'mp/register.html',{'form':form}) #For Creating Profile class ProfileCreate(LoginRequiredMixin,CreateView):#ye hogia hamara upload wala model = Profile fields = ['user_name','user_ethnicity','SelectGender','user_job','user_age','mother_additionalinfo'] success_url = reverse_lazy('profile') def form_valid(self,form): form.instance.user = self.request.user success_url = reverse_lazy('profile') return super(ProfileCreate,self).form_valid(form) here are my URLs #for register path('register/',views.CustomerRegistrationView.as_view(),name= 'register'), #for CreateProfile path('profilecreate/',views.ProfileCreate.as_view(),name= 'profilecreate'), when User Created and I remove the loginrequiredmixin from profilecreateview. It give me an error of Page No Found With This Url:127.0.0.1:8000/accounts/login/?next=/profilecreate. It does not go to Profile Create View because it is not logged in but just Registered. And I want the User Go to Profilecreateview only one time. Later he can Update it. – -
Page Number in Django Template
Here is a Django template. {% for balance in balances %} {{ balance.amount }} {% endfor %} {% for price in price %} {{ price.amount}} {% endfor %} I would like to show multiple values in Django template like one after another. I also need to print the page number. For example, 1,2,3,4 page for balance and 5,6,7 is used for the price. So is there any way I can print it? -
how to make group join and leave functionality in Django?
def join_group(request,pk): group = Room.objects.get(id=pk) group.members.add(request.user) return redirect('home') urls.py path('create_group', views.create_group, name="create-group"), path('group/<str:pk>', views.group, name="group"), path('join_group/<str:pk>', views.join_group, name="join_group"), feed.html <a href="{% url 'join_group' group.id %}"> <p class="roomListRoom__topic"> Join </p> </a> I have group in my app. I wanted to make join and leave functionality. Join functionality is working properly but i want to make when ever anyone clicks on (join) then he should be redirected to that particular group when i change return redirect to ' return redirect ('group/' + str(pk)) ' then i am getting url like 127.0.0.1:8000/join_group/group/8..... and i want to make that if the user is joined to group then there should be joined instead of join and join for other users. - using if statement and i want to make leave functionality: please help me to get out of these problems.. if you need more info .. i am ready thank you in advance!!! -
Django 4 Giant Enormous Bug Report
Bug description: Page A is accessed directly, Click something on page A goes to page B, Press back button back to Page A, And simple html elements on Page A will stop working with Safari. The website link live: https://howtoback.com/ Django 3 no such bug Days of work to find the bug, Please fix in the upcoming Django releases. -
django no module named 'settings'
i inherited a python project where django is used. for my devs, i needed the transaction module of django. so i went to 'P:\file\ourLibrary\server\config\settings.py' and updated the **DATABASES = { 'default': { filled infos }** then in Powershell i set the ENV_VARIABLE DJANGO_SETTINGS_MODULE to the path specified before i then tried to use the function that uses the @transaction.atomic but i had the folowing error > You must either define the **environment variable > DJANGO_SETTINGS_MODULE** or call **settings.configure()** before > accessing settings. which i don't understand because i already setted it. i found various posts in StackOverflow that suggest to use import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','P:\file\ourLibrary\server\config\settings') but now when i use the @transaction function i got ModuleNotFoundError: No module named **'P:\file\ourLibrary\server\config\settings'** what am i doing wrong here? thank you for your help, -
Django - How to make a model that when an instance of this model is created, that data is saved to a page that is unique to a user
I'm making a website where you can post jobs to an 'explore page', and I was then wondering how I would go about making it so that when a job is posted to that 'explore page', that job will also be posted to a page where the person who posted the job can manage all of the jobs they have posted i.e. edit, delete. I can post jobs to the explore page but I need to find a way for the job to save to the 'employers' page views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from base.forms import JobForm @login_required(login_url='login') def manage_jobs(request): if request.user.is_employee: return redirect('home') else: form = JobForm(request.POST) if form.is_valid(): form.save() context = {"form":form} return render(request, 'employer/manage-jobs.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.manage_jobs, name='manage-jobs'), ] models.py class Job(models.Model): company = models.CharField(max_length=40, null=True, verbose_name="Company/Employer") description = models.TextField(null=True) role = models.CharField(max_length=25) area_of_filming = models.CharField(max_length=50, verbose_name="Area Of Filming", default="") contact_email = models.EmailField(verbose_name='Contact Email', max_length=60, default='') created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.company class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) name = models.CharField(max_length=45, unique=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
Django - static files not showing inside sources tab
In my folder of static files i have two images, a javascript file and a css file but when i look inside the browsers sources tab one of my images like_icon_LIKED.png does not appear. This causes errors in my javascript file when trying to change the images src path as the image cannot be found. No idea why this is happening -
how to add file path in django project
I am making an online judge in Django. I am taking user code in a file and then compile it and running it and giving the verdict. for example let say a user submitted code in c++ language so I am taking that code in a .cpp file and compile it and running it and I am doing it by giving the absolute path of my .cpp file like E:\online_judge_project\oj\language\forcpp.cpp my problem is that when I will deploy my project it will cause error because this paths are my local machine path and I can't use that in deployment so how will I access the files( like .cpp file) after the deployment. Although those files are in my project directory only and I kept them in a folder name language. my project directory structure is like: I am thinking of using os.join.path() but I am not getting how to do that. -
How can i auto increment and shorten a string as textfield?
im currently trying to do a project management app and i need to autoincrement project count and add shortened string from department. For example if Product Development add a project to site i need to show in table like this PD_1 -
profile shape not partially saved
After the first registration, it transfers to a new form - you can enter a profile email, photo, bio, links to twitter, github and other social networks, 2 models participate: ProfileUser and User. When a person wrote what he wanted and pressed the button, after the transition he clicked on the user and then he was thrown to the profile page, but there, apart from the mail, nothing from the previously entered is shown, when trying to change the profile, nothing is shown either, there is nothing in the form, I went in the admin panel in the model, only the user is also set automatically when switching to creating a profile after registration, other data is simply not entered, please tell me how to fix it The user appears to me because this is in the registration profile = ProfileUser.objects.create(user=new_user) I tried to redo it according to this article did not work models.py class ProfileUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) img = models.ImageField(null=True, blank=True, upload_to='static/images/', validators=[img__size]) birthday = models.DateField(blank=True, null=True) about = models.TextField(max_length=1000, null=True) #? social media twitter = models.URLField(null=True, blank=True) facebook = models.URLField(null=True, blank=True) instagram = models.URLField(null=True, blank=True) telegram = models.URLField(null=True, blank=True) vk = models.URLField(null=True, blank=True) reddit = … -
pytest-django Use env vars in settings.py
I have an api in Django that uses quite a few environment variables. The idea is to add pytest-django to test all its functionalities (I know it would have been smarter to build the tests together with the project). Currently it is in the manage.py file where I load the environment variables as follows: def main(): dotenv.read_dotenv() And in my api settings.py file I use some of these environment variables as follows: os.environ.get('one_key') In my pytest.ini file I have correctly configured my settings.py as follows: DJANGO_SETTINGS_MODULE = api.settings The problem is that when I run pytest I get the error that it does not find those environment variables, because the manage.py has not been executed and therefore these have not been loaded. Is there any way to make pytest load an .env before running the tests and the settings.py? -
Why doesn't css styles apply to html correctly in django?
Only body styling work in django, I use static files to get css. I tried even commenting out body part css, but it still works, I don't know how, I don't know why, please help! (I've used collectstatic, so it's not because of that). I've inserted static_root and url and other things in setting to, but it didn't help either. body{ max-width: 1080px; margin: auto; background: #8D7D77; font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; } /* ----------------------------------------------NAV-BAR-UPPER------------------------------------------ */ .nav-bar{ display: flex; flex-direction: row; padding-top: 20px; } .nav-bar img{ max-width: 150px; margin-left: 20px; } .nav-bar ul{ list-style: none; display: flex; flex-direction: row; } .nav-bar ul li{ margin-right: 15px; } .nav-bar ul a{ text-decoration: none; color: white; font-size: 20px; margin-left: 80px; padding: 10px 20px 10px 20px; border: solid 1px; border-radius: 10px; } .nav-bar ul a:hover{ text-decoration: none; color: #8D7D77; background-color: white; } .search-bar{ width: 600px; height: 40px; margin-top: 10px; margin-left: 50px; border-radius: 5px; border-width: 1px; border-color: #C2B280; font-size: 110%; } .search-bar:focus{ border-style:none; } {% load static %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static 'styles/main.css' %}" /> <link rel="icon" href="{% static 'images/logomogo.png' %}" /> <title>BookShelf</title> </head> <body> {% … -
how to set object admin moderation in drf
I am using python 3.8 and django 4.0.6 + drf 3.13.1 There are models class Profile(models.Model): user='US' manufacturer = 'MA' admin='AD' choice=[ (user, 'User'), (manufacturer, 'Manufacturer'), (admin, 'Admin') ] user_company = models.CharField(max_length=2, choices=choice) user = models.OneToOneField(User, on_delete=models.CASCADE) last_request = models.JSONField(null=True) class ProfileCompany(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.OneToOneField('Company', on_delete=models.CASCADE) classCompany(models.Model): id_company = models.IntegerField(null=True, unique=True) Company = models.CharField(max_length=128) Direction = models.CharField(max_length=512, blank=True) Description = models.TextField(null=True, blank=True) Categories = ArrayField(base_field=models.CharField(max_length=128), null=True, blank=True) Products = ArrayField(base_field=models.CharField(max_length=128), null=True, blank=True) Serializer class CompanySerializer(serializers.ModelSerializer): class Meta: model=Company fields = '__all__' The task is to make the pre-moderation of the creation and updating of companies by the admin. Manufacturer creates a new company or updates data in it, this data is not visible to all users, but only to the admin. The admin accepts or rejects this data with a comment (in this case, the Manufacturer receives a message with this comment, corrects the data and sends the data again for moderation) I could not connect django-moderation, because it is not suitable for REST. Are there ready-made libraries or solutions? -
Size not being displayed on productdetails page
I am doing CRUD using serializers and foreign keys and I have made a product details page which shows the details of the product that I have clicked. The problem is that the Size(SM,M,L,XL,XXL) itself isn't coming but the id is coming as shown below below is the 'productdetails' function <tr> <td>{{data.id}}</td> <td>{{data.title}}</td> <td>{{data.price}}</td> <td>{{data.sku_number}}</td> <td>{{data.product_details}}</td> <td>{{data.size}}</td> <td>{{data.quantity}}</td> <td><img src="{{data.image}}" alt="product image" width="400" height="400"></td> </tr> productdetails function def productdetails(request,id): prod = Products.objects.get(id=id) product = POLLSerializer(prod) return render(request,'polls/productdetails.html',{'data':product.data}) model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) Help is greatly appreciated,thanks! -
"Page not found error" after enabling Login required (CMS_Permission)
I would like to password protect a page on my website. For this I set CMS_PERMISSION = True in settings.py. And under Page > Permission I checked login required. The following error appeared when I tried to visit the page: Page not found (404) Request Method: GET Request URL: http://localhost:8000/en/accounts/login/?next=/en/private/ Raised by: cms.views.details Using the URLconf defined in backend.urls, Django tried these URL patterns, in this order: en/ ^jsi18n/$ [name='javascript-catalog'] ^static/(?P<path>.*)$ en/ ^admin/ en/ ^ ^blog-content/\Z [name='posts-latest'] en/ ^ ^blog-content/feed/\Z [name='posts-latest-feed'] en/ ^ ^blog-content/feed/fb/\Z [name='posts-latest-feed-fb'] en/ ^ ^blog-content/(?P<year>[0-9]+)/\Z [name='posts-archive'] en/ ^ ^blog-content/(?P<year>[0-9]+)/(?P<month>[0-9]+)/\Z [name='posts-archive'] en/ ^ ^blog-content/author/(?P<username>[^/]+)/\Z [name='posts-author'] en/ ^ ^blog-content/category/(?P<category>[^/]+)/\Z [name='posts-category'] en/ ^ ^blog-content/tag/(?P<tag>[-a-zA-Z0-9_]+)/\Z [name='posts-tagged'] en/ ^ ^blog-content/tag/(?P<tag>[-a-zA-Z0-9_]+)/feed/\Z [name='posts-tagged-feed'] en/ ^ ^blog-content/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/(?P<slug>[^/]+)/\Z [name='post-detail'] en/ ^ ^blog-content/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<slug>[^/]+)/\Z [name='post-detail'] en/ ^ ^blog-content/(?P<category>[^/]+)/(?P<slug>[^/]+)/\Z [name='post-detail'] en/ ^ ^blog-content/(?P<slug>[^/]+)/\Z [name='post-detail'] en/ ^ ^cms_login/$ [name='cms_login'] en/ ^ ^cms_wizard/ en/ ^ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] en/ ^ ^$ [name='pages-root'] en/ ^sitemap\.xml$ en/ ^taggit_autosuggest/ en/ ^filer/ The current path, /en/accounts/login/, didn’t match any of these. My urls.py looks like this: from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import include, re_path, path from django.views.i18n import JavaScriptCatalog from django.contrib.sitemaps.views import sitemap from cms.sitemaps import CMSSitemap from djangocms_blog.sitemaps import BlogSitemap urlpatterns = i18n_patterns( re_path(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), … -
How To Hide Form Fields When A Particular Type Of Product Is Selected Django
Please I have a project where I want to hide some fields in a form when the category selected belongs to a particular product type. The type of products is Single and Bundle products. So for instance, if I choose something like pens(Bundle) in the form category I should only see quantity in the form fields but if I select something like Desk(single) all fields should be available to fill. How do I implement this in Django? Thank you My Model TYPE =(('Single', 'Single'),('Bundle','Bundle')) class Category(models.Model): name = models.CharField(max_length=50, blank=True, null=True) pro_type = models.CharField(max_length=50, choices=TYPE, null=True) timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) def __str__(self): return f'{self.name}' class Product(models.Model): pro_name = models.CharField(max_length=100, blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) quantity = models.IntegerField(default='0', blank=True, null=True) issue_to = models.ForeignKey('Order',default='', on_delete=models.CASCADE,blank=True, null=True) serial_num = models.CharField(max_length=100, blank=True, null=True) model_num = models.CharField(max_length=100, blank=True, null=True) storage_size = models.CharField(max_length=50, blank=True, null=True) My views def add_products(request): form = ProductCreateForm(request.POST) if request.method == 'POST': if form.is_valid(): obj = form.save(commit=False) obj.staff = request.user obj.save() return redirect('dashboard-products') else: form = ProductCreateForm() context = { 'form': form, } -
Show image next to text using CSS/Bootstrap
i want to show image next to text. But its showing below it Here is the code <div class="container"> <div class="row"> <div class="col-md-8"> <h1>This is my first post</h1> <div> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard … </div> <div class="col-md-4"> <img src="/media/post/Screenshot_from_2022-07-17_23-55-13.png" class="img-thumbnail" > </div> <div><a href="/blog/first-post" >Read More..</a></div> <div class="col-md-8"> <h1>this is second post</h1> <div> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard … </div> <div class="col-md-4"> <img src="/media/post/0a61bddab956.png" class="img-thumbnail" > </div> <div><a href="/blog/2nd-post" >Read More..</a></div> </div> </div> This is how it look like EDIT. I copied this from view-source and some text is cut off there. Actually i am using Django jina 2 template code {% for post in context %} <div class="col-md-8"> <h1>{{ post.title}}</h1> {{ post.content |truncatewords:20 | safe}} </div> <div class="col-md-4"> <img src="/media/{{post.image}}" class="img-thumbnail" > </div> <div><a href="/blog/{{post.slug}}" >Read More..</a></div> {% endfor %} Here is base.html file code <div class="container"> <div class="row"> {%block content %} {%endblock%} </div> </div>