Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Initialise filed value to null when page loads in Django Admin panel
The following code is in models.py it is registered in admin.py class Customer(models.Model): name = models.CharField(max_length=100, null=True, blank=True, default=None,help_text="The full official name of the customer.") email = models.CharField(max_length=100, null=True, blank=False, default=None,) password = models.CharField(max_length=1000, null=True, blank=True, default=None,) name_short = models.CharField(max_length=100, null=True, blank=True, default=None,help_text="The commonly used (short) name of the customer.") country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True, default=None,help_text="The main country code of the customer.") status = models.IntegerField(null=True, blank=True, default=None, help_text="1-2-3 temporary-registered-qualified.") sample = models.IntegerField(null=True, blank=True, default=None, help_text="1 if sample customer.") reset_password_otp = models.CharField(max_length=100, null=True, blank=True, default=None) reset_password_otp_time = models.DateTimeField(default=timezone.now) reset_password_otp_duration = models.CharField(max_length=100, null=True, blank=True, default=None) created = models.DateTimeField('created', default=timezone.now) updated = models.DateTimeField('updated', default=timezone.now) I want to initialise the password field to null when the admin page loads. -
Django Debug in VsCode
I am using Django 2.1 with the following code in vsCode-launch.json : { "name": "Python: Django", "type": "python", "request": "launch", "stopOnEntry": true, "pythonPath": "${config:python.pythonPath}", "program": "${workspaceFolder}/manage.py", "cwd": "${workspaceFolder}", "args": [ "runserver", "--noreload", "--nothreading" ], "env": {}, "envFile": "${workspaceFolder}/.env", "debugOptions": [ "RedirectOutput", "DjangoDebugging" ] } Even I mark the break point, vscode doesn't stop. Can anyone please teach me how to fix the bug? -
django-URL inside anchor tag becomes relative to the current page django
urls.py path('add_a_product_to_store/<store_id>',views.add_a_product_to_store,name='add_a_product_to_store'), path('show_a_store/<store_id>', views.show_a_store,name='show_a_store') show_a_store.html <a href="add_a_product_to_store/5">Add a product</a> When user enters ip:port/show_a_store/5 . . . . show_a_store.html is shown. But the link inside anchor tag points to http://127.0.0.1:8000/show_a_store/add_a_product_to_store/5 instead of http://127.0.0.1:8000/add_a_product_to_store/5 How to make it point to actual url irrespective of current page? -
Traversing Django models downstream in template language
I have the following model setup: class Model1(models.Model): val1 = models.CharField(max_length=25, blank=True) val2 = models.CharField(max_length=25, blank=True) user = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='model1') class Model2(models.Model): val3 = models.BinaryField() model1_link = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='model2') class Model3(models.Model): id = models.BigAutoField(primary_key=True) model2_link = models.ForeignKey(Model2, on_delete=models.CASCADE, related_name='model3') class Model4(models.Model): id = models.BigAutoField(primary_key=True) model3_link = models.ForeignKey(Model3, on_delete=models.CASCADE, related_name='model4', null=True, default=None) pred = models.CharField(max_length=50) In my HTML template, I have a section where I iterate over entries from Model1 (e.g. val1), and would like to be able for each value, to include field 'pred' from Model4. Models 1-4 are daisy-chained through their FK`s at the moment. Yes, I know I could just include FK in Model4 linking it to Model1, but from logical point of view, I do not prefer this option at the moment. Anyway, expression like this does not get the job done on my end: ... {% for entry in model1_entries %} ... {% if user.is_superuser and entry.model2.model3.model4.count > 0 %} something here {% endif %} ... {% endfor %} I figure the problem has something to do with the fact that call model1.model2 returns a set of all model2's related to model1, but I dunno how I can pick one in this expression and … -
Forbidden (CSRF cookie not set.):
i am using ajax to post data from asp (as front) to Django rest api (as backend) First, I had a problem in Accessing to different domain but it solved using CORS then i had another error which is related to CSRF and the error like above :Forbidden (CSRF cookie not set.) i've used @csrf_exempt to pass this validation but i want a solution for use it without csrf exmption i tried more than one solution but it's not working or maybe i dont understand the way Is there any clearly solution to solve it in ajax i'll include code of my .cshtml file bellow ''' form id="std_form" class="mx-auto form-horizontal" method="POST" asp-antiforgery="false"> @Html.AntiForgeryToken() <div class="box-body"> <div class=" form-group"> <label for="inputEmail3" class="col-sm-3">ID</label> <div class="col-md-8"> <input type="number" id="first"> </div> </div> <div class=" form-group"> <label for="inputEmail3" class="col-sm-3">ID</label> <div class="col-md-8"> <input type="number" id="second"> </div> </div> <div class=" form-group"> <label for="inputEmail3" class="col-sm-3">ID</label> <div class="col-md-8"> <input type="number" id="third"> </div> </div> </div> <!-- /.box-body --> <div class="box-footer d-flex"> <button type="submit" id="save_btn" class="btn-success btn">Save</button> </div> <!-- /.box-footer --> </form> </div> ''' ''' window.CSRF_TOKEN = "{% csrf_token %}"; function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start … -
Loop over django object
I have a model like this: class Grn(models.Model): owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='grn_owner') warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name="grn_warehouse") vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name="grn_vendor") product1 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product1') product1_quantity = models.IntegerField(default=0) product2 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product2', blank=True, null=True) product2_quantity = models.IntegerField(default=0, blank=True, null=True) product3 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product3', blank=True, null=True) product3_quantity = models.IntegerField(default=0, blank=True, null=True) product4 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product4', blank=True, null=True) product4_quantity = models.IntegerField(default=0, blank=True, null=True) How can I loop over an object of this model? I tried something like this: class GRNFormView(CreateView): model = Grn template_name = 'GrnForm.html' form_class = Grnform def form_valid (self, form): data = form.save(commit=False) print("form.cleaned_data is ", form.cleaned_data) data.owner = Employee.objects.filter(user = self.request.user.id)[0] data.save() print("data is", data) for i in range(1,5): if data.product(i): print("product ", data.product(i)) else: pass How can I check if a product exists in an object and get its value ? -
Why my Django logging config has different behavior in dev vs prod environment
This is how my setting.py looks in dev and prod, DEBUG=False in both: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {funcName} {processName} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {asctime} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'mail_admins': { 'level': 'WARNING', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'verbose', 'include_html': True, }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'v.log', 'formatter': 'verbose' }, 'debug_file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'v_debug.log', 'formatter': 'verbose' }, }, 'root': { 'handlers': ['mail_admins', 'file'], 'level': 'WARNING', 'formatter': 'verbose', }, 'loggers': { 'django': { 'handlers': ['debug_file'], 'level': 'DEBUG', 'propagate': True, 'formatter': 'verbose', }, 'django.request': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True, 'formatter': 'verbose', }, } } In my dev environment I get the desired result as follows: v.log gets: all INFO and above severity logs v_debug.log gets: all DEBUG and above severity logs Email gets WARNING and above security logs But in my prod environment I get different result as follows: v.log gets: WARNING and above security logs, but not INFO logs v_debug.log gets: WARNING and above security logs, but not INFO logs Email gets (expected) WARNING and … -
Effective way to use CSV of DNA information as database in Django project
I am thinking about the design of the following Django project. In this project, I have a CSV file (4 columns, 500 rows) which I am not sure how to handle as the database. the CSV looks like this The data contains 500 codes where each code has 3 scores: f1, f2, f3. The website goal: 1. to get the input of the user of what feature columns data he is interested in and in which order. e.g: 2Xf2 1Xf1 (there are only 3 feature columns: f1, f2, f3 and 'code' column) 2. to generate an output of codes that contains the highest-ranking codes for the required features in the required order. so for our input: 2Xf2 1Xf1 the output will be the following string: [#1 rankning code f2 column] [#2 ranking code f2 column] [#1 rankning code f1 column] I was thinking about creating a database with 3 columns: f1, f2, f3 where in each column there are codes in descending order, so if the user wants 5 codes from f1 I will take the first 5. My question is: How to handle the database in a simple way for developing and maintaining it (not looking for efficiency) that … -
How can I reference ForeignKey in django to populate a pedigree sheet?
I have two models that is linked each other by ForeignKey and OneToOneField as follows: Models class Porumbei(models.Model): serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") ... ... tata = models.ForeignKey('Perechi', to_field='mascul', on_delete=models.CASCADE, related_name="porumbei_masculi", null=True, blank=True) mama = models.ForeignKey('Perechi', to_field='femela', on_delete=models.CASCADE, related_name="porumbei_femele", null=True, blank=True) class Perechi(models.Model): ... mascul = models.OneToOneField(Porumbei, null=True, on_delete=models.CASCADE, limit_choices_to=Q(sex="Mascul"), related_name="perechi_masculi") femela = models.OneToOneField(Porumbei, null=True, on_delete=models.CASCADE, limit_choices_to=Q(sex="Femelă"), related_name="perechi_femele") ... In template I need to populate a table with ancestors of pigeons. To retrieve the pigeon from database I use: Views def editareporumbei(request, pk): porumbel = get_object_or_404(Porumbei, pk=pk) Then, in ancestor table, at father field I use {{ porumbel.tata.mascul }} My question is how I can get the grandfather, grandgrandfather of porumbel? How could I get it in template? Thanks in advance! -
How to make a self updating variable in Django?
I have 2 models, Employee and Designation. I want to count and update no. of Employees in a particular Designation. The project is a multiple user project, So I need a queryset, that focuses regarding the particular user. Models.py class Designation(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="designation",null=True,blank=True) title = models.CharField(max_length=100) count = models.IntegerField(null=True,blank=True) class Employee(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="employee",null=True,blank=True) name = models.CharField(max_length=100) contact = models.CharField(max_length=15) dateJoined = models.DateField(auto_now_add=False,auto_now=False,null=True) designation = models.ForeignKey(Designation,on_delete=models.CASCADE,null=True,blank=True) I need the Variable count in Designation model to auto-update and count the no. of Employees holding a particular Designation -
Proper way of handling file from Django to Firebase Storage
I'm developing a web app in Django which uses Firebase Storage as its media storage place. Currently I have set the app to handle files saving as something like this: template.html <form enctype="multipart/form-data" method="post" action="{% my_view %}> {% csrf_token %} <input type="file" name="my_file"> <input type="submit"> </form> views.py # All the imports... cred = credentials.Certificate(os.path.join(settings.BASE_DIR, 'serviceAccountKey.json')) initialize_app(cred, { 'storageBucket': settings.FIREBASE_STORAGE_BUCKET}) bucket = storage.bucket() def my_view(request): file = request.FILES['my_file'] path = utils.handle_upload_file(file) blob = bucket.blob(blob_name=str(file)) blob.upload_from_filename(path) # Other logic... return redirect('home') utils.py def handle_upload_file(file): path = os.path.join(settings.BASE_DIR, 'media', str(file)) try: with open(path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) except FileNotFoundError: os.mkdir('media') handle_upload_file(file) return path Okay, let me break this down: User uploads a file I receive the file, process and save it to my server (with the handle_upload_file method) File is sent to Firebase Storage User gets redirected to home view. Now, even though it works as expected, I feel like I'm doing an unnecessary step when I save it to my server. Nevertheless, I've tried with the blob.upload_from_file function to avoid the aforementioned step and I've been able to save it directly to Firebase Storage, but it gets saved in a weird way so I went back to my … -
Docker container does not communicate with others in same docker network(bridge)
I'm trying to set the environment for web server on amazon web server. I want to use django, react, nginx and they are running on each docker container. Belows are the command for running docker container. sudo docker run --name django-server -it -d -p "8000:8000" --volume=$(pwd)/trello-copy-django-src:/backend/trello-copy django-server sudo docker run --name nginx-server -d -p "80:80" --volumes-from react-server nginx-server I did not specified a custom docker network bridge and I checked that they are on same default bridge by typing $ docker inspect bridge. [{ "Name": "bridge", ..., "Containers": { "...": { "Name": "django-server", ... }, "...": { "Name": "react-server", ... }, "...": { "Name": "nginx-server", ... }, } }] So, I expected the react code down below works. But it worked only at my laptop, which has exactly same docker structure of aws. ... const res = await fetch('http://127.0.0.1:8000/api/'); ... Failed to load resource: net::ERR_CONNECTION_REFUSED 127.0.0.1:8000/api/:1 What am I doing wrong? -
How to Call a Foreign Key from a foreign App where the key is non Primary key in Django
I am still a newbie in Django. And Started working on task tracker DB. I have different apps like user, task,status etc., Now I am trying to call userID in different app, which is actually an ID in user table(by default autogenerated column). Below is example where I want to call ID from user app to Status app as userID.. from user.models import User userID = models.ForeignKey(User, to_field="id", db_column="userID", default="", editable=False, on_delete=models.CASCADE) But I am getting this error in my terminal django.db.utils.OperationalError: foreign key mismatch - "status_status" referencing "user_user" Error_Img Also my table name is coming like status_status, user_user Not sure where I am going wrong? can anyone please help me out..? Thanks in advanced! Have a great day.. -
How to autofill values from db in django
Guys i am quite new in django and for learning purpuse i am making mini project for better learning and understanding. Try to do a lot of stuff on my own, but there are stuff that i can't make work. There is a entry filed where a user enters product code. Each code has its product name. I want when i enter product code the field bring me otpions of its product names. Here is my models.py: class NM(models.Model): name = models.CharField(max_length=150) class Products(models.Model): productcode=models.CharField(max_length=200) productname=models.CharField(max_length=500) My views.py: def home(request): if request.method == "POST": form = NMForm(request.POST) if form.is_valid(): for_m = form.save(commit=False) name = for_m.name My template.html: <form method="POST" > {% csrf_token %} {{ form}} <button type="submit">OK</button> </form> I tried to insert the following code in my template.html: {% for field in form.visible_fields %} {{ field.errors }} {{ field }} {% endfor %} Howvere this code does nothing. It does not generate the desited action for me. Can someone help me with it ? I would appreciate your help and any advice. -
Unable to pip install psycopg2
I have been trying to google this all over the internet and still can't figure out how to get this package installed. Any help is much appreciated. I have tried numerous examples from google to no avail. Mac OS 10.15.3 pip freeze asgiref==3.2.5 dj-database-url==0.5.0 Django==3.0.4 entrypoints==0.3 flake8==3.7.9 gunicorn==20.0.4 mccabe==0.6.1 postgres==3.0.0 psycopg2-binary==2.8.4 psycopg2-pool==1.1 pycodestyle==2.5.0 pyflakes==2.1.1 pytz==2019.3 sqlparse==0.3.1 whitenoise==5.0.1 pip install psycopg2 Collecting psycopg2 Using cached psycopg2-2.8.4.tar.gz (377 kB) ERROR: Command errored out with exit status 1: command: /Users/keeganleary/Documents/Coding/life_cal/venv/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '" '"'/private/var/folders/s6/f4q9mnjn7q9b34gw7bz35l680000gn/T/pip-install-qwbzap8s/psycopg2/setup.py'"'"'; __file__='"'"'/private/va r/folders/s6/f4q9mnjn7q9b34gw7bz35l680000gn/T/pip-install-qwbzap8s/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open )(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/s6/f4q9mnjn7q9b34gw7bz35l680000gn/T/pip-install-qwbzap8s/psycopg2/pip-egg-info cwd: /private/var/folders/s6/f4q9mnjn7q9b34gw7bz35l680000gn/T/pip-install-qwbzap8s/psycopg2/ Complete output (12 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/Users/keeganleary/Documents/Coding/life_cal/venv/lib/python3.8/site-packages/setuptools/__init__.py", line 20, in <mo dule> from setuptools.dist import Distribution, Feature File "/Users/keeganleary/Documents/Coding/life_cal/venv/lib/python3.8/site-packages/setuptools/dist.py", line 34, in <module > from setuptools.depends import Require File "/Users/keeganleary/Documents/Coding/life_cal/venv/lib/python3.8/site-packages/setuptools/depends.py", line 7, in <modu le> from .py33compat import Bytecode File "/Users/keeganleary/Documents/Coding/life_cal/venv/lib/python3.8/site-packages/setuptools/py33compat.py", line 2, in <m odule> import array ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/array.cpython-38-darwin.so, 2) : no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/array.cpython-38-darwin.so: code signature in (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/array.cpython-38-darwin.so) not valid for use in proc ess using Library Validation: Library load disallowed by System Policy ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info … -
Django+Postgres FATAL: sorry, too many clients already
I get the "FATAL: sorry, too many clients already" every now and then because I have a lot of idle connecions in Postgres, and I cannot understand where they are coming from or how to prevent them. At first I tried the CONN_MAX_AGE setting in Django but it does not seem to have an effect. I also set idle_in_transaction_session_timeout to 5min in Postgres, but I keep seeing a lot of idle transactions: postgres=# select client_addr, state, count(*) from pg_stat_activity group by client_addr, state; client_addr | state | count ---------------+--------+------- | | 5 | active | 1 | idle | 1 172.30.12.148 | idle | 2 172.30.12.74 | idle | 89 (5 rows) postgres=# select client_addr, state, backend_start, query_start from pg_stat_activity order by query_start ; client_addr | state | backend_start | query_start ---------------+--------+-------------------------------+------------------------------- | idle | 2020-03-24 20:03:16.060707+00 | 2020-03-24 20:55:17.020962+00 172.30.12.74 | idle | 2020-03-25 02:05:32.567976+00 | 2020-03-25 02:05:32.613112+00 172.30.12.74 | idle | 2020-03-25 02:05:34.926656+00 | 2020-03-25 02:05:34.945405+00 172.30.12.74 | idle | 2020-03-25 02:05:49.700201+00 | 2020-03-25 02:05:49.717165+00 [...] 172.30.12.74 | idle | 2020-03-25 04:00:51.019892+00 | 2020-03-25 04:01:22.627659+00 172.30.12.74 | idle | 2020-03-25 04:04:18.333413+00 | 2020-03-25 04:04:18.350539+00 172.30.12.74 | idle | 2020-03-25 04:04:35.157547+00 | 2020-03-25 04:05:16.746978+00 172.30.12.74 | idle | 2020-03-25 … -
Indexes in Django PostgreSQL
MY MODEL Below is the code for my model class Email_passwords(models.Model): email = models.CharField(db_index=True, max_length=50) password = models.CharField(db_index=True, max_length=40) source = models.CharField(default='unknown', max_length=150) domain = models.CharField(db_index=True, max_length=50) before_at = models.CharField(max_length=255) username = models.CharField(db_index=True, max_length=150) hash = models.CharField(db_index=True, max_length=255) ipaddress = models.CharField(db_index=True, max_length=50) phonenumber = models.CharField(db_index=True, max_length=100) class Meta: constraints = [ models.UniqueConstraint(fields=['email', 'password', 'source'], name='email password source unique') ] index_together = [ ("domain", "before_at"), ] def __str__(self): return self.email I was expecting total 7 indexes on this table but when i checked in database i got like 17 are there by default indexes on the table As you can see by clicking here the indexes for the table created by above model What i want is to perform search using one field at a time though table.This table my contains billions of record. I want to achieve the maximum performance. -
Choosing a backend web language for a newbie
I'm not sure if this is the appropriate place to put this question, I'm relatively new here, so I apologize if it's not. I'm not a big fan of front end development (or Javascript, but I'd learn it if necessary) and thought I'd learn backend instead, as I think may enjoy that more. My main goal is to obtain a job (I have no issues with moving states/countries either) while also working on my own personal projects like a blog, portfolio, web apps, and such. I have some experience with JS, C#, and Python, but honestly, I'm not even sure where to start, and have no problems delving into a language, even if it's not one I know. I've been debating between node.js, asp.net, django/flask, or ruby on rails, but looking for a more informed opinion. Here are some of the questions rolling around in my head: Which one offers me the most potential for jobs? Which is easiest for a beginner to get into? Which is most recommended in general? All advice and suggestions welcome, or even answers to questions I can't even think of. Thank you all very much for your time and opinions! -
Django serializer not saving data during create
I am trying to save data by creating serializer. I have the data passed in as the serializer's argument, and after validating and saving the serializer, I can see the data when I print (serializer). However, if I print(serializer.data), part of the data is missing. view: class TaskList(generics.ListCreateAPIView): serializer_class = TaskSerializer pagination_class = None permission_classes = [IsAuthenticated ] def get_queryset(self): return TaskProject.objects.all().filter(users=self.request.user) def create(self, request, *args, **kwargs): data=request.data projects = [] for id in request.data['projects'].split(','): projects.append(Project.objects.get(id=id)) data['projects']=projects serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer,projects) headers = {} print("serializer data",serializer.data) print("serializer",serializer) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer, projects): print(projects) obj = serializer.save(users=[self.request.user]) if not self.request.user.is_superuser: ProjectRoleMapping.objects.create(user=self.request.user, task=obj, role=Role.objects.get_or_create(name=settings.ROLE_PROJECT_ADMIN)[0]) serializer: class ProjectSerializer(serializers.ModelSerializer): current_users_role = serializers.SerializerMethodField() def get_current_users_role(self, instance): print("p in serializer") role_abstractor = { "is_project_admin": settings.ROLE_PROJECT_ADMIN, "is_annotator": settings.ROLE_ANNOTATOR, "is_annotation_approver": settings.ROLE_ANNOTATION_APPROVER, } queryset = ProjectRoleMapping.objects.values("role_id__name") if queryset: users_role = get_object_or_404( queryset, project=instance.id, user=self.context.get("request").user.id ) for key, val in role_abstractor.items(): role_abstractor[key] = users_role["role_id__name"] == val return role_abstractor class Meta: model = Project fields = ('id', 'name', 'description', 'guideline', 'users', 'current_users_role', 'project_type', 'image', 'updated_at', 'randomize_document_order', 'collaborative_annotation') read_only_fields = ('image', 'updated_at', 'current_users_role') class TaskSerializer(ProjectSerializer): class Meta: model = TaskProject fields = ('id', 'name', 'description', 'guideline', 'users', 'current_users_role', 'updated_at', 'ignore_unlabeled_files', 'project_type', 'projects') read_only_fields = ('updated_at', 'current_users_role', 'users', 'projects') … -
Django order by custom list
I have problem of ordering the queryset. For example, it will be sorted desc. If they have same priority so can't define specific order, they will use second priority. # list = [[id, priority], ...] list_1 = [[1,2],[2,3],[3,3],[4,4]] # first priority list_2 = [[1,4],[2,5],[3,7],[4,2]] # second priority using first priority : 4 -> (2,3) -> 1 using second priority : 4 -> 3 -> 2 -> 1 result = 4 -> 3 -> 2 -> 1 So i want to get queryset, ordered like result id sequence. -
How Calculate Hours and OT Hours, save to database?
I'm trying to calculate login and logout and convert it into total hours. If the time exceeds 9 hours it should then calculate OThours. Then save both total hours and OThours into my model. How can I go around this? I know it's by using property but I'm not sure how to get the syntax right with this. I just need some advice and insight on what to do, any help is appreciated TIA. Here is my code: testuser = models.ForeignKey(User,on_delete = models.CASCADE,unique_for_date= 'reportDate') status = models.CharField(max_length=30, choices=STATUS_CHOICES,null=True) reportDate = models.DateField(blank=False, null=False) login = models.TimeField(blank=False, null=False) logout = models.TimeField(blank=False, null=False) totalHours = models.DecimalField(max_digits=4,decimal_places=2,null=True) OTHours = models.DecimalField(max_digits=4,decimal_places=2,null=True) mainTasks = models.CharField(max_length=50, blank=False, choices=TASKS_CHOICES, null=True) remarks = models.CharField(max_length=30,null=True) def __str__(self): return f'{self.testuser.full_name} DPR Log' @property def CalculateTotalHours(self): self.totalHours = self.logout.timeDelta - self.login.TimeDelta return self.TotalHours @property def OTHours(self): if self.totalHours > 9.00: self.OTHours = self.totalHours-9.00 -
how to add a custom field that is not present in database in graphene django
so my model looks like class Abcd(models.Model): name = models.CharField(max_length=30, default=False) data = models.CharField(max_length=500, blank=True, default=False) need to pass a dictionary at query time which is not a part of model, query is query { allAbcd(Name: "XYZ") { edges { node { Data } } } } How does one pass such a custom field with the query ?. This custom field is required for other process purpose. -
get user id in Django clas based view
i'm trying to implement the following class View and populate customer field with a filtered list of customers retrieved from Customers Model but filtered by user id class SellCreateView(CreateView): model = Sell fields = [ 'name', 'store', 'customer', ] in function based view i do something like the following: def sell_create(request): customer_list = Customer.objects.filter(belongs_to=request.user.id) ... form.fields['customer'].queryset = customer_list but i can't make this work in class view! Any idea how should i do this? Thanks! -
Using Django how to format fields rendered by __all__
I am using Django. Getting fields from database > models > forms by using all. I would like to place the fields in the html to my convenience. How to go ahead with that? -
mod_wsgi cannot import django, but local python can do
Please help me. What I want to do I want to deploy my Django application. Sample code reproduce probrem import django def application(environ, start_response): start_response("200 OK", [("Content-type", "text/plain")]) return ['hello, world'.encode('utf-8')] This works well when I start python from console, but raise ModuleNotFoundError when I call this from web browser (No module named 'django'). $ python3 Python 3.8.2 (default, Mar 24 2020, 02:28:58) [GCC 7.5.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import wsgi >>> wsgi.application(None, lambda x, y: print(x, y)) 200 OK [('Content-type', 'text/plain')] [b'hello, world'] [Wed Mar 25 02:27:58.115629 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] mod_wsgi (pid=1717): Failed to exec Python script file '/home/ubuntu/grabar/wsgi.py'. [Wed Mar 25 02:27:58.115706 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] mod_wsgi (pid=1717): Exception occurred processing WSGI script '/home/ubuntu/grabar/wsgi.py'. [Wed Mar 25 02:27:58.115888 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] Traceback (most recent call last): [Wed Mar 25 02:27:58.115917 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] File "/home/ubuntu/grabar/wsgi.py", line 1, in <module> [Wed Mar 25 02:27:58.115924 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] import django [Wed Mar 25 02:27:58.115955 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] ModuleNotFoundError: No module named 'django' [Wed Mar 25 02:27:58.410154 2020] [authz_core:error] [pid …