Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically save the form
I am trying not to use formset in my form. Instead of that, I trying to create form dynamically and save all forms data in DB. Currently, I can create a dynamic form, but the thing is I fail to save all data from the form even though I create multiple forms. Now my code only can save only one form. But I want to save the whole form (with multiple form data) in DB. views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': forms = OrderForm(request.POST) if forms.is_valid(): po_id = forms.cleaned_data['po_id'] supplier = forms.cleaned_data['supplier'] product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] order = Order.objects.create( po_id=po_id, supplier=supplier, product=product, part=part, ) return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['supplier', 'product', 'part','po_id'] widgets = { 'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}), 'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}), 'part': forms.Select(attrs={'class': 'form-control', 'id': 'part'}), } HTML <form action="#" method="post" id="form-container" novalidate="novalidate"> {% csrf_token %} <div class="form"> <div class="form-group"> <label for="po_id" class="control-label mb-1">ID</label> {{ form.po_id }} </div> <div class="form-group"> <label for="supplier" class="control-label mb-1">Supplier</label> {{ form.supplier }} </div> <div class="form-group"> <label for="product" class="control-label mb-1">Product</label> {{ form.product }} </div> <div … -
ModuleNotFoundError: No module named 'weasyprint'
I have installed WeasyPrint==0.42.3, but when I try to import it in Django, it raises the following error: ModuleNotFoundError: No module named 'weasyprint' When I look at the requirements.txt, it actually shows that it is installed. I am using Django==2.1.5, python==3.8.5. another issue I am encountering is, the version of Django I am using is not listed in the requirements.txt, but when I check the version from the terminal, it shows that I am using the above named version. -
How to send data from any customized HTML form to Django model form without using jinja {{form}} template
This is not a bug-based problem. Basically, an advice-seeking one. I am a newbie and a great fan of Django's function-based view. It allows me to customize as I need. Like I can customize the HTML form as I want. If I wish, I can also put any icons or images or any things inside my <form> </form> tag. On the other hand, the class-based view also provides lots of attractive features in CRUD operation with the jinja form template and Django's model form. So to take advantage of those features I want to use Django's model form. But as I need to customize my <form> </form> also, I need to create an HTML form also, instead of the jinja model form (bootstrap widgets based modification is not enough for it.). So how can I send data to Django's model form from my customized HTML <form>. Kindly suggest me an overall idea in which way I should approach to solve it? You can also provide me any blog or article or tutorial types of stuff. Thanks for reading the full post. -
Best way to modify the fields in response in django rest?
I have a serializer that gives this data class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'name', 'cost', 'currency') class UserSerializer(serializers.ModelSerializer): posts = PostSerializer(many=True) class Meta: model = User fields = ('id', 'name') and it gives the response like this, { "id": 1, "name": "joe", "posts": [ { "id": 20, "name": "first post", "cost": 20.00, "currency": "USD" }, { "id": 21, "name": "second post", "cost": 30.00, "currency": "USD" } ] } However I want to change/add the fields of the response based on few conditions, Eg. if cost is less than 25, make it zero and add a discount field for every post. This is how I am doing. class MyPostView(APIView): def get(request): query_set = User.objects.all() user_and_posts = UserSerializer(query_set) response_data = user_and_posts.data # I am modifying the serializer data here :< for post in response_data['posts']: post['discount'] = 10 # some value if post['cost'] < 25: post['cost'] = 0 return Response(serializer.data, status=status.HTTP_200_OK) To me modifying the primitive data like this is not looking right, is there any alternate way in django rest to do this? or could've done better with serializer? In general, what's the best way to alter the response data we get from serializer and format it … -
Django Page not Loading Favicon in Chrome
I have a Django website with multiple pages, all of them load the favicon without errors on the top browsers (Chrome, Mozilla, Opera...) but recently I have noticed that in Google Chrome, the favicon in my index page isn't load, instead, I get a console error: GET http://127.0.0.1:8000/favicon.ico 404 (Not Found) (this is also happening in production) The problem with this is that I'm not making any request to /favicon.ico, instead, my code to load the icon is: <link rel="icon" href="{% static 'logo.ico' %}"> This is the same code used in the other pages and it loads fine in them, I have already tried to delete cache, delete Favicon folder in Chrome and to load the icon with full path: http://127.0.0.1:8000/static/logo.ico (if I paste this in browser I can see the icon) I don't understand why Chrome keeps making a default request to /favicon.ico instead of to the actual favicon. My Google Chrome version is: Version 91.0.4472.101 (Official Build) (64-bit) Django version is: 3.1.2 I don't think it is an issue with static files, because the favicon is loaded in other browsers, but also it is not a cache problem, do you have any suggestions about how to solve it? -
The url of the image without http is returned
I am writing a rest api application in the django rest framework in which I can post images. I want to receive the url of the image: https://path/image_name.jpg Here is my serializer class: class Serializer(serializers.ModelSerializer): url = serializers.SerializerMethodField('get_image_url') ... def get_image_url(self, obj): return obj.image.url In this case /media/filename.jpg is returned If I add the https prefix, the link will be displayed, but if I click on it I get an error: browser can not connect to the server localhost -
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?