Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to search for substring in array of JSON Field?
I'm using a JSONField provided by Django and I store this type of data in that field: [ { "number": 1, "text": "This text is about dogs" }, { "number": 2, "text": "Only cats in this text here" }, { "number": 3, "text": "However, this text does also contain dogs" }, ] What I'm trying to achieve is some sort of substring match - ie, if a person searches for the string "dog", the result should return something like: { "number": 1, "text": "This text is about dogs" }, { "number": 3, "text": "However, this text does also contain dogs" }, Looking at the Django docs, it seems possible to query for JSON fields, as such Model.objects.filter(field__text__contains='dogs') However, contains only works for single dictionary values, not when there is an array of dictionaries. Any tips? Either through the Django ORM or through Postgres straight up. -
How To Fix TemplateDoesNotExist at /agents/ agents/agents_list.html, leads/agent_list.html
How To Fix I Saw A Directory and everything is right but i still get same error TemplateDoesNotExist at /agents/ agents/agents_list.html, leads/agent_list.html Code class AgentListView(LoginRequiredMixin, generic.ListView): template_name = "agents/agents_list.html" def get_queryset(self): return Agent.objects.all() -
Markdown2 text rendering as a string using Python and Django
I'm working on a project that takes in a markdown page and converts it into HTML before inserting it into the correct document. This is the code I'm running Python def markdown(request, entry): pathOfFile = "entries/" + entry + ".md" return render(request, "encyclopedia/entry.html", { "html_markdown": markdown2.markdown_path(pathOfFile) }) HTML {% block body %} <div> {{ html_markdown }} </div> {% endblock %} And this is what is returning on the web page <h1>CSS</h1> <p>CSS is a language that can be used to add style to an <a href="/wiki/HTML">HTML</a> page.</p> When I inspect the source of the page the HTML is encased in quotes. Is the problem that my html_markdown variable is being read as a string? What steps can I take to get the HTML to render properly? Thanks in advance for your help! -
Getting following error when trying to use replica database: "django.db.utils.ProgrammingError: relation "vt_ecommerce_orderitem" does not exist"
When I am trying to run "OrderItem.objects.using("replica").all()" or any query on "replica" database, I am getting that error. Please help me out! When I am trying to run "OrderItem.objects.using("replica").all()" or any query on "replica" database, I am getting "*** django.db.utils.ProgrammingError: relation "vt_ecommerce_orderitem" does not exist" error. Please help me out! settings is as following: DATABASES = { "default": { "ENGINE": "django_tenants.postgresql_backend", "NAME": os.environ.get("POSTGRES_DB", "starling"), "USER": os.environ.get("POSTGRES_USER", "vesatogo"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD", "vbhv3301"), "HOST": os.environ.get("POSTGRES_HOST", "db") if VT_ENV in PROD_ENV_TAGS else "localhost", "PORT": os.environ.get("POSTGRES_PORT", 5432), "TEST": {"NAME": os.environ.get("POSTGRES_TEST_DB", "starling_test")}, }, "replica": { "ENGINE": "django_tenants.postgresql_backend", "NAME": os.environ.get("POSTGRES_DB", "starling"), "USER": os.environ.get("POSTGRES_USER", "vesatogo"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD", "vbhv3301"), "HOST": os.environ.get("POSTGRES_HOST", "db") if VT_ENV in PROD_ENV_TAGS else "localhost", "PORT": os.environ.get("POSTGRES_PORT", 5432), "TEST": {"NAME": os.environ.get("POSTGRES_TEST_DB", "starling_test")}, } } yml file is as following: version: '3' services: db: image: mdillon/postgis container_name: sl_database ports: - "5432:5432" volumes: - db_vesatogo_starling_v1:/var/lib/postgresql/data env_file: - ./config/dev.env networks: - db_network pgadmin: image: dpage/pgadmin4:4.28 container_name: sl_admin links: - db depends_on: - db environment: PGADMIN_DEFAULT_EMAIL: admin PGADMIN_DEFAULT_PASSWORD: password ports: - "80:80" networks: - db_network redis: image: redis:latest container_name: sl_redis ports: - "6379:6379" restart: always networks: - redis_network networks: db_network: driver: bridge redis_network: driver: bridge volumes: db_vesatogo_starling_v1: static: -
Django 3x built in url template tag // dynamic urls via name pattern
Hello fellow human beings, I try to build a rather simple application and I have a struggle with handling url template tags. I looked up many different sources and coded the project 3 times new I have no idea whats the problem any suggestion is a big help. thanks C:. ├───nps │ ├───templates │ └───__pycache__ └───user ├───migrations │ └───__pycache__ ├───templates │ └───user └───__pycache__ nps/urls.py from django.contrib import admin from django.urls import path,include from django.views.generic import TemplateView #include urls from user-app urlpatterns = [ path('',TemplateView.as_view(template_name='homepage.html')), path('user/',include('user.urls')), path('admin/', admin.site.urls), ] user/urls.py from django.urls import path from . import views as user_views #define names for the specific urls urlpatterns = [ path('home/',user_views.home,name='user-home'), path('login/',user_views.loginPage,name='user-login'), path('register/',user_views.registerPage,name='user-register') ] #---------------------------------------------------------------------------------------# base layout for templates user/templates/user/base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> <title>Document</title> </head> <body> {%block main%}{%endblock main%} </body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> </html> home.html with navlinks and url tags user/templates/user/home.html {%extends 'user/base.html'%} {%block main%} <ul class="nav justify-content-center"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Active</a> </li> <li class="nav-item"> <a class="nav-link" href="{%url'user-home'%}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{%url'user-login'%}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{%url'user-register'%}">Register</a> </li> </ul> {%endblock main%} #----------------------------------------------------------------------------------------# ERROR MESSAGE TemplateSyntaxError at/user/home Error during template … -
Order with id=<id> didn't have expected object=<obj_name>
Sometimes my order object doesn't have an expected foreign key object. Here is my model, that represents Paypal Order(some fields are skipped): class Order(models.Model): order_id = models.CharField(...) # naive polymorphism object1 = models.ForeignKey(...) object2 = models.ForeignKey(...) object3 = models.ForeignKey(...) The logic is following: The user can create one of the objects (object1, object2, objects3) and then he will need to pay for it. Order can have only one object assigned to it. User creates an object User creates an order instance with object id. User pays a specified amount of money in the order. System waits for an API call from PayPal (webhook). Webhook logic is following: Fetch order instance Fetch object by a sequence of ifs: if order.object1: handle_object1(order.object1) if order.object2: handle_object1(order.object2) if order.object3: handle_object1(order.object3) else: raise Exception() At this point, I can get an exception, that the expected object doesn't exist. Later when I try to fetch the expected object from DB - it is there. It's weird, because it takes some time to PayPal to make a request. The expected object must exist at this time. Also it's impossible to create an Order instance with not valid object id. -
Bad Gateway in Django Production Server
The below configuration were working fine before. I pulled my latest code for django project which was not reflecting. So I wanted to refresh it. I killed gunicorn by killall gunicorn Now it is giving bad gateway. How do I resolve it? I tried restarting nginx, uwsgi sudo systemctl restart nginx sudo service uwsgi restart Created a file called my_project in /etc/nginx/sites-enabled server { listen 80; server_name my_ip_address; # customize with your domain name location /static/ { # static files alias /home/ubuntu/static/; # ending slash is required } location /media/ { # media files, uploaded by users alias /home/ubuntu/media/; # ending slash is required } location / { proxy_pass http://127.0.0.1:8000; } } linked it using cd /etc/nginx/sites-available sudo ln -l /etc/nginx/sites-available/project_name In /home/ubuntu/conf/ created a file called gunicorn_config.py command = '/home/ubuntu/DJango/env/bin/gunicorn' pythonpath = '/home/ubuntu/DJango/my_project' bind = 'IP_address:8000' workers = 3 -
The authorization server is sending back unauthorized error no matter what
I am trying to authenticate users from another 3rd party application. The authorization server uses oauth2. All my client credentials are correct. But when implementing get a request to obtain code from the authorization server. According to the documentation of the authorization server, I should encode state to bas64. Below is my view def one_id_login(request): state = "{'method':'IDPW'}"; state = base64.b64encode(state.encode('ascii')) state = state.decode() scope = 'e_mehmon' redirect_url = 'http://127.0.0.1:8000/home/o/redirect/' return render(request, 'client/login.html', {'url': auth_one_id_url, 'state': state, 'scope': scope, 'redirect': redirect_url}) And this is HTML <body> <form name="OAuthForm" action="{{ url }}" method="get"> <input type="hidden" name="response_type" value="one_code" /> <input type="hidden" name="client_id" value={{client_id}} /> <input type="hidden" name="redirect_uri" value={{ redirect }} /> <input type="hidden" name="scope" value={{e_scope}} /> <input type="hidden" name="state" value={{ state }} /> </form> <script type="text/javascript"> document.OAuthForm.submit(); </script> </body> But always I am receiving the following error message {'error': 'unauthorized_client', 'error_description': 'Unknown Client'} -
get the values of the created object in the same view in django rest framework
How can i get values of the created object in the same view ? in the same view after creating the instance i need to send an email to the user, using the email entered by him and the code gerated randomly. Models.py def generate_activation_code(): return int(''.join([str(random.randint(0,10)) for _ in range(6)])) class Email_for_Verification(models.Model): email = models.EmailField( max_length=100, verbose_name='email', unique=True) code = models.CharField(max_length=100, default=generate_activation_code) Views.py class EmailForVerificationView(CreateAPIView): queryset = models.Email_for_Verification.objects.all() serializer_class = EmailForVerificationSerializer def create(self, request): data = request.data email_for_verification = self.create(email=data.email) send_mail( 'Here is the code of verification', email_for_verification.get['code'], 'info@ivan-online.ru', [email_for_verification.get['email']], fail_silently=True, ) i'm facing the following error: 'QueryDict' object has no attribute 'email' -
Django Web App Help! How to Add Attendance to Requested Students
I have my Django web app nearly complete but am stuck on one final component. Background of the app: teachers will be able to request students for tutoring. Once the tutoring period expires, teachers can then enter attendance for those students. What is the best way to approach this? Below are my models, views and forms. Thank you so much in advance! MODELS from django import forms from django.db import models from django.forms import ModelForm from django import forms # Create your models here. class Student(models.Model): first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) AdvisoryRoom = models.CharField(max_length=200, null=True) # def __str__(self): return self.last_name + ", " + self.first_name class Meta: ordering = ['last_name'] class AdvisoryTeacher(models.Model): first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) room_number = models.CharField(max_length=200, null=True) phone_number = models.CharField(max_length=200, null=True) def __str__(self): return self.last_name + ", " + self.first_name class Meta: ordering = ['last_name'] class Teacher(models.Model): first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) room_number = models.CharField(max_length=200, null=True) phone_number = models.CharField(max_length=200, null=True) def __str__(self): return "" + str(self.last_name) + ", " + str(self.first_name) class Meta: ordering = ['last_name'] class RequestAStudent(models.Model): MARK =( ('Present', 'Present'), ('Late', 'Late'), ('Absent', 'Absent'), ) PERIODS=( ('Academic Network 1', 'Academic Networking 1'), ('Academic Network 2', … -
django partial search issue
This sample text that needs to be searched State Model { "region": "National Capital Territory of Delhi", "country": "in" }, { "region": "Union Territory of Chandigarh", "country": "in" }, I have two models on the server, First is a country model in which user selects the country they reside in then from that state is filter and is displayed. So now if they type Chandigarh when am using they query state = loginModels.State.objects.filter(country=country_code.lower()).filter(region__icontains=state).get() It automatically selects -> Union Territory of Chandigarh BUT, Now if the user types NCT of Delhi the above query fails I tried Q method too as suggested in blogs, this also FAILS. state = loginModels.State.objects.filter(country=country_code.lower()).filter(Q(region__icontains=query)).get() P.S Note In this user stands for the system, so backend system calls like NCT and above query fails in several places we don't want to hardcode places. Any kind of help will be really appreciated. -
Django Unit Test - filtered query results in the view
I am relatively new to Django and very new to writing unit tests. I'd like to ask for assistance but I'm a bit stuck with where to even begin. The app in question allows a teacher to assign multiple assignments to a student. On the student dashboard, an assignment should only be available if the start date <= today's date. The student should only see the first assignment in the list on their dashboard. I need to compose a unit test to cover this scenario: I'd like to assign multiple assignments to a student and then use the same query that is used for the student dashboard to ensure that the only assignments returned are the ones with a start date <= today's date AND that the student only sees the first assignment (with the earliest start date) in the list. Below I have posted the relevant code that is pulling what displays on the student dashboard. Please let me know if additional code is needed to help me get started with this. Thanks very much for any help you can offer! from my home/views.py file @login_required def index(request): user_type = request.user.type.text if user_type == 'Student': """ Only return the … -
Opening a connection to an additional database specifying cursor_factory
I've defined a named database in settings.py::DATABASES, called db. I want to open a connection to that database and get a NamedTupleCursor instead of the default psycopg2 cursor. Ny naive attempt was to do: from psycopg2.extras import NamedTupleCursor db = connections["db"].connection with db.cursor(cursor_factory=NamedTupleCursor) as cursor: ... But .connection is None until I explicitly connect to the database. I can manually connect to the database, then access the underlying connection, like this: db = connections["db"] if not db.connection: db.connect() connection = db.connection with connection.cursor(cursor_factory=NamedTupleCursor) as cursor: ... But this all feels very ad-hoc and un-Djangoesque. Also, I'm not sure whether the connection will ever be closed because I haven't used a context manager. Is there an accepted way to get a connection to one of your DATABASES which will allow me to specify the cursor_factory? -
error when trying to execute python manage.py migrate
django.db.utils.OperationalError: (1046, 'No database selected') I get the above error when I try to execute: python manage.py migrate The database settings in my settings.py file are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'DATABASE': 'financeblog', 'USER': 'financeblog', 'PASSWORD': 'xxxxx', 'HOST': '127.0.0.1', 'PORT': '3308', } } I have confirmed that the database does in fact exist. The port is 3308 -
Error generating pdf from latex file in django in production
I developed a system to generate a pdf through a latex file and deployed it to a Windows server using Microsoft SII, on my local machine it generates the pdf normally, but in production it generates the following error: Command 'cd "C:\Windows\TEMP\tmpzrdfals9" && pdflatex -interaction=batchmode texput.tex' returned non-zero exit status 1. Here's the code of the view: def verFormularioDesconto(request,id): with connections['integracaoSiem'].cursor() as cursor: sql = "SELECT VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'APROVACAO'),\ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'CRM_RT') ,\ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'NM_RT'), \ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'NU_REGISTRO_EMPRESA'),\ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'RAZAO_SOCIAL'),\ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'CNPJ'), \ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'ID_SOLICITACAO'), \ VALIDA_DIREITO_DESCONTO_FUNC(%(id)s,'PRAZO') \ FROM DUAL" valores = {'id':id} cursor.execute(sql,valores) resultado = cursor.fetchall() context = { "date": datetime.now().strftime("%d/%m/%Y %H:%M:%S"), "CRM_RT": resultado[0][1], "NM_RT": resultado[0][2], "NU_REGISTRO_EMPRESA": resultado[0][3], "RAZAO_SOCIAL": resultado[0][4], "CNPJ": resultado[0][5], "ID_SOLICITACAO": str(resultado[0][6].zfill(5)), } if resultado[0][0] =='A' and resultado[0][7] == 'S': return render_to_pdf(request, "latex/formularioDesconto.tex", context,filename='Requerimento_de_desconto.pdf') else: return HttpResponseNotFound('<h1>Página não encontrada</h1>') latex code: \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{anysize} \usepackage{fancyhdr} \pagestyle{fancy} \fancyhf{} \lhead{ {{date}} } \rhead{ Nº Solicitação: {{ID_SOLICITACAO}} } \cfoot{ \thepage} \marginsize{30mm}{30mm}{20mm}{20mm} \date{} \begin{document} \section*{REQUERIMENTO DE DESCONTO DE 80\% NA ANUIDADE PESSOA JURÍDICA 2021} %\maketitle Número de registro da EMPRESA no CRMMG: {{NU_REGISTRO_EMPRESA}} \\ Número de inscrição no CNPJ: {{CNPJ}} \\ Razão Social: {{RAZAO_SOCIAL}} \vspace{1em} Eu, {{NM_RT}}, CRMMG n.º {{CRM_RT}}, Responsável Técnico do estabelecimento acima identificado, venho REQUERER junto ao Conselho Regional de Medicina do Estado de Minas Gerais, desconto … -
django postgresql cumulative sum
I am trying to make a party ledger. which details will show by a date search result. I have a column name balance which will display cumulative data by the date search. The balance field is a decimal field. I am trying the following in views.py def partyDetails(request,pk): form = DateRangeForm() search = [] until = [] cumbalance = 0.00 if request.method == 'POST': form = DateRangeForm(request.POST or None) if form.is_valid(): search = PurchasePayment.objects.filter(vendor=pk,date__range=( form.cleaned_data['start_date'], form.cleaned_data['end_date'] )) for balancet in search: cumbalance += Decimal(balancet.balance) else: return redirect('party_ledger') return render(request, 'purchase/party_details.html', {'dateform':form, 'party':search,'name':pk, 'cumbalance':cumbalance}) But I am getting error unsupported operand type(s) for += If I try cumbalance += [balancet.balance] then get [Decimal('200000.00'), Decimal('-200000.00')] MY Models.py are given bellow class PurchasePayment(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) invoice = models.CharField(max_length=20) vendor = models.CharField(max_length=50) amount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) discount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) payment = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) balance = models.DecimalField(max_digits=9, decimal_places=2) remarks = models.TextField(blank=True) extra = models.CharField(max_length=100, blank=True) def __str__(self): return self.vendor How can I make a cumulative view in balance field -
Celery is killed after running gunicorn
I have implemented all of Celery, Redis, Nginx and Django configurations. First, I am running Redis, then after I am running Celery. I can see that celery is working but when I run gunicorn, celery is being killed. I wonder what is the problem here, I have to start gunicorn so that to access Django application. -
How to get the logged in user ip and compare it with the previous ip, if the ip address is different, a message is issued (Django)
I'm quite new to the world of python and django programming, I'm developing my first app which is basically a very simple blog. I would like to know how to do what I have described in the title. I haven't created a user model but i have used settings.AUTH_USER_MODEL, a form.py for the Login and a view.py. Form.py class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password,) if not user: raise forms.ValidationError('Account does not exist') if not user.check_password(password): raise forms.ValidationError('Wrong password') if not user.is_active: raise forms.ValidationError('User disabled') return super(UserLoginForm,self).clean(*args, **kwargs) View.py def login_view(request): next = request.GET.get('login') title = 'Login' form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if next: return redirect(next) return render(request,'bloggo/homepage.html', {}) return render(request, 'bloggo/account_form.html', {'form': form, 'title': title}) Thank u all!! -
How to use the add tag in django admin templates
in django admin change_list_results.html there is a part which is responsible for the items that get registered for a model in the screen {% for item in result %} {{ item }} {% endfor %} Now I wanted to add something to the first of every item, I know if it was in pagination, I could do add:paginator.page.start_index but in this case, there is no start_index key for item, or result : {{ forloop.counter|add:item.start_index }} or {{ forloop.counter|add:result.start_index }} returns Failed lookup for key [start_index] in '<td class="action-checkbox"><input type="checkbox" name="_selected_action" value="705" class="action-select"></td>' So what should I do to add something to the listview of an item in django admin? -
How to merge two Querysets and create new queryset in django
class IndoorInventory(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) product = models.CharField(max_length=50) indoor_brand = models.CharField(max_length=100, null=True, blank=True) indoor_model_no = models.CharField(max_length=100, null=True, blank=True) indoor_sr_no = models.CharField(max_length=100, null=True, blank=True) outdoor_model_no = models.CharField(max_length=100, null=True, blank=True) class OutdoorInventory(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) product = models.CharField(max_length=50) outdoor_brand = models.CharField(max_length=100, null=True, blank=True) outdoor_model_no= models.CharField(max_length=100, null=True, blank=True) outdoor_sr_no = models.CharField(max_length=100, null=True, blank=True) indoor_model_no= models.CharField(max_length=100, null=True, blank=True) I have two models for two parts of AC, that is IndoorInventory for the indoor unit which shows all indoor unit information, and OutdoorInventory for showing outdoor unit information. I am passing a queryset of IndoorInventory to my Django template and fetching all the data there. enter image description here Now I want to get the outdoor_sr_no from OutdoorInventory models and pass it to the IndoorInventory queryset so that outdoor_sr_no value also get fetched on the table -
How to make Tags and Categories Separate in django wagtail
How to make Tags and Categories Separate... I have a tag for SCRC and a Tag for Libraries, but How can i make it so when I create a blog, and choose each different tag, the posts show up? -
Should the api return the UUID or the actual record?
I'm receiving data objects from the backend with UUIDs. example: { name: "evcs", website: "", created_by: "6c7b3ca1-8c32-4787-8286-0c0635d67444" } the UUID can be from any microservice, so from the front-end, I have to make a request to that microservice to get the name of the user who created the record. so my question is: If a data object has 7 to 8 fields with UUIDs. Should we make requests to those microservices from the front-end? or the backend should send the actual data instead of sending the UUIDs my UI is a bit slow due to making requests from the front end. users have to wait until the front end finishes with all requests. what is the right way to handle this? -
Is it possible to add to a model field from the frontend without having to invoke a url and template?
I have a Recipe models as follows: class Recipe(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE,related_name='recipe') title = models.CharField(max_length=255) subtitle = models.TextField(max_length=500) slug = models.SlugField(max_length=255) ingredients = models.TextField(blank=True, null=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='uploads/', blank=True,null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True,null=True) date_added = models.DateTimeField(auto_now_add=True) I create instances of this model via a custom form which includes all the fields. I display all my recipe models in a page called my_account by doing the following in the html page. {% for recipe in recipes %} <tr> <td><a href="{% url 'recipe_details' recipe.category.slug recipe.slug %}" class='field'>{{recipe.title}}</a></td> <td><a href="{% url 'update_recipe' recipe.slug %}" class='button is-dark'>Update</a></td> <td><a href="{% url 'delete_recipe' recipe.slug %}" class='button is-light'>Remove</a></td> My question us basically, can i achieve the following in my_accounts page, where in when the user clicks on add ingredient button, whatever the user has typed in gets added to the recipe.ingredients field for that particular recipe. Example: if the user types in '1 tbsp sugar' into the input field and clicks Add ingredient, for Black Tea, then '1 tbsp sugar' should get added to ingredients fields for my Black Tea Recipe model instance. -
How can i auto fill those bootstrap_form fields when i enter certain id then those id related data is auto filled in django
this is my model and when i enter some data it goes to database and i want to retrive that data in a form field automatically i am using bootstrap_form when i enter there id like when i enter id then name:something,address:something like this data is autofilled in form fields.Please help i am new to django. # Create your models here. user_sex = (('Male','male'),('Female','female')) This is my Student Registration model class StudentRegistration(models.Model): Id = models.ForeignKey(unique=True) StudentName = models.CharField(max_length=150) Std_Address = models.CharField(max_length=250) std_phone = models.CharField(null = False , blank = False, unique = True,max_length=150) Email = models.EmailField() faculty = models.CharField(max_length=150) parents_name = models.CharField(max_length=250) parents_phone = models.CharField(null = False , blank = False, unique = True,max_length=150) join_Date = models.DateTimeField(auto_now_add=True) Registration_No = models.IntegerField(unique = True) sex = models.CharField(default='Male',choices=user_sex,max_length=150) def __str__(self): return self.StudentName,self.Registration_No def get_absolute_url(self): return reverse('registration:stdlist') def save(self,*args,**Kwargs): return super().save(*args,**Kwargs) This is my Staff registration Detail class StaffRegistration(models.Model): Id = models.ForeignKey(unique=True) Name = models.CharField(max_length=250) Address = models.CharField(max_length=250) Email = models.EmailField() phone = models.CharField(null = False,blank = False,unique = True,max_length=150) Join_Date = models.DateTimeField(auto_now_add=True) sex = models.CharField(default='Male',choices=user_sex,max_length=150) def __str__(self): return self.Name,self.Address def get_absolute_url(self): return reverse("registration:stafflist") def save(self,*args,**Kwargs): self.slug = slugify(self.Name) return super().save(*args,**Kwargs) -
Issue when I want to send a request to an url with middleware applied even when I'm logged in, in Django
I have a Django project include rest API. since i have added middleware in my project i cant access my api through requests modules although i am logged in. but it is possible to access while i type the address in url. middlewares.py from django.http import HttpResponseRedirect from django.contrib import messages LOGIN_EXEMPT_URLS = [ '/api/', ] class LoginMiddleWare: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.user.is_authenticated and request.path not in LOGIN_EXEMPT_URLS: messages.error(request, 'You should login first!', 'warning') return HttpResponseRedirect('/api/') response = self.get_response(request) return response settings.py 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', 'djangoProject_app.middlewares.LoginMiddleWare', ]