Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model object reuse without erasing data's
In my project I conduct one tournament on one date..so users are like to register the tournament..so I store users register info to my database.. Then the another Date I am conducting another tournament but this time I want to store the user info in the same model without erasing the old tournament data's in database. Because I don't want to create the new Model for every tournament Is there any possible ways to do that? any one help me thanks advance -
django when updating pass the required field
I want to update postModel in my template.But in models.py i don't use blank=True and null=True because when model is creating, i want from user can not pass this area without adding image.But when i was doing update, i want from user they can pass this area if they want and showing image link.How can i do this? models.py class postModel(models.Model): STATUS = ( ("yes" , "YES"), ("no" , "NO") ) image=models.ImageField( upload_to="post_images", ) title=models.CharField( max_length=100, blank=False, null=False ) slug=AutoSlugField(populate_from="title",unique=True) content=RichTextField() writer=models.ForeignKey(CustomUserModel,on_delete=models.CASCADE,related_name="articles") categories=models.ManyToManyField(CategoryModel,related_name="posts") is_slider=models.CharField(max_length=10,choices=STATUS,default="no",verbose_name="IS slider?") created_date=models.DateTimeField(auto_now_add=True) updated_date=models.DateTimeField(auto_now=True) readingCount=models.SmallIntegerField(default=0) is_published=models.CharField(max_length=10,choices=STATUS,default="no",verbose_name="Is published") forms.py class addPostForm(forms.ModelForm): class Meta: model = postModel fields=("title","categories","content","is_slider","image") widgets = { "title" : TextInput(attrs={"class":"form-control","style":"color: black; text-transform: none;"}), "categories" : SelectMultiple(attrs={"class":"form-control"}), "content" : Textarea(attrs={"class":"form-control"}), "is_slider" : Select(attrs={"class":"form-control"}), "image" : FileInput(attrs={"class":"form-control"}), } views.py @login_required(login_url="login_view") def update_post(request,slug): post=get_object_or_404(postModel,slug=slug) if request.method == "POST": form = addPostForm(request.POST or None,request.FILES or None) if form.is_valid(): post=form.save(commit=False) post.writer=request.user post.save() form.save_m2m() return redirect("update_post",slug=post.slug) else: return redirect("update_post",slug=post.slug) form=addPostForm(instance=post) context={ "form":form, "post":post, } return render(request,"update_post.html",context) -
django-admin is showing error ,How can i fix it?
When I run this command to create django project but it error, How can I fix it. C:\Users\pawat\Documents\madpro\testapp>django-admin startproject name . Traceback (most recent call last): File "c:\users\pawat\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\pawat\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\pawat\AppData\Local\Programs\Python\Python39\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\commands\startproject.py", line 21, in handle super().handle('project', project_name, target, **options) File "c:\users\pawat\appdata\local\programs\python\python39\lib\site-packages\django\core\management\templates.py", line 160, in handle with open(new_path, 'w', encoding='utf-8') as new_file: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\pawat\\Documents\\madpro\\testapp\\manage.py' -
Workaround for logging out a user logged in using HTTP Apache LDAP in django
In the Django 2.2 application, user is allowed to log in "through http (Apache LDAP)" by providing username and password in the browser prompt (as shown below): Problem is that when I logout the user using the default django logout defined in django.contrib.auth, the user is still able to access the application. In simple words, the django login and logout have no effect on the application. I have learnt that, the only way to logout the user is by closing the browser window. But I wanted to implement the logout functionality usin django. After a bit of googling about this issue, I found something relatable here, which shows the following method: class HttpAuthMiddleware(object): def process_request(self, request): if request.path == '/accounts/logout/': httpResponse = HttpResponse() httpResponse.status_code = 401 httpResponse.headers['WWW-Authenticate'] = 'Basic realm="<same realm as in the http server>"' return httpResponse else: # check for http headers - maybe the user is already logged in using http auth ... This is a workaround for the logout feature. It basically checks for the request.path == '/accounts/logout/' which helps me in using the default django logout function. I want this snippet to redirect the user back to the same login prompt that browser provides (as … -
How to get django syndicate to pull the hostname correctly
While using view reverse with django syndication, get_absolute_url() returns correctly but with wrong host, I'm always getting the link with http://localhost instead of my domain, where is that configured ? How to get it to return my hostname Thank you forum_patterns = [ path('p/<str:uid>/', views.post_view, name='post_view'), ] Post: def get_absolute_url(self): url = reverse("post_view", kwargs=dict(uid=self.root.uid)) return url if self.is_toplevel else "%s#%s" % (url, self.uid) getting: <rss version="2.0"> <channel> <title>Post Feed</title> <link>http://localhost/</link> <description>Posts that match africa</description> <atom:link href="http://localhost/feeds/tag/africa/" rel="self"/> <language>en-us</language> <lastBuildDate>Sun, 06 Jun 2021 03:56:58 +0000</lastBuildDate> -
How to refresh related objects in the django signals?
Here anothermodel_set represents the Foreign Key relationship to the AnotherModel from SenderModel. When Creating SenderModel I am not being able to query it's related objects to the AnotherModel SenderModel is being created normally by django generic CreateView. @receiver(post_save, sender=SenderModel) def some_signal(sender, instance, created, **kwargs): if created: if instance.parent_id: print(instance.id, instance, 'instance', flush=True) # returns id no issue instance.refresh_from_db() related_objs = AnotherModel.objects.filter(obj=instance) # returns None related_objs = instance.anothermodel_set.all() # returns None #But when Do this in shell related_objs = obj.anothermodel_set.all() # returns queryset -
Test Django with dictionary in dictionary data
Description I'm using Django for my website and trying to write some unit tests. However, when using dict in dict data I met some errors. I found out that view received slightly different data. From {'class_id': '1', 'filter_options': {'full_name': 'user 1'}} in data of test file to <QueryDict: {'class_id': ['1'], 'filter_options': ['full_name']}>. I means that value has changed to array, and value of nested dict wasn't detected. Code # test.py def test_search_with_full_name(self): data = {'class_id': '1', 'filter_options': {'full_name': 'user 1'}} response = self.client.post('/api/students', data, format='json') self.assertEqual(response.status_code, 200) # view.py class SearchStudentView(generics.GenericAPIView): def post(self, request): print(request.data) if not 'class_id' in request.data: return HttpResponse('class_id is required', status=400) class_id = request.data['class_id'] students = Users.objects.filter( details_student_attend_class__course__pk=class_id) if 'filter_options' in request.data: filter_options = request.data['filter_options'] if 'full_name' in filter_options: students = students.filter( full_name=filter_options['full_name']) Thanks for any help! -
How to create a slot interval between two hours in Django
I am trying to create slot intervals from two given times ie Input : Start time : 1:00 End time : 2:00 Output: 1:00-1:15 , 1:15 - 1:30, 1:30-1:45 , 1:45 - 2:00 Code I am currently using: THE SLOT GENERATOR import datetime def time_slots(start_time, end_time): t = start_time while t <= end_time: yield t.strftime('%H:%M') t = (datetime.datetime.combine(datetime.date.today(), t) + datetime.timedelta(minutes=15)).time() USAGE: >>> import datetime >>> start_time = datetime.time(13, 00) >>> end_time = datetime.time(14, 00) >>> list(time_slots(start_time, end_time)) THE ISSUE IS : If I give inputs as Start time as 9:00am ie datetime.time(9, 00) Endtime as 12:00am ie datetime.time(0, 00) then i get an empty list , So how do i solve it CODE REFERENCED FROM: Create 15-min slots between two hours in Django -
Notes should be showed only for the author
In my note taking project, I want to do so, that notes should be showed only for the author of the object. I am trying to solve this problem for 3 days. But, I could not solve this. Please Help! Thanks in an advance view.py @login_required(login_url='login') def index(request): tasks = Task.objects.all() if request.method=='POST': form = TaskForm(request.POST) if form.is_valid(): obj = form.save() obj.owner = request.user obj.save() return redirect('/') form = TaskForm() user = request context = { 'tasks' : tasks, 'form':form, 'obj':obj } return render(request, 'list.html',context) models.py class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title -
django session value not passing.The value is not passing while creating session in cart in ecommerce project
Iam creating an Ecommerce site and iam creating session to for the cart functionality.but my values is not passing to the session dictionary. basket.py ''' class Basket(): def __init__(self, request): self.session = request.session basket = self.session.get('skey') if 'skey' not in request.session: basket = self.session['skey'] = {} self.basket = basket def add(self,product): product_id=product.id print(product_id) if product_id not in self.basket: print(product.price) self.basket[product_id]={'price':product.price} print(self.basket[product_id]) print(self.basket) self.session_modified=True ''' views.py ''' def add_product(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id =int(request.POST.get('productid')) print(product_id) product = get_object_or_404(Product, id=product_id) print(product) basket.add(product=product) response=JsonResponse({'test':'data'}) return response ''' when i am printing all the values are showing in the terminal but when i am decoding the session key the value are not passing or showing {'skey': {}} are showing. -
How to use multiple if statements to color p tags
Im trying to color these four p tags based off of if they are either the correct answer or the one a user picked, there seems to be an error in the if statements however because it will only color it green or red, the loop doesnt go to color the red one for what the user picked and green for the correct answer <p {% if quiz.correctness1 == 0 %} {% if quiz.userAnswer1 == 'a' %} style="color:red;" {% endif %} {% endif %} {% if quiz.answer1 == 'a' %} style="color:green" {% endif %}> A. {{ quiz.q1Choice1 }}</p> <p {% if quiz.correctness1 == 0 %} {% if quiz.userAnswer1 == 'b' %} style="color:red;" {% endif %} {% endif %} {% if quiz.answer1 == 'b' %} style="color:green" {% endif %}> It will only color red if they are wrong and the if statements don't countinue to do both red and green -
How to nest these Serializes without facing AttributeError: 'BlogPost' object has no attribute 'review_set'
I followed Dennis Ivy proshop Tutorial He used the same approach as the code is class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = '__all__' class ProductSerializer(serializers.ModelSerializer): reviews = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = '__all__' def get_reviews(self, obj): reviews = obj.review_set.all() serializer = ReviewSerializer(reviews, many=True) return serializer.data Now I need a Blog for the eCommerce Project and I created another app named blog and Created the models as class BlogPost(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=200, null=True, blank=True, help_text="Like How To Treat Hypertension etc") image = models.ImageField(null=True, blank=True, default='/placeholder.png') rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) youtubeVideoLink = models.CharField(max_length=1000, null=True , blank=True) def __str__(self): return str(self.createdAt) class BlogPostReview(models.Model): blogpost = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.rating) But when I serialize them via same approach as mentioned above.... class BlogPostReviewSerializer(serializers.ModelSerializer): class Meta: model = BlogPostReview fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): blog_post_reviews = serializers.SerializerMethodField(read_only=True) class Meta: model = BlogPost fields = '__all__' def get_blog_post_reviews(self, obj): blog_post_reviews = obj.review_set.all() … -
How to test Django class base View method with pytest Client?
I am using Django to build a website and now I am running unittest with pytest, but I could't test my class base view method with pytest Client, I did it with RequestFactory but I want to run it also with Client. This is my test case Class. import pytest from django.contrib import auth from django.contrib.auth.models import User from django.forms import modelform_factory from django.urls import reverse, is_valid_path from company.models import Company from company.views import CompanyView @pytest.mark.django_db class TestCompanyView: @pytest.fixture def company_form(self): yield modelform_factory(Company, fields='__all__') @pytest.fixture def user(self, db): yield User.objects.create_user(username='admin', password='admin') @pytest.fixture def login_pass(self, client): yield client.login(**{'username': 'admin', 'password': 'admin'}) @pytest.fixture def login_fail(self, client): yield client.login(**{'username': 'admin', 'password': 'admi'}) def test_company_view_require_login_failed(self, client): path = reverse('companyview') assert is_valid_path(path) response = client.post(path, data={'saveForm': '-1', 'name_english': 'ITTech', 'mobile_number': 89897}) assert response.status_code == 302 # status_code will be 302 if login failed assert response.context is None def test_company_view_require_login_pass(self, client, user): path = reverse('companyview') assert is_valid_path(path) client.login(**{'username': 'admin', 'password': 'admin'}) response = client.post(path, data={'saveForm': '-1', 'name_english': 'ITTech', 'mobile_number': 89897}) assert response.status_code == 200 # status_code will be 200 if login pass assert '_auth_user_id' in client.session # checks that auth_user_id is in client session user = auth.get_user(client) assert user.is_authenticated # checks that logged in user is … -
Django : input field dropdown for receiver customized based on sender
I am trying to make my dropdown list for the receiver in which the sender's id/name won't be included. I guess this is not a case of chained dropdown which has been answered previously. Maybe ajax is needed to be used here, but I am not understanding the exact code of ajax, if it is to be used. Below are my template file, views.py file and models.py file. home.html <!DOCTYPE html> <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"> <title>Document</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'Bank_App/css/styles.css' %}" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"> </script> </head> <body> <div class="container"> <center> <h2>Customer Details</h2> </center> <table> <tr> <th>Sr. No.</th> <th>Customer Id</th> <th>Customer Email</th> <th>Account Balance</th> <th>Send Money</th> </tr> {% for customer in customer_details %} <tr> <td id="customer_pk">{{customer.pk}}</td> <td id="customer_id">{{customer.customer_id}}</td> <td id="customer_email">{{customer.customer_id.email}}</td> <td id="customer_acc_balance">{{customer.account_balance}}</td> <td> <center><button type="button" class="btn btn-primary btnDemo" data-bs-toggle="modal" data-bs-target="#exampleModal" id="send" data-name={{customer.customer_id}} data-balance={{customer.account_balance}}> Send Money </button> </center> </td> </tr> {% endfor %} </table> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Transfer Money</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <h6 id="modal_body"></h6> <center> <form … -
color p tags different colors based off for loop in Django template
Im creating an application where answers to multiple quizes are displayed on one page. To do this i have a for loop which loops through each one and within that loop use if tags to color the correct answer green. However all quizes get teh same answered color, because the css style doesnt stick between each for loop. How can i stop this? {% for quiz in Quizes %} <div class="question-Card"> <p id="a"> A:{{choice1}} <p id="b"> A:{{choice2}} <p id="c"> A:{{choice3}} <p id="d"> A:{{choice4}} {% if quiz.answer == 'a' %} <style> #a { color: green; } </style> {% endif %} **this then continues for the other choices but the code isnt the issue, so i will save you the read** </div> {% endfor %} The issue is that if the last quiz to be 'read' is colored c then they are all colored c and it doesnt do each one indivisually, please help -
Changes not reflecting in local server of vue project
I have a project built on Vue js. I cloned it and setup in my local machine. I changed the base url from the staging to my local django server. The picture is here. But when I run the vue developemtn server and call the api, it is still calling the staging/production backend. The changes are not reflecting. I can see it is calling the staging backend like here. -
How to pass choises from views.py in forms.ChoiceField?
I want to make a form for online tests, but I can't figure out how to make radio buttons (forms.ChoiceField or similar) with the transfer of the selection value not from forms, but from views. Why can't you get from models directly in the form? because I do not know in advance which pk is needed. Please tell me an option that will help you create a form for online testing. I ask with examples to make it easier to understand. Thanks in advance. -
Reverse for 'bans' with keyword arguments '{'user': 1}' not found. 1 pattern(s) tried: ['bans/(?P<pk>[0-9]+)/$']
I am building a GroupApp and I am trying to add some group members in premium_members(ManyToManyField). In Brief :- I made a Group model for group creation and adding members and I made another GroupPosts with ForeignKey of Group for post creation in the particular Group with id or pk. It means i am accessing all the groups in one page and when someone opens a group then blogposts are showing of the clicked group, Like group_1 has 6 posts and group_2 has 2 posts. AND I am trying to add post_creater in premium_members which is a instance in Group Model. The Problem :- BUT When i click on add_premium_member in the group's post's User. Then post creater is not adding in premium_members. No error is showing. BUT NOT ADDING. models.py # For Group Creation class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') premium_members = models.ManyToManyField(User, related_name='premium_members', blank=True) def get_absolute_url(self): return reverse('group_detail_view',kwargs={'pk':self.pk}) # For Post Creation in Particular Group class GroupPosts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) post_title = models.CharField(max_length=30,default='') views.py # For show the group details and posts in one page (group_detail_view) def group_detail_view(request,pk): data = get_object_or_404(Group,pk=pk) posts = GroupPost.objects.filter(group=data) context = {'data':data,'posts':posts} return render(request, 'group_detail_view.html',context) # … -
How to access a legacy database without creating a new table in it in Django
I was given access to a database to use on one of my Django projects. I set everything up and went to migrate the new models and I got an error. "Unable to create the django_migrations table ((1142, "CREATE command denied to user 'MyDatabaseName' for table 'django_migrations'"))" After looking into it, I see its because Django is trying to create a new table in that database. I don't have write access and I do not want it because I am pretty new at this and do not want to mess anything up. I am also not sure the owner would give it to me. Is there a way to get to use the legacy database without having to create a new table in it? -
how to make requirements.txt work while using circle ci with django
I have the following configuration crashing using CIRCLE CI / DJANGO FOLDER STRUCTURE .circleci |____ config.yml djangoproject |____ djangoproject |____________ settings.py ...etc |____ manage.py Circle CI config.yml file jobs: build: working_directory: ~/someproject docker: - image: circleci/python:3.8 auth: username: mydockerhub-user password: $DOCKERHUB_PASSWORD environment: PIPENV_VENV_IN_PROJECT: true DATABASE_URL: postgresql://root@localhost/circle_test - image: circleci/postgres auth: username: mydockerhub-user password: $DOCKERHUB_PASSWORD environment: POSTGRES_USER: admin POSTGRES_DB: $POSTGRES_DB POSTGRES_PASSWORD: $POSTGRES_PASSWORD steps: - checkout - run: sudo chown -R circleci:circleci /usr/local/bin - run: sudo chown -R circleci:circleci /usr/local/lib/python3.8/site-packages - restore_cache: key: deps9-{{ .Branch }}-{{ checksum "requirements.txt" }} - run: name: Wait for db to run command: dockerize -wait tcp://localhost:5432 -timeout 1m - run: name: Install Python Dependencies command: | pip3 install virtualenv python3 -m venv env . env/bin/activate pip3 install -r requirements.txt - save_cache: key: deps9-{{ .Branch }}-{{ checksum "requirements.txt" }} paths: - "env" - "/usr/local/bin" - "/usr/local/lib/python3.8/site-packages" - run: name: run tests command: | . env/bin/activate pytest -s -v mkdir test-results pytest --junitxml=test-results/junit.xml --html=test-results/pytest_results.html --self-contained-html - store_test_results: path: test-results - store_artifacts: path: test-results workflows: build_and_test: jobs: - build When i push a change to github, Circle CI crash with the following error: #!/bin/bash -eo pipefail pip3 install virtualenv python3 -m venv env . env/bin/activate pip3 install -r requirements.txt Requirement … -
Django - filtering on foreign key usin an attribut
i have 2 foreingkey , one from the User and the other one from Device. class checkn(models.Model): user = models.ForeignKey(User, null=True,on_delete= models.SET_NULL) devices = models.ForeignKey(Device, null=True,on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) ch = models.CharField(max_length=1000, null=True) he's using the Device ID for the search and i want to use the IP adresse : this is the device model : class Device(models.Model): hostname = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200, null=True) type = models.CharField(max_length=200,choices=dtype, null=True) ipadress = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) any advices ? -
Customizing model fields by user
I am making a CRM, and I ran into one task: I want to make a “Client” model, with all possible fields, and give an opportunity for users to “enable” only those “Client” fields that he needs. I have little experience and unfortunately I have not been able to find a solution for this for a long time. I would be grateful if someone can show me an example of how this is done (or a link to a repository with a similar method). -
Setting Up Logins For Users with Django
I am trying to use Django's built in user authentication for login/allowing users to create an account and login. I think there's something wrong with my urls or where files are placed in the project. Can anyone help? I know the login.html file is supposed to be inside a folder called 'registration.' I think the fact that my templates are then in a sub folder called 'capstone' might be causing issues. I just don't know how to point to the right file when someone clicks to login. In urls.py under 'weather' I have the following. In two tutorials I saw it should say 'accounts/' but I'm a bit confused as to why. urlpatterns = [ path('admin/', admin.site.urls), path('', include('capstone.urls')), # medium site says to do this path('accounts/', include('django.contrib.auth.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is how my files are set up in Visual Studio Code: -
Django how to add admin page without using model
I needed to create a admin page which is not associated with any model. I have followed the below documentation. https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls So my admin.py looks like this, class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [ path('statistic/', self.my_custom_view), ] return my_urls + urls def my_custom_view(request): . . . return HttpResponse(html) When I login to admin site, I am not able to see the link for this view. Then I added below line to the above code, admin.site.register(MyModelAdmin) It is not working. Please advise what I am doing wrong. -
Request deleting an appointment?
I'm trying to build an appointment system. If a user decided to delete his appointment it must be through request where the admin decides to accept/reject his deleting request. after that the user will receive an email that his deleting request got approved/rejected.. how do I implement that? Where should I start reading about it? Any help is appreciated!