Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User matching query does not exist :Django
i am making a custom user login authentication system. i am getting error User matching query does not exist . i think that's come from ORM while fetching the query but i am not pretty sure why query does not exit while user matching. it would be great if anybody could me out what i am trying to solve. thank you so much in advance. here below is my working code; class LoginAPIView(APIView): def post(self, request, format=None): #gather the username and password provided by user data = request.data email = data['email'] user_password = data['password'] user_entered_password = user_password salt = "5gz" db_password = user_entered_password + salt hash_password = hashlib.md5(db_password.encode()) print(hash_password.hexdigest()) user_queryset = User.objects.all().get(Q(email__exact=email) & Q(password__exact=hash_password.hexdigest())).first() # user_ser = UserLoginSerializers(user_queryset,many=True) # user_data = user_ser.user_queryset user_id = [] for u in user_queryset: _id = u.get('id') user_id.append(_id) if len(user_queryset) > 0: print(user_id) payload ={'user_id':user_id[0], 'exp':datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS)} jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) return Response({'token':jwt_token, "data":user_queryset}, status=status.HTTP_200_OK) else: return Response({"msg":"Invalid User"}, status=status.HTTP_400_BAD_REQUEST) -
Why is my Query not working? 'Exception Value: Cannot use QuerySet for "Conversation": Use a QuerySet for "Profile" '
I am attempting to query Conversation, which has a many to many field called members. I am doing this so that I can then pass Conversation to my InstantMessage object because that object has a foreign key called conversation that attaches to Conversation. I need to check if members are apart of Conversation first, and then if so, get, or if not, create, and then pass that into my InstantMessage object. But for some reason, I am not able to query it and I don't understand why. error Exception Value: Cannot use QuerySet for "Conversation": Use a QuerySet for "Profile". views.py/message def message (request, profile_id): other_user = get_object_or_404(Profile,id=profile_id) members = Conversation.objects.filter(members= request.user).filter(members= other_user) conversation, created = Conversation.objects.get_or_create( members = members) if request.method == 'POST': form = MessageForm(request.POST, instance= request.user, sender=request.user, conversation = conversation, message=message, date=date) if form.is_valid(): form.save() return redirect ('dating_app:messages.html') else: conversation, created = Conversation.objects.get_or_create( members= [request.user, other_user]) form = MessageForm(instance= request.user, sender=request.user, conversation= conversation, message=message, date=date) context = {'form' : form } return render(request, 'dating_app:messages.html', context) models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must … -
Python framework for CLI development
Need to write python CLI scripts - basic functionalities include - expose REST APIs, consume REST APIs, connect to Oracle/sql-server etc.Hooking onto a front end is not an immediate requirement - but its a possibility. Checked here, here etc. - came to realize that there is no file structure which is universally accepted. Checked various frameworks like click, cement, django, flask etc. - kind of decided on django(as may need to hook a front-end later in time).Here are my concerns: Is it an overkill to use django for CLI development Do we get all features of django(like ORM etc.) if we choose to run from CLI(without web server) If I start with click(for example), how difficult will it be to hook front end in future Please advice. -
Checking if user exists in django table once when looping through values
I have a table where I query all the objects into 'test' in views def book_module(request): test = books.objects.all() and in html, I'm trying to check whether user exists once inside of it. The issue I'm running into is that it is instead printing out every time it finds it inside the table.. table example user col1 col2 col3 test 1 1 1 test 1 1 1 test_2 1 1 Here is my html code. If the current user = 'test' {% for item in test %} {% if item.user == user %} //if user exists in table once, value= "True" <p>Checking if user exists in table.<input type="text" id="exists" value= "True" readonly></p> {% elif item.user !== user %} //if user does not exist in table once, value= "False" <p>Checking if user exists in table.<input type="text" id="exists" value= "False" readonly></p> {% endif %} {% endfor %} If the current user = 'test', I would get 3 outputs, but I'd only like one. Checking if user exists in table. Checking if user exists in table. Checking if user exists in table. I also attempted to use if in, but nothing returned. {% if user in test.user %} <p>Checking if user exists in … -
Set default value to reference own relationship in django migrations
I am updating a Picture model to add additional information and need to set some default values. When the migration runs, I want to populate the DB with some reasonable default values which can be obtained from the user within it. These are my models: class User(models.Model): ... company = ForeignKey(Company, on_delete=models.CASCADE) ... class Picture(models.Model): ... user = ForeignKey(User, on_delete=models.CASCADE) company = ForeignKey(Company, on_delete=models.CASCADE) # New field being added ... The Picture would belong to a company even if the user changes companies. When making migrations, Django wants to know a default value for the company field on Pictures. Is there a way to tell it to look at the Pictures user and use the company that user has? -
Nginx caching of uwsgi served static files
The django project is deployed using uwsgi as application server, it also serves static files from a specified directory(as shown in the below command) and nginx is used as reverse proxy server. This is deployed using docker. The uwsgi command to run the server is as follows: uwsgi -b 65535 --socket :4000 --workers 100 --cpu-affinity 1 --module wui.wsgi --py-autoreload 1 --static-map /static=/project/static; The application is working fine at this point. I would like to cache the static files into nginx server. So i have referred blog https://www.nginx.com/blog/maximizing-python-performance-with-nginx-parti-web-serving-and-caching and i have included following configuration in my nginx.conf : location ~* .(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg |jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid |midi|wav|bmp|rtf)$ { expires max; log_not_found off; access_log off; } After adding this into my Nginx conf, the Nginx server container exits with the following error: [emerg] 1#1: invalid number of arguments in "location" directive in /etc/nginx/nginx.conf:43 Is this how uwsgi served static files can be cached into nginx? If yes please suggest me what is gone wrong here. My complete nginx.conf is as follows: events { worker_connections 1024; ## Default: 1024 } http { include conf/mime.types; # the upstream component nginx needs to connect to upstream uwsgi { server backend:4000; # for a web port socket (we'll use this … -
Creating <select> element and populating it with variable options
I am using django and I have a template where I have a list of variables. If I wanted to create a select box with HTML I'd easily do it it like this: <select id="maid{{room.id}}" name="maid"> {% for maid in maids %} <option value="{{maid.id}}"> {{maid.first_name}} {{maid.last_name}}</option> {% endfor %} </select> But if I create select element with jquery: var select=$('<select>').appendTo('#....'); What is the best way to populate it with variable options? Thank you. -
Django rendering html tags
Struggling a bit here with the html tags confused on where I am going wrong. So I have create a model cart so I trying to view it and I am not getting any errors but the view is just not rendered here is the model.py of the cart class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CartManager() def __str__(self): return str(self.id) below is now then the view.py def cart_home(request): cart_obj = Cart.objects.new_or_get(request) cart = {"cart": cart_obj} return render(request, 'carts/home.html', cart) Now below is the html page for the cart that I am trying to render out {% extends "base.html" %} {% block content %} <h1> Cart </h1> {% if cart.products.exits %} <table class="table table-dark"> <thead> <tr> <th scope="col">#</th> <th scope="col">Product Name</th> <th scope="col">Product Price</th> </tr> </thead> <tbody> {% for products in cart.products.all %} <tr> <th scope='row'>{{ forloop.counter }}</th> <td>{{ product.name }}</td> <td>{{ product.title}}</td> </tr> {% endfor %} <tr> <td colspan='2'>2</td> <td><b>Total</b></td> </tr> </tbody> </table> {% else %} <p class='lead'>Cart is empty</p> {% endif %} {% endblock %} when I go to the url where I have that html tag I get cart … -
Pyscopg2 Module Not Found
I hope someone can help me to resolve this issue. I have a webapp developed in Django with postgresql, the app is working properly in my local pc, the issue started when i migrate the code into a server. I have a Windows Server 2019 core, and after configure the IIS to serve this app, appear the following issue: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Python\Python38\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' I have installed the connector "psycopg2" and also i already tried all that i found in "google" but i couldnt fix that issue. SO i dont know if i forgot configure something in the IIS or what is happening here because if i open the python console or django shell and import the PSYCOPG2 the connector is imported successfully. Thanks and Regards. -
No moudle named roocket
hello guys i have a problem with a tutorial which im seeing since qurantine has started and i really need a big help into solving it. story is i lost some of my files or accidently deleted them , so i used the files for the project which they have into zipfiles but for this projects i keep getting this error while im trying to run local server this is the error after using py manage.py makemigrations (( its a big error so i just copied end of it )) File "c:\users\navid\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'roocket'``` i think it must be something with bootstrap so i started to see if bootstrap is installed or not and the results for the project directory are: `asgiref==3.2.7 astroid==2.3.3 beautifulsoup4==4.9.0 colorama==0.4.3 Django==3.0.5 django-bootstrap4==1.1.1 django-jalali==3.3.0 django-jalali-date==0.3.1 isort==4.3.21 jdatetime==3.6.2 lazy-object-proxy==1.4.3 mccabe==0.6.1 psycopg2==2.8.5 pylint==2.4.4 pytz==2019.3 six==1.14.0 soupsieve==2.0 sqlparse==0.3.1 wrapt==1.11.2` -
Django validate_unique method all ready exists message
Thinking How to get the instance pk that exists during validate_unique? it is not a good practice to overwrite the method validate_unique and I don't know if it would be correct to validate unique fields in the clean() method. but imagine the following situation: you want to show admin users which is the instance that already exists so they can edit it if they want, I think it would be more intuitive when working with thousands of data. the following code is just an example - think about it as a pseudocode although I tried it and it works, I know it could be better def clean(self): lockup ={} unique_togethers = self._meta.unique_together[0]#these could throw an error for field in unique_togethers: f = self._meta.get_field(field) value = getattr(self, f.attname) if value is None: continue if f.primary_key and not self._state.adding: continue lockup[str(field)] = value qs = snippet.objects.filter(**lockup) if qs.exists and self._state.adding: raise ValidationError( format_html('''this object all ready exist plese edit it on <a href="{}">Edit</a>''', reverse('admin:testing_snippet_change', args=(qs[0].pk,)))) Is this approach correct, how to apply it to the validation_unique method to works in all unique validations? Result -
Get the dropdown data and update the data in Django
dear all of django developer , i having facing this below issue . i try to update this db table data where has one field and one drop down field data , i getting basic field data . but not get the drop down list data . i request expert for help me the issue . Advanced Thanks For All views.py def update_brands(request, id): brand = Brand.objects.get(id=id) form = AddBrandForms(request.POST, instance=brand) if form.is_valid(): form.save() return redirect('/parts/brands') return render(request, 'parts/edit_brands.html', {'brand': brand }) edit_brands.html {% extends 'parts/base.html' %} {% block content %} <form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form"> {% csrf_token %} <div class="form-group row"> <label class="col-sm-2 col-form-label">Country Name:</label> <div class="col-sm-4"> <input type="text" name="country" value="{{ brand.brand_name }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Country Name:</label> <div class="col-sm-4"> <select id="cars" name="cars"> {% for db in dbf.all %} <option value="{{ db.db}}">{{ db.db}}</option> {% endfor %} </select> </div> </div> <button type="submit" class="btn btn-success">Submit</button> </form> {% endblock %} -
Why form.is_valid() does not returns false immediately when the first clean_<field_name> raises ValidationError?
I have defined a form with two CharField. I have defined clean method for both fields. In my view i am calling is_valid() method of the form I defined. I am giving an invalid input for field1 so that clean_field1 method raises ValidationError. In clean_field2 i am accessing cleaned_data[field1]. When calling the url, it is giving 500 error. And in stack trace it says KeyError: 'field1'. On debugging I found ValidationError was raised in clean_field1 method. I expected that form.is_valid() will return false when clean_field1 raised ValidationError. But django went on to execute clean_field2. Why django is executing clean_field2, when clean_field1 raised ValidationError. form.is_valid() should have returned false when clean_field1 raised ValidationError. Am I correct? Does Form.is_valid() method return only after executing all clean_<'field_name'> methods(even if ValidationError was raised)? If yes, then this poor design I think. If first clean_<'field_name'> method raises ValidationError then what is the point in executing other clean_<'field_name'> method? I think Form.is_valid() should return false when it encounters first ValidationError. Or am I missing something? It will be really helpful if anyone can explain what is going on? Thank you. The code that I was executing: class MyForm(Form): field1 = forms.CharField() field2 = forms.CharField() def clean_field1(self): … -
Django queryset get empty values in query
So I'm trying to get all the values to be able to display in my templates. However I have encountered myself with this problem: I have these models: class Project(models.Model): projectId = models.AutoField(primary_key=True, db_column="Id", db_index=True, verbose_name='Project ID') description = models.CharField(max_length=900) class PM(models.Model): PMid = models.AutoField(primary_key=True, db_column="Id", db_index=True) PMNumber = models.CharField(max_length=50, unique=True, db_column="PMNumber") description = models.CharField(max_length=600) projectId = models.ForeignKey(Project, on_delete=models.CASCADE, db_column="ProjectID", related_name='+') And I'm trying to get all the projects with their respective PMNumber. For which I'm trying something like this: fpm = PM.objects.all() projects = [] for i in fpm: projects.append('ProjectName': i.projectId.description, 'PMNumber': i.PMNumber}) After that the result is like this [{'ProjectName': 'pr1', 'PMNumber': '119508-01'}, {'ProjectName': 'pr1', 'PMNumber': '119490-01'}] However, I'm still missing some projects that don't have a PM related to them, I want all the projects in the queryset to be able to show them in a template, not just the ones that have a PM. It should look something like this: [{'ProjectName': 'pr2', 'PMNumber':'None'}, {'ProjectName':'pr3' , 'PMNumber':'None'}, {'ProjectName': 'pr1', 'PMNumber': '119508-01'}, {'ProjectName': 'pr1', 'PMNumber': '119490-01'}] Is there a way to do this? or is there another way to do this in the views? Note: I know that setting an ID for each class in Django is not … -
Unsupported config option for services.volumes: 'postgres_data'
My docker-compose.yml is below, version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: but while running the command docker-compose up -d --build I got the following error message,someone please help me, ERROR: The Compose file './docker-compose.yml' is invalid because: Unsupported config option for services.volumes: 'postgres_data' -
Save table loop data in database in django
html file <table style="border-spacing: 10px;"> <thead> <th>Test</th> <th>Rate</th> </thead> <tbody> {% for booktest in var1 %} <tr> <td width="100%">{{ booktest }}</td> <td>{{ booktest.rate }}</td> </tr> {% endfor %} <br> <th scope="row">Total</th> <td><strong> {{ total_rate }} </strong></td> </ul> </tbody> </table> I want to save the {{ booktest }} and {{ booktest.rate }} value in database , as both has multiple values has it is in for loop -
How to correctly add AJAX to DataTable?
i'm using a bootstrap data table and i'm passing the registers through ajax. However, for some reason since i started filling the table with the ajax function, the search box, the pagination and the column ordering stopped working. At first it does print the registers, but if i search for one, it adds a row at the beggining of the table saying "No registers found", like it's empty. Same thing happens when i try to switch how many registers it shows per page. (And it doesn't paginate at all) Here is my code: <script type="text/javascript"> $(document).ready(function() { $('#dom').DataTable({ ajax:{ url: '/restapi/enviarjson/', type: 'get', success: function (json){ $("#dom > tbody").empty() var table = []; $.each(json, function(key, val){ table.push('<tr>'); table.push('<td style="vertical-align: middle; text-align: center;">'+ '<input type="checkbox" id="onff2" name="onff2" value="'+val.pk+'">' + '</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.pk+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.nombre_activo+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.desc_act+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.dat_cont_arch+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.resp_dom+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.estado+'</td>'); table.push('</tr>'); }); $("<tbody/>", {html: table.join("")}).appendTo("table"); } }, language: {searchPlaceholder: "Buscar", search: "", "paginate": { "first": "Primero", "last": "Ultimo", "next": "Siguiente", "previous": "Anterior" }, "zeroRecords": "Sin resultados encontrados", "infoEmpty": "", "emptyTable": "No hay información", "lengthMenu": "Mostrar … -
how to return 200OK before the function is completed
I write a bot for Vkontakte on Django(2.2.4), with the vk_api library Some of the functions are quite long (performed in 5-7 seconds). But Vkontakte requires the server to respond no longer than 3 seconds. If the response is delayed, the request is sent again, and the bot starts sending the same message many times after a while. (I Use The Callback Api) I will describe my problem briefly my function runs for more than 6 seconds the 200OK response must be sent in less than 3 seconds Is it possible to solve this problem without major changes in the code? # views.py @csrf_exempt def MainBotView(request): # i need something like return HttpResponse('ok') here ... my slow code ... return HttpResponse('ok') # but I don't need it at the end (I use pythonanywhere and Celery perhaps does not work there) Should I use threading? How? -
Passing User Data to Admin Actions in Django
I am attempting to write an admin action that accesses data from selected users. i.e. email. However, when I access Account instances, I have only been able to access the instance/data of the user that is currently logged in. For example, to access the emails of selected users, I have tried: #models.py class Account(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) #admin.py from account.models import Account for Account in queryset: author = request.Account.email #OR author = Account.objects.get(email=request.email) and both of these will fill "author" with the email address of the admin that is trying to pull the data. Does anyone know how I could call to the instances of selected accounts with an admin action? -
How to calculate django model fields
I have the following fields in my models: class Materiale(models.Model): quantity=models.DecimalField(max_digits=5, decimal_places=2, default=0) price=models.DecimalField( max_digits=5, decimal_places=2, default=0) VAT=models.DecimalField(max_digits=5, decimal_places=2, default=0) VAT_amount=models.DecimalField(max_digits=5, decimal_places=2, default=0) But the VAT_amount is the result of quantity*price*VAT. How can store in my database that value automatically??? It's important that the field (VAT_amount) is present in database. Thanks. -
Django Rest Framework Permissions List Issues in ModelViewSet
I am trying to check multiple permissions classes in the get_permissions method of a ModelViewSet but even though the has_object_permission returns false on all of the classes in the list I'm still able to perform the action. Here's my get_permissions method: def get_permissions(self): if self.action in ("retrieve", "list",): permission_classes = [AllowAny] elif self.action in ("update", "partial_update", "destroy",): permission_classes = [IsOwner | IsAdminUser] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] On an update IsOwner returns True for has_permission and False for has_object_permission but even a non-admin can make updates. Anyone know what I'm doing wrong here? -
WebSocket handshake failed.. Error in the browser console, with response code: 500
My django channels app is not working. Can this be a reason that my site is 'not secure'. Does sockets work only on HTTPS? If someone could help... -
How to add more features to user permission in django?
I am new to django. I want to edit default user auth_permissions. More precisely I want to add an integer field in addition to "label", "code" features to distinct permission types (like strong, moderate and etc.). So far I could not find anything like this. I tried to make custom permissions, but could not add them to the permission database. Anyone could help me? -
Drag drop save database django
I have a django project that teacher assign students courses by drag drop.I made html part but I couldnt figure out how to save db. Is there any framework or method ? screenshot from my project -
Hosting a django app on a personal wondows machine
I've developed a django web application which I now want to deploy so that everyone in my organization can start accessing the website. However, I do not have a dedicated server location to actually host it. I have been given a dedicated Windows machine to host the app on. Previously I've always used things like Heroku or AWS to deploy websites which make it really easy, so I really have no idea how to turn a desktop into a server hosting a web application. Does anyone have any suggestions on how to do this using free software? Thanks in advance.