Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When i create a Group in Django it automatically applies all users to group
I'm trying to create a group, and when I create that group I then want to add the user to that group, but whenever I create a group it automatically adds all users to that group, and I don't want that to happen so i can add users to that group as needed. my models.py class MlptUsers(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) edipi = models.PositiveIntegerField(unique=True, blank=True, null=True) display_name = models.CharField(max_length=45, blank=True, null=True) phone = models.CharField(max_length=45, blank=True, null=True) date_joined = models.DateTimeField( verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) unit = models.ManyToManyField(Units) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'edipi'] objects = MyAccountManager() def __str__(self): return f"User: {self.display_name}\tEDIPI: {self.edipi}\tEmail: {self.email}\tPhone: {self.phone}" class MyAccountManager(BaseUserManager): def create_user(self, email, username, edipi, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') if not edipi: raise ValueError('User must have a Edipi') user = self.model( email=self.normalize_email(email), username=username, edipi=edipi, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, edipi, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, edipi=edipi, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class … -
How to pass parameter variable from Django web to python script?
I have a python script that will be triggered to read an inbox and send email to an gmail account when some condition is meet. In order to send , the script will filter through subject or text of the incoming email. Currently the script is just hard-coded format and I prefer the condition is dynamically set by the user. I created a django website and let user to input their condition, but I do not know how can I pass the parameter from the web to my python script. I already do my researched on the internet but couldn't found any useful source, does anyone can help me or send my any related article for me to read ? Thanks My py script import datetime import email import imaplib import mailbox import smtplib EMAIL_ACCOUNT = "zhuangah@macrovention.com" PASSWORD = "P@ssw0rd456" mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login(EMAIL_ACCOUNT, PASSWORD) mail.list() mail.select('inbox') result, data = mail.uid('search', None, "UNSEEN") # (ALL/UNSEEN) i = len(data[0].split()) for x in range(i): latest_email_uid = data[0].split()[x] result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)') # result, email_data = conn.store(num,'-FLAGS','\\Seen') # this might work to set flag to seen, if it doesn't already raw_email = email_data[0][1] raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) # Header … -
Trying to connect Google Vision AI to Django
On my Django website the user is able to upload images. I am trying to implement a feature for them to search for images based on what the images are. To do this I decided to use Google Vision AI. I was able to get this API to work in a separate project. However, when I try implementing the API into my Django project it doesn't work. (Error pasted at the end). In my test project I had to create an environment variable for the Google Application Credentials, this is what it looked like: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'venv/filename.json' After reading several articles on how to implement environment variables into Django, this is what I implemented thus far into settings.py: env = environ.Env() environ.Env.read_env() GOOGLE_APPLICATION_CREDENTIALS = env('GOOGLE_APPLICATION_CREDENTIALS') As a test to see if environment variables were working at all in my project, I stored the SECRET_KEY into the .env file and I got it to work. Here is what that looked like along with my .env file .env GOOGLE_APPLICATION_CREDENTIALS=venv/filename.json SECRET_KEY=this-is-my-secret##key SECRET_KEY: SECRET_KEY = env('SECRET_KEY') The error I am getting: DefaultCredentialsError at /images/ File venv/filename.json was not found. Please help me to figure out why my environment variable is not working -
Configure the DEFAULT_AUTO_FIELD setting or the MainConfig.default_auto_field attribute to point to a subclass of AutoField,
?[33;1mmain.in_touch: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the MainConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.?[0m -
Add API key to a header in a DRF browsable API page
I am enabling token/api-key authentication on my API. But once I enable it, I can no longer use the browsable API page of the DRF. I know I can disable the authentication while developing, but this is a question of curiosity: Can I add an api-key to the header of each request sent to the browsable API page? Can I do that by tweaking the Browser settings? Or is it possible to tweak the Browsable API page itself and hardcode the api-key into it? -
OSError: [Errno 22] Invalid argument: '/proc/37369/task/37369/net when trying to run django project
I keep getting this error when I try to run my Django Project using python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 11, 2021 - 05:08:26 Django version 3.2.2, using settings 'homeworkanswers.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 637, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 622, in start_django reloader.run(django_main_thread) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 328, in run self.run_loop() File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 334, in run_loop next(ticker) File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 374, in tick for filepath, mtime in self.snapshot_files(): File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 390, in snapshot_files for file in self.watched_files(): File "/home/colton/Desktop/homeworkanswers/HomeworkAnswers.Co/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 293, in watched_files yield from directory.glob(pattern) File "/usr/lib/python3.8/pathlib.py", line 1139, in glob for p in selector.select_from(self): File … -
How to bulk delete django model data in optimized way
I have at around 30K data in one of the model say A and A is a foreign key in model B, model B have 10cr data. class A(models.Model): type = models.CharField(max_length=100, choices=SOME_CHOICE) class B(models.Model): a = modles.ForeignKey(A, on_delete=models.CASCADE) I am fetching all the A data by applying some filters and now when I am deleting it, it also deletes corresponding models B data which is expected but model B has more than 10cr data because of this it is taking time and huge loads to the db. what I did is I am deleting model A data in batch wise and after each batch I put timeout of 0.5 sec. Below is my code: batch_size = 100 while True: counter = 0 offset = counter * batch_size min_value = offset max_value = offset + batch_size batch = queryset[min_value:max_value] if not batch: break batch.delete() time.sleep(0.05) is there any other way to optimize this. Please suggest. -
send values to views.py from forms other than vlaue entered in input
I am trying to work on making a dynaic form in Django. I am sending a list of item from my views.py and I want to have each list display with a '+' button and a form associated to it. I have a form that I put in the for loop in template while displaying my list but i donno how to tell my views that which input belongs to which data? my template : {% for each in lists %} <ul> <li>|| {{each.name}} ||{{each.l_category}} </li> <form method="POST" action="">{% csrf_token %} <input type="submit" name="addItem" value="+"><br> {{new_item}} </form> </ul> {% endfor %} Forms.py class ItemForm(forms.Form): item =forms.CharField() Views.py: if "addItem" in request.POST: new_item = ItemForm (request.POST) if new_item.is_valid(): name=new_item.cleaned_data.get("item") slist = List.objects.get(name='<list>') #<------- How to send? p=Item(name=name,slist=slist) p.save() else: new_item = ItemForm() lists= List.objects.all() the model has items and list where item has a foreign key to list. Is there a different approach than adding the form in for loop?? -
django admin change page add foreign key error: server refuses to connect
I have a model called "press" with a field for "lab", which is another model. on the admin change page for an object in "press", I can choose the "lab" from a list, or click the green plus sign to add a new one. In development, this works fine. the choice box: after clicking the 'add' sign IN DEVELOPMENT looks good. BUT, on my actual site, this is what happens. the red is the name of the server/root url of the site This is not the only time this happens. It is every 'plus' button that adds a new item to a foreign key field. the link on the button in this case was dev: http://.../admin/press/lab/add/?_to_field=id&_popup=1 actual: https://.../admin/press/lab/add/?_to_field=id&_popup=1 everything there looks ok. ALSO on the actual site, if i click 'add' on the left menu, it works fine. in that case, the link is: https://.../admin/press/lab/add/ is the problem because the first case is a popup? any ideas? -
Check if data exists in Django annotate queryset
Environments Django 2.0 DRF 3.11 mariaDB I want to output'N' if at least one of the columns is 0, and'Y' if all of them are 1. Database Model class UserPoint: user = models.ForeignKey('User', others options) poinit = models.IntegerField() used = models.SmallIntegerField(default=0) deleted = models.SmallIntegerField(default=0) Expected results total_point_used : Sum of points where used is 1 used_status : 'N' if any of used has 0 or 'Y' if all values of used are 1 user username total_point_used used_status 1 'AA' 600 'N' 2 'BB' 0 'N' 3 'CC' 500 'Y' Tried queryset q = UserPoint.objects.filter( deleted=0 ).values( username=F('user__username') .... others values .... ).annotate( total_point_used=Sum( # Sum of used point Case( When( used=1, then='point', ), output_field=IntegerField(), ) ), # I don't know what to do with used_status. # tried <- not work #used_status=Case( # When( # used=1, # then=Value('Y') # ), # default=Value('N'), # output_field=CharField() # ) # I want something like this. used_status=Exists(used=0, then='N', default='Y') ) How can I get the value I expect in annotate? -
Error "Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?" in postgresql on docer
I have Django application with postgresql on docker. I tried to insert data like this: import psycopg2 try: connection = psycopg2.connect(user="postgres", password="postgres", host="127.0.0.1", port="5432", database="postgres_db") cursor = connection.cursor() postgres_insert_query = """ INSERT INTO Test (smth1, smth2) VALUES (%s,%s)""" record_to_insert = (5, 950) cursor.execute(postgres_insert_query, record_to_insert) connection.commit() count = cursor.rowcount print(count, "Record inserted successfully into mobile table") except (Exception, psycopg2.Error) as error: print("Failed to insert record into mobile table", error) finally: # closing database connection. if connection: cursor.close() connection.close() print("PostgreSQL connection is closed") but I have this error: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? In my postgresql.conf file I have this lines: listen_addresses = '*' and port = 5432 My pg_hba.conf file looks like this: TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. local replication all trust host replication all 127.0.0.1/32 trust host replication all ::1/128 trust host all all all md5 How can I fix this error and insert … -
How to add a message time sent just like facebook messenger?
I have a simple project that i have been working on for almost 3 days now and this project is a chat app that you can send and receive message. So i want to add a time that when i send a message just like in facebook messenger it have "just now", "2 mins ago or hour ago", "6 days ago", and also "the year and the time that i send that message". So i found a solution using react and js but i don't have any knowledge with react and js. Can someone help me to add a message sent time like messenger on my chat app project. views.py def message_view(request, sender, receiver): if not request.user.is_authenticated: return redirect('index') if request.method == "GET": return render(request, "chat/messages.html", {'users': User.objects.exclude(username=request.user.username), 'receiver': User.objects.get(id=receiver), 'messages': Message.objects.filter(sender_id=sender, receiver_id=receiver) | Message.objects.filter(sender_id=receiver, receiver_id=sender)}) messages.html {% extends 'chat/chat.html' %} {% block messages %} {% for message in messages %} {% if message.sender == request.user %} <div class="card-panel right" style="width: 75%; position: relative"> <div style="position: absolute; top: 0; left:3px; font-weight: bolder" class="title">You</div> {{ message }} </div> {% else %} <div class="card-panel left blue lighten-5" style="width: 75%; position: relative"> <div style="position: absolute; top: 0; left:3px; font-weight: bolder" class="title">{{ message.sender }}</div> … -
I am missing basic and can not get my html page to populate with the data I have correctly generated
I need to look up a stock price and then display it on an quoted.html. I generate the data correctly in my function, but can not get my html page to read the data. Here is my function: @app.route("/quote", methods=["GET", "POST"]) @login_required def quote(): """Get stock quote.""" if request.method == "POST": # Ensure ticker was submitted if not request.form.get("symbol"): return apology("must input stock symbol") else: # Get symbol and make sure it exists symbol = request.form.get("symbol") quote = lookup(symbol) if not quote: return apology("symbol does not exist") else: # to show company name and price print(quote["name"], quote["price"]) return render_template("quoted.html", name=quote["name"], price=quote["price"]) # User reached route via GET (as by clicking a link or via redirect) else: return render_template("quote.html") It is quoted.html that does not load: {% extends "layout.html" %} {% block title %} Quoted With values from lookup {% endblock %} {% block body %} <p> One share of {{ name }} costs ${{ price }} </p> {% endblock %} I thought I was following the example from the class notes, but I get a blank screen after I put in a stock ticker and ask for the quote, but I can see that the quote is correctly done. I … -
What might be the consequences of disabling Garbage Collection in Django?
While running my application, I noticed that pods in Kubernetes reset due to insufficient memory. The reason for this behavior was that the memory after a given request was not freed but was still reserved. Additionally, the next request increased the reserved memory. The workaround for this problem was to properly configure gunicorn, that is, turning the Garbage Collection off and on between requests. Below is the solution that can be found in the gunicorn configuration file. import gc bind = ":8000" worker_tmp_dir = "/dev/shm" workers = 1 timeout = 300 def pre_request(worker, req): gc.disable() def post_request(worker, req): gc.enable() What are the side effects of this solution? -
How to set a default value on TextInput widget?
I have created a forms.py file, find below code. I would like to get the current login user from function add_cr of view.py then send this value to the pm widget. Please advise how to achieve that, thanks! class TaskForm(ModelForm): class Meta: model = Task fields = ('user', 'cr_date', 'project_name', 'cr_description', 'cr_project_code', 'attendance_point', 'result_point', 'pm', 'remark', ) labels = { 'user': "Select Engineer", 'cr_date': "CR date", 'project_name': "", 'cr_description': "", 'cr_project_code': "", 'attendance_point': "出勤", 'result_point': "作業結果", 'pm': "PM", 'remark': "", } MONTHS = { 1:('1月'), 2:('2月'), 3:('3月'), 4:('4月'), 5:('5月'), 6:('6月'), 7:('7月'), 8:('8月'), 9:('9月'), 10:('10月'), 11:('11月'), 12:('12月') } widgets = { 'user': forms.Select(attrs={'class':'form-select'}), # 'cr_date': forms.SelectDateWidget(months=MONTHS, attrs={'style': 'font-size: 15px'}), 'cr_date': forms.NumberInput(attrs={'type': 'date'}), 'project_name': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Enter Project Name'}), 'cr_description': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Enter CR content'}), 'cr_project_code': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Enter Project Code'}), 'attendance_point': forms.Select(attrs={'class':'form-select'}), 'result_point': forms.Select(attrs={'class':'form-select'}), 'pm': forms.TextInput(attrs={'class':'form-select'},), 'remark': forms.TextInput(attrs={'class':'form-control', 'placeholder': '[Optional] : Enter a reamrk for CR ' }), } -
TemplateDoesNotExist at home.html
I have been tinkering at this for an hour plus but can't figure it out. I'm getting the following error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.4 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: C:\Users\nollb\Desktop\florafanatics\florasite\templates\home.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\nollb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\admin\templates\home.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\nollb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\templates\home.html (Source does not exist) Traceback (most recent call last): File "C:\Users\nollb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\nollb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\nollb\desktop\florafanatics\florasite\pages\views.py", line 5, in home return render(request, 'home.html') File "C:\Users\nollb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\nollb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\nollb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at / Exception Value: home.html The project structure looks like: Heres urls.py inside pages: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'flora-home'), path('home/', views.home, name = 'flora-home') ] Here's the view I'm trying to render: … -
djnago migrationis applied before its dependency
First of all, hello, I encountered this error and did not even know the reason for its occurrence Migration api.0001_initial is applied before its dependency auth.0013_auto_20210510_1928 on database 'default' I searched a lot and some solutions looked like delete __pyc file remove changes and run ` migrate --fake-initial remove migrations file and remigrate remove django_migrations table These solutions brought me to errors like Django migration dependencies reference nonexistent parent node django.db.utils.ProgrammingError: relation "django_content_type" django.db.utils.ProgrammingError: column "name" of relation "django_content_type" does not exist Until I completely wipe the database I did not find any real solution or what caused this to happen Currently, I did not have important data but what really caused this problem to avoid it or a correct solution method from the beginning -
ValueError at /create The view djangoproj1.view.stinsert didn't return an HttpResponse object. It returned None instead
I have created simple student details form for getting marks,name,dob of the student. Iam very very new to django. Please help to clear this error IN view.py from django.shortcuts import render from djangoproj1.models import crudst from django.contrib import messages def stdisplay(request): results=crudst.objects.all() return render(request,"index.html",{"crudst":results}) def stinsert(request): if request.method=="POST": if request.POST.get('stname') and request.POST.get('stregno') and request.POST.get('stdob') and request.POST.get('stsubmath') and request.POST.get('stsubenglish') and request.POST.get('stsubsocial') and request.POST.get('stsubscience'): savest=crudst() savest.stname = request.POST.get('stname') savest.stdob = request.POST.get('stdob') savest.stsubmath = request.POST.get('stsubmath') savest.stsubenglish = request.POST.get('stsubenglish') savest.stsubsocial = request.POST.get('stsubsocial') savest.stsubscience = request.POST.get('stsubscience') sum = int(savest.stsubmath ) + int(savest.stsubenglish) +int(savest.stsubsocial)+ int(savest.stsubscience) avg = sum/4 savest.staverage = avg # grade="" # savest.stgrade = grade savest.save() messages.success(request,"The Record "+savest.stname+ " is saved succesfully.") return render(request,"create.html") else: return render(request,"create.html") Error message ValueError at /create The view djangoproj1.view.stinsert didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:8000/create Django Version: 3.2.2 Exception Type: ValueError Exception Value: The view djangoproj1.view.stinsert didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\Raji\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 309, in check_response Python Executable: C:\Users\Raji\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.2 please help me to clear this error. IDK where I have done the mistake. Thanks in advance -
Inlineformset is just saving the first form
I am using InlineFormset to get several forms input and save them to the database. Problem is only first one is saved while added forms (dynamically with js) are just ignored. Here is needed code content: ***My view function:*** def profile(request): '''Manage the profile page where we need two form''' # Define an Inlineformeset to manage foreign key between Pitche and User PitchesFormSet = inlineformset_factory( User, Pitch, fields=( 'pitch_title', 'content'), widgets={'content': forms.FileInput(attrs={'accept':'video/*'})}, extra=0) if request.method == 'POST': # Post modified pitch for the current user formset = PitchesFormSet(request.POST, request.FILES, instance=request.user) # Post profile data for the current user depending on his role if request.user.role.role_title == 'Candidate': p_form = CandidateProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile) elif request.user.role.role_title == 'Supplier': p_form = SupplierProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile) else: p_form = RecruiterProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile) # Save when all forms are valid if p_form.is_valid() and formset.is_valid(): p_form.save() formset.save() return redirect('pitches:feed') else: # Display current user pitches in a get request formset = PitchesFormSet(instance=request.user) # Display profile data for the current user depending on his role if request.user.role.role_title == 'Candidate': p_form = CandidateProfileUpdateForm(instance=request.user.profile) elif request.user.role.role_title == 'Supplier': p_form = SupplierProfileUpdateForm(instance=request.user.profile) else: p_form = RecruiterProfileUpdateForm(instance=request.user.profile) # Add these forms to the context context = { 'formset': formset, 'p_form': … -
Which is the best way to save multiple data from chechboxes in django
I'm trying to save data from template, when user select there multiple choice of fields (Like MCQ's). not want to use JavaScript & JQuery on that, please share your valuable comments. -
Conditional to not display a form in Django
I have a conditional that won't let display the form if the user has filled the address before, but my issue is when I try to submit the other form I'll get this error: The Profile could not be created because the data didn't validate. How can I work around that? def addbooking(request, car_id): if request.method == 'POST': profile_form = ProfileForm(request.POST) booking_form = BookingForm(request.POST) print(request.POST) if booking_form.is_valid() or profile_form.is_valid(): # do stuff here # form = ProfileForm(request.POST) new_profile = profile_form.save(commit=False) new_profile.car_id = car_id new_profile.user_id = request.user.id new_profile.save() # do stuff here # form = BookingForm(request.POST) new_booking = booking_form.save(commit=False) new_booking.car_id = car_id new_booking.user_id = request.user.id new_booking.save() return redirect('detail', car_id=car_id) else: profile_form = ProfileForm(prefix="profile_form") booking_form = BookingForm(prefix="booking_form") my conditional <div> <form action="{% url 'addbooking' car.id %}" method="POST"> {% csrf_token %} {{ booking_form.as_p }} {% if not user.profile.zipcode %} {{ profile_form.as_p }} {% endif %} <input type="submit" class="btn" value="Add booking"> </form> </div> -
Django template won't display model object attributes on page
I am attempting to display the attributes of my model object in a Django template but the data will not appear in the page source. In views.py def view_func(request): ... data = ModelObj.objects.all() print(data) #prints <QuerySet [ <ModelObj: ModelObj object (primary_key)>, ... ]> return render(request, "templates/app/page.html", {'data': data}) In page.html ... formatted html ... <thead> ... </thead> <tbody> { % for i in data % } <tr> <td> {{ i.name }} </td> <td> {{ i.time }} </td> <td> {{ i.value }} </td> </tr> { % endfor % } <tbody> When I view the page source after running the Django site: ... html ... <tbody> { % for i in data % } <tr> <td></td> <td></td> <td></td> </tr> { % endfor % } <tbody> If I add <td> {{data}} </td> to the html page, I can see the <QuerySet [ <ModelObj: ModelObj object (primary_key)>, ... ]> display on the page, but Django will not display the model object attributes on the page. Any help with this error is appreciated, thank you. -
How to import and manage the database in postgresql on the docker?
I have my Django project with structure like this: myapp/ manage.py Dockerfile docker-compose.yml my-database1.sql my-database2.sql requirements.txt pgadmin/ pgadmin-data/ myapp/ __init__.py settings.py urls.py wsgi.py This is my docker-compose.yml file: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./my-database1.sql:/docker-entrypoint-initdb.d/my-database1.sql - ./my-database2.sql:/docker-entrypoint-initdb.d/my-database2.sql environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - PGDATA=/var/lib/postgresql/data pgadmin: image: dpage/pgadmin4:4.18 restart: unless-stopped environment: - PGADMIN_DEFAULT_EMAIL=admin@domain.com - PGADMIN_DEFAULT_PASSWORD=admin - PGADMIN_LISTEN_PORT=80 ports: - "8090:80" volumes: - ./pgadmin-data:/var/lib/pgadmin links: - "db:pgsql-server" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db volumes: db-data: pgadmin-data: I have three problems with my app: 1 - how can I import my my-database1.sql and my-database2.sql databases into postgresql? The solution (I mean ./my-database1.sql:/docker-entrypoint-initdb.d/my-database1.sql) in my code doesn't work. 2 - after successful import databases from previous step how can I see them inside pgadmin? 3 - my code should write something inside tables of my-database1.sql. How should I connect to it after import to postgresql? -
Why is the ajax status ifModified always success?
There is such an ajax code: $(document).ready(function(){ setInterval(poll_for_new_messages, 2000); function poll_for_new_messages(){ $.ajax( { url: 'messages.json', type: 'get', dataType: 'json', ifModified: true, cache: true, timeout: 2000, success: function(messages, status) { if (status === "success") { console.log('true') } else { console.log('false') } } } ) }; }); The messages.json structure [ { "name": "Test", "datetime": "09.05.2021 22:05:07", "messages": "Hello" }, { "name": "Test2", "datetime": "09.05.2021 22:05:10", "messages": "Hello Help" } ] messages.json is handled by a simple view in views.py: def messages(request): messagesPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'messages.json') messagesFile = json.load(open(messagesPath)) return JsonResponse(messagesFile, safe=False) Where did I do something wrong? When the server starts, ajax, as intended, makes requests every two seconds, but every time it gets a success status, even if there was no file change. I want to make a general chat on the site, and I have already done the very adding of messages via ajax, but I also need to make sure that users receive all these messages that fall in messages.json If you help, I will be grateful. -
Trouble with pip install psycopg2
Trying to learn Django. Followed the tutorial and created my virtual environment. Now I'm trying to install psycopg2. I can install psycopg2-binary, but I've been told for "psycopg2-binary is good for development and testing but it is advised to use psycopg2 for production". So I'd like to figure this out. In my venv I'm running pip install psycopg2 it starts with this: Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) Using legacy 'setup.py install' for psycopg2, since package 'wheel' is not installed. Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error Then gives this error: ERROR: Command errored out with exit status 1: command: /Users/Me/Documents/Learn/PythonDjango/dev/project/venv/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/hf/9bs1zgkx5pj9gt84snhwrq780000gn/T/pip-install-atdy12xg/psycopg2_cd32e59009264d2bbf87b0a9def98b4e/setup.py'"'"'; __file__='"'"'/private/var/folders/hf/9bs1zgkx5pj9gt84snhwrq780000gn/T/pip-install-atdy12xg/psycopg2_cd32e59009264d2bbf87b0a9def98b4e/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/hf/9bs1zgkx5pj9gt84snhwrq780000gn/T/pip-record-30vttiiv/install-record.txt --single-version-externally-managed --compile --install-headers /Users/me/Documents/Learn/PythonDjango/dev/project/venv/include/site/python3.9/psycopg2 cwd: /private/var/folders/hf/9bs1zgkx5pj9gt84snhwrq780000gn/T/pip-install-atdy12xg/psycopg2_cd32e59009264d2bbf87b0a9def98b4e/ Then it's a long list of generated warnings. I've done some research and I've been unable to get it to work. Running Python 3.9.0 on macOS Big Sur 11.2.1