Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django more-admin-filters in Filt
I created my admin filtering with multi dropdown filter. The problem with Multidropdown filter I can choose the names that i want. How to solve this problem? models.py Tee_name = models.CharField(max_length=255, verbose_name=_("Tea Name")) admin.py list_filter = [ ("tea_name",MultiSelectDropdownFilter) ] -
compile django app to executable using PyInstaller
I am trying to compile a Django app as an executable. I know that this is not best practice - the app was built as a server app running on log in, but now the app shall be used by Users who shall not have access to the server. The challenge is now to make the app installable in such a way that the average Windows user is capable of double-clicking the exe and type in the url in a browser of their choice. I am working on Linux with Django 3.2.7, Python 3.8 and PyInstaller 4.1 (I know that I must compile on a windows platform for Windows OS to run the exe, but I first wanted to try using PyInstaller on my OS). Now, when starting the app, it complains not to find a specific folder in the dist directory, which when I add the demanded folder, changes to file not found "settings.pyc". ".pyc" files are compiled Python files, but I cannot grep the filename, so PyInstaller did not even create it. I executed the PyInstaller command in the directory where the first "mysite" is located. I also tried to separately hook the "myapp" folder by adding a … -
Variable 'html' referenced before assigned: UnboundLocalError
This code previously worked and outputed what I wanted on the website, but then this error happened from django.shortcuts import render import json def get_html_content(fplid): import requests API_KEY = "eb9f22abb3158b83c5b1b7f03c325c65" url = 'https://fantasy.premierleague.com/api/entry/{fplid}/event/30/picks/' payload = {'api_key': API_KEY, 'url': url} for _ in range(3): try: response = requests.get('http://api.scraperapi.com/', params= payload) if response.status_code in [200, 404]: break except requests.exceptions.ConnectionError: response = '' #userdata = json.loads(response.text) return response.text def home(request): if 'fplid' in request.GET: fplid = request.GET.get('fplid') html = get_html_content(fplid) return render(request, 'scrape/home.html', {'fpldata': html}) here is my views.py file. I think I assigned html before, but I'm not sure, how is it referenced before it renders. I added scraperapi for many ip addresses, as I thought maybe I was banned from the api. I am unsure what is going on. <body> <h1>Enter Your FPL id </h1> <form method="GET"> <label for="fplid"> </label> <input type="text", name="fplid", id="fplid"> <br> <input type="submit" value="Submit" /> </form> <h3> {{fpldata}}</h3> </body> This is the home.html file if it is relevant -
Django update/render bloghome page using the form filter elements
Let us say I have an HTML page (blogHome.html) with different elements like this one, <div class="container-fluid bg-light"> <div class="container"> <div class="row sm-3 justify-content-center"> <div class="col md-3 p-3 d-flex justify-content-center"> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="vegetarian" name="vegetarian" checked> <label for="vegetarian">Vegetarian</label> </div> </div> <div class="col md-3 p-3 d-flex justify-content-center"> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="nonvegetarian" name="nonvegetarian" checked> <label for="nonvegetarian">Non-Vegetarian</label> </div> </div> <div class="col md-3 p-3 d-flex justify-content-center"> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="vegan" name="vegan" checked> <label for="vegan">Vegan</label> </div> </div> </div> </div> <div class="container"> <a href="#" class="btn btn-primary" type="submit">Get Filter Values</a> </div> <div class="container my-3"> <div class="row"> {% for post in allPosts %} <div class="col-md-3"> <!-- HERE --> <div class="card mb-4 shadow-sm"> <!-- HERE --> <img class="card-img-top" src='{% static "img/tamilnadu.jpg" %}' alt="Card image cap"> <div class="card-body"> <strong class="d-inline-block mb-2 text-primary">Article by {{post.author}} ({{post.views}} views)</strong> <h3 class="card-title"><a class="text-dark" href="/blog/{{post.slug}}"></a>{{post.title}}</h3> <div class="mb-1 text-muted">{{post.timestamp}}</div> <p class="card-text mb-auto"><div class="preview">{{post.content|safe|truncatechars:200}}</div></p> </div> </div><!-- /.card --> </div><!-- /.col-md-3 --> {% if forloop.counter|divisibleby:4 %} </div> <div class="row">{% endif %} {# HERE #} {% endfor %} </div><!-- /.row --> This is how my urls.py looks like urlpatterns = [ path('', views.blogHome, name="bloghome"), ] My models.py file class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=255) author = models.CharField(max_length=25) content … -
How solve in vue model
Access to XMLHttpRequest at 'http://127.0.0.1:8000/graphene' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource -
How to get the json key and value in Django's Templating language?
I'm trying to build a website for tv series using Django framework, I put in the models.py all kinds of details about that show and a JSONField to define the number seasons and episodes in each season. Example: { "s1" : 15 , "s2" : 25 , "s3" : 23} I made a dropdown in the template where the series is playing so the user can select the episode the problem starts when I try to access the values of the keys in the JSON object passed. I tried that: {% for key in show.episodes %} Season {{key}} {% for value in show.episodes[{{key}}] %} {{ value }} {% endfor %} {% endfor %} But it this is not working, I assume that the [] thing in js doesn't work in Django's Templating language, but I cant seem to find any solution. -
I am trying to run the command 'heroku run bash' but it is giving following error ;
(trying to deploy a django project and trying to create tables and superuser) (env) D:\CRM>heroku run bash » Warning: heroku update available from 7.53.0 to 7.60.1. Running bash on ⬢ quiet-waters-22939... done Error: connect ECONNREFUSED 52.3.44.61:5000 my postgresql settings are : listen_addresses = '*' # what IP address(es) to listen on; # comma-separated list of addresses; # defaults to 'localhost'; use '*' for all # (change requires restart) port = 5432 # (change requires restart) IS the above error due to the fact that the port number in the postgresql = 5432 and the error is on port number 5000? if yes , the do i need to change the port number OR is it something else ? another similar errors : (env) D:\CRM>heroku pg:psql » Warning: heroku update available from 7.53.0 to 7.60.1. --> Connecting to postgresql-clean-14965 psql: error: connection to server at "ec2-54-157-79-121.compute-1.amazonaws.com" (54.157.79.121), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? ! psql exited with code 2 $ heroku run python manage.py migrate » Warning: heroku update available from 7.53.0 to 7.60.1. Running python manage.py migrate on ⬢ quiet-waters-22939... done Error: connect ECONNREFUSED 54.156.98.218:5000 -
502 Bad Gateway during during user Django user registration on ubuntu,ngnix
I am working on a django project,the registration view works pretty fine on development on my localhost and heruko test server.But when I switch to production using Ubuntu and Ngnix.I get a 502 bad gateway error whenever a user tries to submit the registration form.Other forms e.g the login is perfect.The only problem is the registration part on production. def registerView(request): form = UserCreationForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.is_active = False # user.set_unusable_password() user.save() current_site = get_current_site(request) mail_subject = 'Activate your account.' email_var = { 'user' : user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } to_email = form.cleaned_data.get('email') from_email = settings.DEFAULT_FROM_EMAIL html_content = render_to_string('confirm_email.html',email_var) text_content = strip_tags(html_content) msg_html = render_to_string('confirm_email.html',email_var) send_mail(mail_subject,msg_html,from_email, [to_email],html_message=msg_html) return render(request,'email_redirect.html',{}) context = { 'form':form, } return render(request,'register.html',context) class ActivateAccount(View): def get(self, request, uidb64, token, *args, **kwargs): try: uid = urlsafe_base64_decode(uidb64).decode() user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return render(request,'confirm_sucess.html',{}) else: return render(request,'confirm_error.html',{}) forms.py class UserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': ('The two password fields didn’t match.'), } password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ['firstname','email',] def clean_password2(self): … -
while connecting mysql database [closed]
System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection connection = Database.connect(**conn_params) File "C:\ProgramData\Anaconda3\lib\site-packages\MySQLdb_init_.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\MySQLdb\connections.py", line 185, in init super().init(*args, **kwargs2) MySQLdb._exceptions.ProgrammingError: (1102, "Incorrect database name 'd:\final year (5th sem)\final year project\code\final_year_project\brickcafe'") -
Start async event loop with n tasks from sync function
In my Django webapp, I have a method that emails all subscribers a notification whenever a new blog post is created. Executing this method is time-consuming, and I'm trying to make it more efficient with python's asyncio library. My motive is not just for the sake of performance, but also because my web server times out any form submissions that take longer than 300 seconds (including the form that creates new blog posts, and hence emails all subscribers). I'm assuming it's not wise to make a timeout window much longer than that, and I know that executing this method is only going to take more time the more subscriber objects I have. So, I'm thinking some sort of async solution is the way to go. Anyways, enough rambling. Here is what I've tried: # This method gets called every time a new blog post (agpost) is saved for the first time. def send_subs_new_post_email(agpost): logger.info("Setting up async emailing loop...") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(setup_async_sub_email_loop(agpost, loop)) loop.close() # Add a send_email task in the event loop for every subscriber. async def setup_async_sub_email_loop(agpost, loop): for i, sub in enumerate(Subscriber.objects.all()): domain = Site.objects.get_current().domain absolute_path = 'https://' + str(format(domain)) # Build unsubscribe link token = … -
Daphne does not running after server restart on digitalOcean
After Creating daphne.service file. I run following command. ''' sudo systemctl daemon-reload sudo systemctl start daphne.service sudo systemctl status daphne.service ''' output: is showing Active(Running) enter image description here When I run again the last command just after it is showing: failed (Result exit-code) enter image description here I also checked log of daphne.service. It says that env/bin/python : can't open file and env/bin/daphne : No such file or directory. -
Extending functionality of an external package's View in Django
I'd like to extend the functionality of a specific View in an external package that initiate SSO authentication with SAML. the package: https://github.com/zibasec/django-saml2-pro-auth I have a service that uses the package and logs in users from multiple apps, right now the sso login works but i'd like to extend specifically the SsoView - view of the package such that I could save the referrer so I know where to return to when I finish the authentication I guess it happens because I call the view from within my View and the namespace of my urls is not the same as theirs - in theirs the app_name is indeed saml2_pro_auth. Is there a better way to extend the View or solve this issue? Thanks in advance I tried to write a view in my app's views that uses the SsoView but it gives me "saml2_pro_auth is not a registered namespace" error of django when it is trying to reverse a url. The package's view class SsoView(GenericSamlView): http_method_names = ["get", "head"] def get(self, request, *args, **kwargs): # SP-SSO start request auth = kwargs["saml_auth"] req = kwargs["saml_req"] return_to = req["get_data"].get(REDIRECT_FIELD_NAME, app_settings.SAML_REDIRECT) or "/" saml_request = auth.login(return_to=return_to) response = redirect(saml_request) response.set_signed_cookie( "sp_auth", auth.get_last_request_id(), salt="saml2_pro_auth.authnrequestid", … -
Invalid Default value for entry that doesnt exist
I am looking at this example in the Django docs to add a field to my CustomUser which has just a few choices. I added this class StringInstrument(models.TextChoices): VIOLIN = 'VIO', _('Viool') ALT_VIOLIN = 'AVI', _('Alt Viool') CELLO = 'CEL', _('Cello') DOUBLE_BASS = 'CON', _('Contrabas') OTHER = 'OTH', _('Anders') working_on = models.CharField( max_length=3, choices=StringInstrument.choices, default=StringInstrument.OTHER ) which gave me the following traceback when migrating: File "...\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "...\Python39\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "...\Python39\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "...\Python39\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "...\Python39\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "...\Python39\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "...\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "...\Python39\lib\site-packages\django\db\migrations\executor.py", line 131, in migrate state = self._migrate_all_forwards( File "...\Python39\lib\site-packages\django\db\migrations\executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "...\Python39\lib\site-packages\django\db\migrations\executor.py", line 248, in apply_migration state = migration.apply(state, schema_editor) File "...\Python39\lib\site-packages\django\db\migrations\migration.py", line 131, in apply operation.database_forwards( File "...\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 108, in database_forwards schema_editor.add_field( File "...\Python39\lib\site-packages\django\db\backends\mysql\schema.py", line 105, in add_field super().add_field(model, field) File "...\Python39\lib\site-packages\django\db\backends\base\schema.py", line 641, in add_field self.execute(sql, params) File "...\Python39\lib\site-packages\django\db\backends\base\schema.py", line 192, in execute cursor.execute(sql, params) return super().execute(sql, params) File "...\Python39\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File … -
Please is there a way to make my django page pagination with with Quiz App?
my problem is on page pagination on Django quiz App when I click on the next question, its will unselect the previous selected input and only one answer will be recorded. Form Codes: <form action="/calculate_marks" onsubmit="return saveAns()" enctype="multipart/form-data" id ='quiz' method="POST"> {% csrf_token %} <input type="hidden" name="csrfmiddlewaretoken" value="C24rUotmdHawVQJL3KrqiWxvti8UffOFYUc8TRbZtLt36AVLdP3jbkzUVe3beRAa"> <h1>{{course}} Quiz</h1><br> <h4>Number of Questions in the Quiz: {{q_count}}</h4> <hr> <p>pages {{page_obj}}</p> <hr> {% for q in page_obj %} <!-- <h6 style="text-align: right;">[marks {{q.marks}}]</h6> --> {% if q.img_quiz.url %} <div class="text-center" ><img src="{{q.img_quiz.url}}" width="100%" height="300px" alt=""> </div><br> {% endif %} <div style="border: 2px dotted green;" class="container shadow-lg mb-1 bg-white rounded"> <p class="d-flex" style="overflow-x: auto; white-space: pre-wrap; font-size: 20px;font-family: sans-serif;" > {{ q.question }}</p> {% if q.marks %} <h6 style="text-align: right;">[marks {{q.marks}}]</h6> {% endif %} </div> {% if q.option1 %} <div class="card-header shadow-lg mb-1 bg-white rounded"> <input type="radio" name="{{forloop.counter}}" id="{{q.option1}}" value="Option1"> <label for="option1"> {{q.option1}}</label><br> </div> {% endif %} {% if q.option2 %} <div class="card-header shadow-lg mb-1 bg-white rounded"> <input type="radio" name="{{forloop.counter}}" id="{{q.option2}}" value="Option2"> <label for="option2">{{q.option2}}</label><br> </div> {% endif %} {% if q.option3 %} <div class="card-header shadow-lg mb-1 bg-white rounded"> <input type="radio" name="{{forloop.counter}}" id="{{q.option3}}" value="Option3"> <label for="option3">{{q.option3}}</label><br> </div> {% endif %} {% if q.option4 %} <div class="card-header shadow-lg mb-1 bg-white rounded"> <input type="radio" name="{{forloop.counter}}" … -
Search by id not primary key not working django, no data is shown
I have one model and I want to search by patientid (not a primary key) when the id match the ids in the database list all the objects related to this id. I tried many ways but it is not working not showing anything when i search can someone tell me the issue ?? def search_bar(request): if request.method=='GET': searchbox=request.GET.get['searchbox'] if searchbox: prodctuts=Item.objects.filter(Name__icontains=searchbox) return render(request,'project/showData.html',{'prodctuts':prodctuts}) else: print("No information to show") return render(request,'project/showData.html',{}) Showdata.html {% load static %} <!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 rel="stylesheet" href="{% static 'assets/css/external/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/external/normalize.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/external/all.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/showData.css' %}"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css'"> <title>Show Data</title> </head> <body> <!-- ---------------------------start navbar----------------- --> <nav class="navbar navbar-expand-lg "> <a class="navbar-brand" href="#"> <img src="{% static 'assets/images/logo/logo.png' %}" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav m-lg-auto"> <a href="#" class="close-icon d-lg-none"><i class="fas fa-times"></i></a> <li class="nav-item active"> <a class="nav-link" href="{% url 'index' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Doctor</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Register <span … -
how can I change css Request url in nginx wit django
Below is my Nginx config location /static { alias /srv/django_site/mysite/static/; } when I approach www.mysite.com/admin browser request css file 'www.mysite.com/admin/css/~.css' But when I approach www.mysite.com browser request css file like below www.mysite.com/static/styles.css so I got 404 error. I want to change this request url like this www.mysite.com/static/home/static How can I fix this? Below is my url.py and settings.py urlpatterns = [ path('', include('home.urls')), path('accounts/signup', lambda requests: redirect('')), path('activate/', lambda requests: redirect('')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ### home/url.py urlpatterns = [ path('', views.MainView.as_view(), name = 'homepage'), STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
Passing values to child class which inherits from PageNumberPagination from drf
I have to use PageNumberPagination (from drf) in many of my views, I used to define a custom class inheriting PageNumberPagination in each of my views.py, like - from rest_framework.pagination import PageNumberPagination class CustonmPageNumberPagination(PageNumberPagination): page_size = 3 page_query_param = "pageNumber" class MyViewSet(viewsets.ModelViewSet): serializer_class = MySerializer queryset = MyModel.objects.all() pagination_class = CustonmPageNumberPagination Now I'm trying to define a helper class in project level file and call this class whenever required. so my custompagination.py file is - from rest_framework.pagination import PageNumberPagination class CustomPageNumberPagination(PageNumberPagination): page_size = 3 page_query_param = "pageNumber" and then I can use it like - from backend.pagination import CustomPageNumberPagination class MyViewSet(viewsets.ModelViewSet): serializer_class = MySerializer queryset = MyModel.objects.all() pagination_class = CustonmPageNumberPagination But I also want to pass the value of page_size to my CustomPageNumberPagination whenever the class is called from my views, so as to get exact page size for each of my views. I understand class takes arguments in the init method so when I try something like class CustomPageNumberPagination(PageNumberPagination): def __init__(self, count): self.count = count page_size = 3 page_query_param = "pageNumber" and when trying to call this class pagination_class = CustomPageNumberPagination("gh") it gives an error 'CustomPageNumberPagination' object is not callable. Any help on how can I pass values? -
Django AuthenticationForm giving error "NameError: name 'UsernameField' is not defined"
I am trying to implement Login Form using AuthenticationForm , but I am getting error NameError: name 'UsernameField' is not defined, I dont understand , why it is giving this error. from django import forms from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from django.contrib.auth.models import User class CustomerRegistrationForm(UserCreationForm): password1 = forms.CharField(label="Password",widget=forms.PasswordInput(attrs={"class":"form-control"})) password2 = forms.CharField(label="Confirm Password (again)",widget=forms.PasswordInput(attrs={"class":"form-control"})) email = forms.CharField(required=True,widget=forms.EmailInput(attrs={"class":"form-control"})) class Meta: model = User fields = ["username","email","password1","password2"] labels = {"email":" Email"} widgets = {"username":forms.TextInput(attrs={"class":"form-control"})} class LoginForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField(label=("Password"),strip=False,widget=forms.PasswordInput(attrs={"autocomplete":"current-password","class":"form-control"})) -
How to redirect to main page from any url
I've set up a link using an anchor tag which is connected to a template. Now when I click on the link I am redirected to (http://127.0.0.1:8000/blogpost/TopTenBestSellinggamesof2021) in which blogpost is the template and afterwards is the slug. And then when I go to the link of the navbar of the template to home I am directed to (http://127.0.0.1:8000/blogpost/index) but I want to go to (http://127.0.0.1:8000/index) instead. *My app's urls patterns - My app's urls patterns My project's urls patterns - My project's urls patterns I'm a beginner so I don't know much please help me I'm stuck at it for 2 hours!! -
How columns are connected in posgresql and data autopopulate in between tables?
I have to tables that I created through models.py in Django models and connect it to postgresql db. I have a common columns in two table Departments(DepartmentName) and Employees (Department) and say we want to add new row to Employees table. The thing that confuses me since those two columns are DepartmentName and Department are same how can we make sure when the new recors are generated in Employees table how the records are auto populated in Departments table? "models.py" from django.db import models # Create your models here. class Departments(models.Model): DepartmentId = models.AutoField(primary_key = True) # Autoincremented department id DepartmentName = models.CharField(max_length = 500) class Employees(models.Model): EmployeeId = models.AutoField(primary_key = True) # Autoincremented department id EmployeeName = models.CharField(max_length = 500) Department = models.CharField(max_length = 500) DateofJoining = models.DateField() PhotoFileName = models.CharField(max_length = 500) After inserting new records to Employees Table in postgresql table insert into public"Employees" values (1, 'Bob', 'IT', '2021-12-12', 'anonyms.png') Departments Table in when we inserted new records to So my questions are How can we connect those two tables when new records created in one of them the other gets populated with the data ? In this case DepartmentName data in Departments table. -
Does using/calling method having calculating queryset in another method hits the database multiple times
I'm working on a DRF project to learn about ContentType models. I created a post model and comment model(ContentType) and then added comments to the post. Everything was working fine until I added django-debug-tool and duplicated queries. I have the following questions: I've defined a method(children) and property(total_replies) on the comment model. Since total_replies just calling children method and count the size of queryset. Will it result in hitting the database two or more times in case I use the children method in some other methods or property? If the database is hitting multiple times, what solution two improve performance? After adding select_related the num of queries has been reduced drastically. Before using select_related After using select_related Is it good to use select_related at all places where Foreignkey has been used? Blog app models.py class Post(models.Model): title = models.CharField(verbose_name=_("Post Title"), max_length=50) content = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title @property def comments(self): instance = self #qs = Comment.objects.filter_by_instance(instance) #before qs = Comment.objects.select_related('user').filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type serializers.py class PostSerializer(serializers.ModelSerializer): author = UserPublicSerializer(read_only=True) status_description = serializers.ReadOnlyField(source='get_status_display') class Meta: model = Post fields = ( … -
Importing files modulenotfounderror
I have looked on multiple stackoverflow post but cannot find the answer. I have the following file structure i am also doing this in a django project crypto_api_site bitvavo_api bitvavowallet.py data.py main views.py Where data.py imports bitvavowallet.py and views.py imports data.py . But when executing python manage.py runserver I keep getting the error ModuleNotFoundError: No module named 'bitvavowallet' my import in views.py looks like this sys.path.append('crypto_api_site/bitvavo_api/') from bitvavo_api import data and my import in data.py looks like this import bitvavowallet.py Thanks in advance for any help -
Celery with rabbitMq and Django delay not working
I am using celery to send mails and that the execution is not in the main thread due to the high workload of this. Although I can send mail, when I try to use shared_task the function does not execute. When I check with celery -A myApp worker -l info what I get is that the userEmail task is received but there is not an output that is executed. What seems strange to me, following the documentation of celery is that it is not necessary to add any statement in settings.py How do I tell celery to use rabbitMq? init.py from .celery import app as celery_app __all__ = ('celery_app',) celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myApp.settings') app = Celery('myApp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Then there is a file call utils.py where there is this function: from celery import shared_task @shared_task(name="userEmail") def send_user_mail(randomNumber, email): subject = 'Validation' body="Your number is: "+str(randomNumber) send_mail(subject, body ,'xxxxxx.ssmtp@gmail.com', [email],fail_silently = False) return 1 -
How to take data from html with json to django
I cant make this work i want to take some data from html in a click of the button from html with json to django i dont want to use stripe. my html file `<form id="payment-form"> Billing address Emri klientit Emaili klientit Adresa Choose... {% for address in addresses%} {{address.address_line}} {% endfor %} Zgjidh nje nga adresat ose krijo nje te tille. ` my view `def add(request): basket = Basket(request) if request.POST.get('action') == 'post': order_key = request.POST.get('order_key') user_id = request.user.id baskettotal = basket.get_total_price() # Check if order exists if Order.objects.filter(order_key=order_key).exists(): pass else: order = Order.objects.create(user_id=user_id, full_name='name', address1='add1', total_paid=baskettotal, order_key=order_key) order_id = order.pk for item in basket: OrderItem.objects.create(order_id=order_id, product=item['product'], price=item['price'], quantity=item['qty']) response = JsonResponse({'success': 'Return something'}) return response` -
How can I use paginator in search form in django
I'm trying to use paginator in my search form , everything works fine until I hit next page it shows a ValueError at /search/ views.py: def search_book(request): if request.method == "POST": searched = request.POST['searched'] # books = Book.objects.filter(title__contains=searched.upper()) paginator = Paginator(Book.objects.filter(title__contains=searched.upper()).order_by('title'),2) page = request.GET.get('page') books_list = paginator.get_page(page) return render(request,'search.html',{'searched':searched ,'books' : books_list}) else: pass form: <form class="search" action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search-box" id="search-book" type="text" placeholder="Search..." name="searched" > <input class="Search-button" type="submit" value="Search"> </form>