Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I handle selenium and geckodriver install error?
I ran the following code by installing selenium and django module. from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title For the selenium module, I need geckodriver for firefox browser. So, I installed geckodriver by different ways - 1. npm, 2. brew, 3. direct install (download from here and move it to /usr/local/bin or /usr/bin. All the ways did not work for the above test code. I got the following error message: Traceback (most recent call last): File "functional_tests.py", line 3, in <module> browser.get('http://localhost:8000') File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get self.execute(Command.GET, {'url': url}) File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF-8&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20server%20at%20localhost%3A8000. Please let me know what the problem is.. -
Django doesn't raise ValidationError on ModelChoiceField (widget RadioSelect) if user didn't select any choice
I have a form that contains a ModelChoiceField poller_category class PollersForm(forms.Form): # Poller Category poller_category = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={ 'class': 'poller-category-radio', }), queryset=Categories.objects.all().order_by('poller_category'), label='Select a Category') which is rendered as follows: <!-- Poller Categories --> <div class="fieldWrapper"> <div class="label">{{ form.poller_category.label_tag }}</div> <div class="category-ctn"> {% for category in form.poller_category %} <div class="category-wrapper">{{ category }}</div> {% endfor %} </div> </div> Now if the user doesn't select any category and tries to submit the form, nothing just happens. That actually means that the form is valid, doesn't it? If so, why doesn't it trigger the redirect? Also If I select a choice and submit, redirect is called, but the category isn't populated in the DB. # create a form instance and populate it with data from the request: form = PollersForm(request.POST) # check whether it's valid: if form.is_valid(): # process the remaining data in form.cleaned_data as required poller_text = form.cleaned_data['poller_text'] poller_category = form.cleaned_data['poller_category'] poller_choice_one = form.cleaned_data['poller_choice_one'] poller_choice_two = form.cleaned_data['poller_choice_two'] # Get the user created_by = request.user # Save the poller to the database p = Pollers(poller_text=poller_text, poller_choice_one=poller_choice_one, poller_choice_two=poller_choice_two, poller_category=poller_category, created_by=created_by) p.save() # redirect to a new URL: return redirect(poller_success) # if a GET (or any other method) we'll create a blank form else: form = … -
Total Price Django
How can i get "total" from these models down below? I tried doing something in views but I get attribute error that QuerySet' object has no attribute 'total'. views.py def cart(request): cart = Cart.objects.filter(order_user=request.user) order_items = OrderItem.objects.filter(cart__in=cart) total = 0 for i in order_items: total = i.quantity * i.item.price + cart.total cart.update(total=total) models.py class OrderItem(models.Model): cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True) item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.IntegerField(default=1000) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) ordered = models.BooleanField(default=False) total = models.IntegerField(default=0, help_text="100 = 1EUR") order_items = models.ManyToManyField(Item, related_name='carts', through=OrderItem ) -
Resend OTP ajax function not working in a django project
I have made an ajax function that resends otp when the 'resend Otp' lick is clicked. This is django project. The follwing are the codes that I wrote. html <a class="resend-otp" href="#" onclick="ReSendOTP('{{user.username}}', 'resendOTPmess')" ><i id="resendOTPmess">Resend</i>OTP?</a> js file function ReSendOTP(username, mess_id){ mess = document.getElementById(mess_id); mess.innerText = "Sending..."; $.ajax({ type: 'GET', url: '/user/resendOTP', data: {usr:username}, success: function(data){ mess.innerText = data; } }) } views.py def resend_otp(request): if request.method == 'GET': get_user = request.GET['usr'] if User.objects.filter(username = get_user).exists() and not User.objects.filter(username = get_user).is_active: user = User.objects.get(username=get_user) user_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = user_otp) mess = f"Hello, {user.first_name}, \nYour OTP is {user_otp}\n Thanks!" send_mail( "Welcome to Solve Litigation - Verify your Email", #subject mess, #message settings.EMAIL_HOST_USER, # sender [user.email], #reciever fail_silently= False ) return HttpResponse("Resend") return HttpResponse("Can't Send OTP") urls.py from .views import resend_otp path('resendOTP', resend_otp) So I am requesting a resend otp for the "username: rick.bhardwaj27@gmail.com" but I am getting the follwing error in the console jquery-3.6.0.min.js:2 GET http://127.0.0.1:8000/user/resendOTP?usr=rick.bhardwaj27%40gmail.com 404 (Not Found) What should I do to rectify it, please suggest. -
How to minimize side bar when enter a spesific page?
I have a sidebar. When user enter the index page, I want to minimize the side bar. There is a button for that in sidebar: <a class="mobile-menu" id="mobile-collapse" href="javascript:"><span></span></a> How can I trigger this link when enter the home (index) page? sidebar.html <nav class="pcoded-navbar"> <div class="navbar-wrapper"> <div class="navbar-brand header-logo"> <a href="/" class="b-brand"> <div class="b-bg"> <i class="feather icon-trending-up"></i> </div> <span class="b-title">HawkDragon</span> </a> <a class="mobile-menu" id="mobile-collapse" href="javascript:"><span></span></a> </div> <ul class="nav pcoded-inner-navbar"> <li class="nav-item pcoded-menu-caption"> <label>Menü</label> </li> <li data-username="dashboard Default Ecommerce CRM Analytics Crypto Project" class="nav-item {% if 'index' in segment %} active {% endif %}"> <a href="/" class="nav-link "><span class="pcoded-micon"><i class="feather icon-home"></i></span><span class="pcoded-mtext">Anasayfa</span></a> </li> <li data-username="dashboard Default Ecommerce CRM Analytics Crypto Project" class="nav-item {% if 'index' in segment %} active {% endif %}"> <a href="/" class="nav-link "><span class="pcoded-micon"><i class="feather icon-home"></i></span><span class="pcoded-mtext">Setup Wizard</span></a> </li> </ul> </div> </div> </nav> -
less than or equal to 0 - is not showing posts which have 0 votes
I am building a simple question and answer site. And I am trying to access the answers which votes are less than or equal to 0. I have three answers which have no votes But it is not showing in the queryset I should show me three posts which have zero votes , But it is showing 0. models.py class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) body = models.CharField(max_length=3000) likes = models.ManyToManyField(User, related_name='likes', blank=True) views.py def answers(request): answers = Answer.objects.filter(likes__lte=0).count() context = {'answers':answers} return render(request, 'answers.html', context} When i remove .count() than it shows <QuerySet []>. I have tried many times but it is still showing 0 posts which have 0 votes. And when i set it to lte=1 than it shows posts which have 1 likes but it doesn't show less than 0. Any help would be much Appreciated. Thank You. -
Accessing Django username in PayPal transaction
I would appreciate any insight as to whether it is possible to access the username of whoever is logged into my Django app from a PayPal smart button. I currently have a "description" string within the createOrder function, which I would like to include the username. TIA for any help. -
Django throws No unique constraints when I add a uuid field to unique_together along with django's ID
I am just creating a model, not even adding a field to an existing model It looks like this class Product(TenantModel): firm = models.ForeignKey("TenantsUI.Firm",on_delete=models.CASCADE, default=get_current_tenant) tenant_id = 'firm_id' tracker = FieldTracker() name = models.CharField(max_length=250, null=True) packing = models.CharField(max_length=250, null=True) product_uref = models.UUIDField(default=uuid.uuid4, null=False, blank=False) class Meta: verbose_name = "Products" unique_together = [['firm','id','product_uref']] When I run migration, it says File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "FirmData_product" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\user\Documents\Django Projects\proj\root\manage.py", line 22, in <module> main() File "C:\Users\user\Documents\Django Projects\proj\root\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\user\Documents\Django Projects\proj\env\lib\site-packages\django\db\migrations\executor.py", … -
filter model with foreignKey
I have these 2 models: class Canva(models.Model): name = models.CharField(null=True, blank=True, max_length=255) site = models.CharField(null=True, blank=True, max_length=255)s created = models.DateTimeField(null=True, blank=True, default=timezone.now) class Bilan(models.Model): agregat = models.CharField(null=True, blank=True, max_length=255) SCF = models.CharField(null=True, blank=True, max_length=255) canva = models.ForeignKey('Canva', null=True, blank=True, on_delete=models.CASCADE, related_name='bilan_canva') How can I filter the Bilan class by the "created" attribut in the Canva class? -
Django Authentication Via Http With Websockets
I'm doing this - Load single page application - an apollo client is initialised with a websocket and http link. This happens when the user is logged out, let's say. The user then logs in without a page reload. The graphql response now contains the session cookie. Problem - whilst subsequent http requests include the session cookie the websocket connection does not. How do people solve this problem? I'm guessing on the client I could either make all communication with the server via websockets, or, create a new apollo client upon successful sign in and use this for subscriptions. Is it possible though to somehow pass the session cookie to the websocket already established on the client? I'm using django channels. I know it has a login function but this is logging in the user who has made a request via websockets I believe. This is for a chat app. But websockets are obviously common within most web apps. For example a notification system. Of course with most web apps you'd use http and websocket. So I'm wondering how people go about this. -
How to Create user objects with CreateAPIView in django
i need create class with CreateAPIView for create new object class Register(CreateAPIView): permission_classes=(AllowAny) serializer_class = UserSerializer def perform_create (self,serializer): obj = serializer.save(user=self.request.user) return Response({ "id": obj.id, "username": obj.username, }, status=status.HTTP_201_CREATED, content_type='application/json') but this code dosent work and And shows the following error : TypeError: init() takes 1 positional argument but 2 were given What should I do? -
How to look up a field value using foreignkey in Django
I have the following models: class Camera(models.Model): url = models.CharField(max_length=300, unique=True) camera_number = models.IntegerField(null=False, blank=False, validators=[ MaxValueValidator(1000), MinValueValidator(1)]) camera_name = models.CharField(max_length=100, null=False, blank=False) slug = models.SlugField(max_length=100, null=True, blank=False, unique=True) class BaseImage(models.Model): url = models.ForeignKey(Camera, on_delete=models.CASCADE) base_image_filename = "base_images/" + str(Camera.slug) + "/%H" image = models.ImageField(max_length=300, upload_to=base_image_filename) What I am trying to do is to create the filename in BaseImage that contains the data in the slug variable of the corresponding Camera record. A camera can have many BaseImages but each BaseImage can only match to one Camera. What I get in the name is something like "base_images/<django.db.models.query_utils.DeferredAttribute object at 0x7f6006bd9b70>/20/camera_1.jpg". What do I need to change to get the slug field value as part of the filename ? -
Getting data from parent to child - FE or BE, how?
I'm learning Django and React. I'm trying to get some data from Order to TranspOrder. Order -< TranspOrders In the model Order (orders/model.py), I have a field total_allowed_amount and a function get_total_remaining_amount(self), which calculates total_allowed_amount - total_consumed_amount and returns the result. In OrderDetailSerializer I have a field total_remaining_amount (source= "get_total_remaining_amount" - I assume this means it gets the dafa from that function). So, in the frontend I have OrderDetails.js (Order) React component which displays the two fields total_allowed_amount and total_remaining_amount. Now I need to display these two fields also on TranspOrderDetails.js (TranspOrder), but can't figure out a way to do it. Not even sure if it is correct to do it via back- or frontend. This is very annoying, as it seems to be a very basic thing. I've tried writing functions in the model TranspOrder (transporder/models.py) to bring these into this model from Orders, so I can then access them from the FE (I think that creating same fields for them in this model is not a good idea): def get_order_total_allowed_amount(self): if not self.order.total_allowed_amount: return None return self.order.total_allowed_amount def get_order_total_remaining_amount(self): if not Order.total_allowed_amount: return None return self.get_total_remaining_amount(Order) I've also tried to import these from OrderDetails.js into TranspOrderDetails.js, as such: … -
Django Rest Framework - response.set_cookie() not setting cookie in browser but working in postman and in browsable api
I am struggling with setting jwt token in httponly cookie. I tried many solution but not working. I am working with localhost "127.0.0.1" but when I try to login the cookies sent by server not display in my frontend working at "127.0.0.1:5501" but if I try with Browsable api working at "127.0.0.1:8000" it works fine and I can check my cookies easily. I noticed a weird thing too. If I login via my frontend "127.0.0.1:5501", cookies not set but if I try with browsable api working at "127.0.0.1:8000" and then switch to my "127.0.0.1:5501" tab I can see that cookies their too. This a very Weird thing and I don't know the reason behind this. Please help me to resolve this issue. Views.py class LoginView(APIView): def post(self,request,format=None): data = request.data response = Response() username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) csrf.get_token(request) response.data = {"Success" : "Login successfully","data":data} return response else: return Response({"No active" : "This account is not active!!"},status=status.HTTP_404_NOT_FOUND) else: return Response({"Invalid" : "Invalid username … -
How to pass the primary key of a object to apply force_update in django?
I am trying to forcefully update a row of my Model. when I do this I get an error super().save(force_update=True, *args, **kwargs) ValueError: Cannot force an update in save() with no primary key. here is my code snippet. How can make sure that only the selected object gets updated with the new values? try: super().save(*args, **kwargs) except: a = Model.objects.filter(is_cancelled=False, class_id=109847583975) super().save(force_update=True, *args, **kwargs) -
REST API search with URL parameters, testing works with some values but not others (all are valid entries)
Im creating a web app to search a database of vases using Django/react. I've created an API view which takes URL parameters to search a vase record. When testing the API call some values work as expected, but others don't. Here is my views.py: class FilterVases(generics.ListAPIView): serializer_class = VaseSerializer def get_queryset(self): queryset = Vase.objects.all() query_provenance = self.request.query_params.get('provenance_name') if query_provenance is not None: try: provenance = Provenance.objects.get(provenanceName=query_provenance) queryset = queryset.filter(provenance=provenance) except: pass inscription = self.request.query_params.get('inscription') if inscription is not None: queryset = queryset.filter(inscription=inscription) query_shape = self.request.query_params.get('shape_name') if query_shape is not None: try: shape = Shape.objects.get(shapeName=query_shape) queryset = queryset.filter(shape=shape) except: pass query_collection = self.request.query_params.get('collection_name') if query_collection is not None: try: collection = Collection.objects.get(collectionName=query_collection) queryset = queryset.filter(collection=collection) except: pass query_artist = self.request.query_params.get('artist_name') if query_artist is not None: try: artist = Artist.objects.get(artistName=query_artist) queryset = queryset.filter(artist=artist) except: pass fabric = self.request.query_params.get('fabric') if fabric is not None: queryset = queryset.filter(fabric=fabric) vaseID = self.request.query_params.get('vaseID') if vaseID is not None: queryset = queryset.filter(vaseID=vaseID) return queryset and my models.py: #define shape class class Shape(models.Model) : shapeID = models.CharField(max_length=10) shapeName = models.CharField(max_length=100) #define artist class class Artist(models.Model) : artistID = models.CharField(max_length=10) artistName = models.CharField(max_length=100) #define provenance class class Provenance(models.Model) : ProvenanceID = models.CharField(max_length=10) provenanceName = models.CharField(max_length=100) #define collection class class … -
django: how i can update checked element by checkbox
i want to update checked user but i get more problems with this code some time i show this error User matching query does not exist. C:\Users\Republic Of Computer\Documents\GitHub\StockManagementProject\stock\views.py, line 106, in ajax_update can any one help me please? plaease note that the deletion was successful this is an image for interface html Action Ajout de utilisateur Move to another group Delete Modifier Send Message <div class="card-body- pt-3 pb-4"> <div class="table-responsive"> <table id="data_table" class="table table-bordered table-striped" cellspacing="0"> <thead> <tr> <th scope="col"></th> <th scope="col">Nom d’utilisateur</th> <th scope="col">Phone</th> <th scope="col">Adresse électronique</th> <th scope="col">Prénom</th> <th scope="col">Nom</th> <th scope="col">Status utilisateur</th> </tr> </thead> <tfoot> <tr> <th scope="col" clospan="7"></th> <th scope="col"></th> <th scope="col"></th> <th scope="col"> </th> <th scope="col"></th> <th scope="col"></th> <th scope="col"> </th> </tr> </tfoot> <tbody> {% for p in user %} <tr> <td class="action-checkbox"> {% if request.user.is_staff %} <input type="checkbox" name="_selected_action" value="{{p.id}}" class="action-select" > {%endif%} <img class="rounded-circle mr-3 table-thumb" src="{{p.profile.image.url}}" width="30px" alt=""/> </td> <td>{{p.username}}</td> <td>{{p.phone_number}}</td> <td>{{p.email}}</td> <td>{{p.first_name}}</td> <td>{{p.last_name}}</td> <td> {% if p.is_staff%} <center>Admin</center> {% else %} <center>Superviseur</center> {% endif %} </td> </tr> {%endfor%} </tbody> </table> </div> </div> js <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function() { $('#action_delete').click(function() { if (confirm('Vous etes sur? ')) { var id_user=[]; $(':checkbox:checked').each(function(i){ id_user[i]=$(this).val(); }); if (id_user.length===0) { alert('Please select a user to … -
Unknown column 'user_details.id' in 'field list' in django
I am creating custom user model for student so that I can easily authenticate. models.py from django.db import models from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager class Student_Manager(BaseUserManager): def create_user(self,username,password): user = self.model(username=username) user.set_password(password) user.save(using=self.db) return user def create_superuser(self,username,password): user = self.create_user(username=username,password=password) user.is_superuser = True user.save() return user class Student(PermissionsMixin,AbstractBaseUser): username = models.CharField(max_length=60, unique=True) user_id = models.IntegerField(unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField(max_length=50) password = models.CharField(max_length=50) status = models.IntegerField() REQUIRED_FIELDS = ['user_id'] USERNAME_FIELD = 'username' objects = Student_Manager() def __str__(self): return self.username class Meta: db_table = 'user_details' views.py from django.shortcuts import render def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = Student.objects.get(username=username) print(user) return render(request,'app_kanri/login.html') My table structure look like this I am getting this error - Django version 3.2.6, using settings 'python_test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /login/ Traceback (most recent call last): File "D:\myproject\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\myproject\myenv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "D:\myproject\myenv\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "D:\myproject\myenv\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "D:\myproject\myenv\lib\site-packages\MySQLdb\connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'user_details.id' in 'field list'") The … -
Traceback while running 'sudo python3 manage.py migrate'
I have been using windows os for development. I have very little understanding of commands in linux. I'm trying to deploy a django application on AWS EC2 instance but got stuck while trying to migrate to the database. I ran the command: sudo python3 manage.py migrate but I keep getting the following error. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 13, in <module> from django.apps import apps File "/usr/local/lib/python3.5/dist-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 114 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax During development on windows os, whenever I run python manage.py migrate on the same project everything works well. But When I clone it from github I'm not able to migrate using linux ubuntu command. Please how do I fix the problem? -
Serving static and media files in django production
I want to serve static and media files in my django application from a server but don't want to use aws s3 what is the best alternate options? How do i serve this files from a server like Nginx or Apache is this good for production? what other professional technology i can use to do so? -
django use mixin needs to have a value for field "id" before this many-to-many relationship can be used
I'm trying to save a M2M object ( set it to a default value which is the one with position= 1 ) when I login with by admin is ok. The problem I'm getting the following error: needs to have a value for field "id" before this many-to-many relationship can be used Models.py class Categorymodel(models.Model): title=models.CharField(max_length=100) slug=models.CharField(max_length=100,unique=True) status=models.BooleanField(default=True) position=models.IntegerField() def __str__(self) -> str: return self.title class Reportmodel(models.Model): subject=models.CharField(max_length=100) category=models.ManyToManyField(Categorymodel,related_name='info') user=models.ForeignKey(User,on_delete=models.CASCADE) Mixin.py class FormValidMixin(): def form_valid(self,form): if self.request.user.is_admin: form.save() else: category1=(Categorymodel.objects.get(position=1)) self.obj=form.save(commit=False) self.obj.user=self.request.user self.obj.category.set(category1) -
Problem with database , how delete field from db ? [Django]
I would like to delete a field from one of the tables in my database but I'm having some problems. (The project I'm working with uses the Django framework) I deleted the fields from the table in the models.py file, then I updated the database from the terminal with the commands "python manage.py makemigrations" and then "python manage.py migrate", (which tell me that there is nothing to be updated in the database). The problem is that those fields are still present in the table if I log into the database ... where am I wrong? -
Django: Update and Create data record with inlineformset_factory
Can someone help me i am trying to use "inlineformset_factory" i actually made it working but instead of updating the record it just duplicating the record this is my view.py def resume(request): user = request.user.personaldetails form1 = personalDetailsForm(instance=user) workExpFormSet = inlineformset_factory( personalDetails, employmentHistory, form=employmentHistoryForm, extra=3, max_num=3) formset = workExpFormSet(instance=user) if request.method == 'POST': form1 = personalDetailsForm(request.POST, request.FILES, instance=user) formset = workExpFormSet(request.POST, instance=user) if form1.is_valid(): form1.save() if formset.is_valid(): formset.save() else: print(formset.errors) # print(formset) return render(request, 'main/Client/resume.html', {'form1': form1, 'formset': formset}) My models.py class personalDetailsForm(ModelForm): profile_image = forms.ImageField(label="", widget=forms.FileInput( attrs={'type': 'file', 'id': 'mediaFile'})) jobTitle = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'jobTitle'})) fname = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'fname'})) lname = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'lname'})) email = forms.EmailField(label="", required=False, widget=forms.TextInput( attrs={'type': 'email', 'class': 'form-control', 'id': 'email'})) phone = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'phone'})) country = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'country'})) city = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'city'})) address = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'address'})) birthplace = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'pdate'})) birthdate = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': … -
Why does Django refuses http connection on a specific route, but on other routes http works properly?
I have a Django project. Its routes are: urlpatterns = [ path('admin/', admin.site.urls), path('projects/', include('projects.urls')) ] When I was preparing the project for production, I set SECURE_HSTS_SECONDS to 3600 seconds. Right after this, I got this error. I tried to set this variable to 1 second, but It didn't help. Also, I tried to remove this variable, but my app still doesn't work. I also noticed, that when I hit the https://localhost:8000/projects/ route, Django automatically sets HTTP to HTTPS and even when I change HTTPS to HTTP manually, It's still not going to work. However, it works if I change my route to something different, like http://localhost:8000/works/. I already tried to clear cache in google chrome, head to chrome://net-internals/#hsts and delete localhost from security policies. And I even updated my SECRET_KEY. Now I think, the only way to solve this issue is to recreate the project, but I can't do this, because all the data will be deleted. So what am I doing wrong? -
how to restore data after deployment on Heroku (Django)
I have successfully deployed my first Django app on Heroku, but there is no data in remote database I do have dump file stored, but i don't know how to restore it on Heroku, I have read docs , and there are some commands mentioned about pulling data from local database, but i don't seem to understand that, need some help thanks in advance the database is Sqlite