Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy two django app with nginx but the second app is directed on the first
I am using nginx server to realise 2 servers block. My apps is made with django and gunicorn. What happen is that the first project working well but the second link or is directed to the second like if the second server block redirect in the first. I have the same name for my django project but in 2 differents virtualenv my first conf for the first project upstream prod_app_server { server unix:/webapps/projet1/run/gunicorn.sock fail_timeout=0; } server { server_name app.exemple.com; client_max_body_size 4G; location /static/ { root /webapps/projet1/django_project; } location /media/ { root /webapps/projet1/django_project; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; if (!-f $request_filename) { proxy_pass http://prod_app_server; break; } } } my second conf for the second project upstream prod2_app_server { server unix:/webapps/projet2/run/gunicorn.sock fail_timeout=0; } server { server_name app2.exemple.com; client_max_body_size 4G; location /static/ { root /webapps/projet2/django_project; } location /media/ { root /webapps/projet2/django_project; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; if (!-f $request_filename) { proxy_pass http://prod2_app_server; break; } } } my gunicorn conf for the project 1 NAME="projet1" DJANGODIR=/webapps/projet1/django_project SOCKFILE=/webapps/projet1/run/gunicorn.sock USER=axit GROUP=webapps NUM_WORKERS=15 DJANGO_SETTINGS_MODULE=django_project.settings DJANGO_WSGI_MODULE=django_project.wsgi my gunicorn conf for the project 2 NAME="projet2" DJANGODIR=/webapps/projet2/django_project SOCKFILE=/webapps/projet2/run/gunicorn.sock USER=axit GROUP=webapps NUM_WORKERS=15 DJANGO_SETTINGS_MODULE=django_project.settings DJANGO_WSGI_MODULE=django_project.wsgi -
Django) I created superuser and made some changes from not on the Virtualenv but on the Python system
hope you are always well. I was doing some project by using django and I realized that I forgot to activate virtualenv. I already made some changes and applied it not on the venv, and created superuser on the system. Please help me how to find changes on the system that I made today and how to remove superuser that I made on the system by using cmd command. Thanks! kind regards, takudaddy -
Django. Triple Many to Many relation on two Many to Many tables with one joint field
I have 2 tables look this at the left bottom on the pic. tables picture They have 1 related field 't' on the table 'Touney'. Their second column are just for example so no matter what do they contain and i think it's even no matter if they have relations or they are common. I need to create a table where it'd be possible to connect this to second fields with each other but only from the rows with similar values of 't' field. So that's impossible to connect t1-p3 with t3-g1. To be even more clear i took a django admin screen where it's seen that i have list of all rows of players with different 't' fields so i can choice a t1 row to t2 or other. That's because i've just setup the first field as relation on the T-P table and the second on the T-G table so i can connect every their row. That's my problem. I know that i can just filter them but it looks like a not right solution and i should make some other structure -
Django REST Framework - pass extra parameter to custom actions
Hi I have a custom action in my viewset, but beyond detail=True, Im not sure how to add more arguments to the route I want to make an action to filter doctors from a certain category, the url should be something like doctor/categories/<int:category_id> but Im getting a Page not found (404) when trying to add the argument @action(detail=False, methods=['get']) def categories(self, request,*args, **kwargs): """ Get a list of doctor profiles from an specific category """ data = { 'profile' : 'doctor', } return Response(data, status=status.HTTP_200_OK) I hope you guys can help me -
Should I leave pgadmin in a container during production
I have a full stack app using vue, django, postgres, and nginx. I have pgadmin in a container along with the rest of the services. Should I live pgadmin in docker during production? -
Developing eSignature Applications
Dears, I am trying to develop a web application like docusign, Hellosign using Python n django. I don’t know where to start, how does security part of the signature works, how does the information is gathered while esignature is done ( ipaddress, location details based on ipaddress and so on). I even don’t know I am asking a logical question, apologizing for that. all your inputs will take me one step further. Kind Regards -
Can't create object inside migrations
I'm extending django.contrib.auth.User model with my model: class Farmer(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name="farmer") mob_phone = models.CharField(max_length=12) I want to create some of these Farmer instances during migrations, so i have a python-migration job, which goes after all other migrations : def create_farmers(apps, schema_editor): db_alias = schema_editor.connection.alias Farmer = apps.get_model("farmer", "Farmer") User = get_user_model() u = User.objects.using(db_alias).create(username="kek" ,password="lol") farmer = Farmer.objects.using(db_alias).create(id=1, user=u, mob_phone="1") I run this job in operations section just like all other migrations: operations = [ migrations.RunPython(create_farmers, revert_create_farmers), ] But Django is laughing in my face with ValueError: Cannot assign "<User: vlad_farmer>": "Farmer.user" must be a "User" instance. This is knocking me off, because u is definitely as User instance! -
django display pdf in cbv template from an iframe or object tag
so I have a receipt model where you can upload a copy of the receipt to a /media/ folder in my root dir. The db record retains the URL to that file in an ImageField(): Model: class Receipt(models.Model): amount = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=False) receipt_image = models.ImageField(upload_to='receipt_images/') def delete(self, *args, **kwargs): self.receipt_image.delete() super().delete(*args, **kwargs) I have a ListView: class ReceiptListView(ListView): template_name = 'receipts/list.html' model = Receipt context_object_name = 'receipts' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'View Receipts' return context I have a Template 'receipts/list.html': {% block receipts %} <ul> {% for receipt in receipts %} <li>${{receipt.amount}} {% if '.pdf' in receipt.receipt_image.url %} <object data="{{ receipt.receipt_image.url }}" type="application/pdf" width="50%" height="50%"> <p>This browser does not support PDFs. Please download the PDF to view it: <a href="{{receipt.receipt_image.url}}">Download PDF</a>.</p> </object> {% else %} <img src="{{receipt.receipt_image.url}}" alt=""> {% endif %} </li> {% endfor %} </ul> {% endblock receipts %} I have used all the difernent combos of <iframes> and <objects> and I can navigate to the pdf file from my dev environment from the browser just fine. Dev tools say: Refused to display 'http://127.0.0.1:8000/media/receipt_images/mypdf.pdf' in a frame because it set 'X-Frame-Options' to 'deny'. in settings.py I tried: X_FRAME_OPTIONS = 'SAMEORIGIN' # 'ALLOWALL' XS_SHARING_ALLOWED_METHODS … -
Accessing ModelForm queryset Object field in template
In my ModelForm, I am filtering the project_users to a certain set of all Users. How can I customize the checkboxes to show a users first_name and last_name? Currently showing their email address as the checkbox label. models.py class Project(models.Model): project_business_profile = models.ForeignKey(BusinessProfile, on_delete=models.CASCADE) project_users = models.ManyToManyField(User, related_name='project_users') ... def __str__(self): return str(self.project_name) views.py class EditProject(LoginRequiredMixin, View): login_url = '/signin' redirect_field_name = 'signin' def get(self, request, project_id): ... form = EditProjectForm(instance=project) ... forms.py class EditProjectForm(ModelForm): project_users = forms.ModelMultipleChoiceField( widget = forms.CheckboxSelectMultiple, queryset = User.objects.none() ) class Meta: model = Project fields = ['project_users'] def __init__(self, *args, **kwargs): super(EditProjectForm, self).__init__(*args, **kwargs) current_project = self.instance current_business = current_project.project_business_profile users = current_business.business_users.all() self.fields['project_users'].queryset = current_business.business_users.all() // Spits out the correct users however I need to access other user fields of User in template. Name etc template {{form.as_p}} -
Issue with Django: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
Any idea what's causing this error? I've tried commenting out each app in INSTALLED_APPS one by one to see which one isn't loading, but I get the same error no matter which one is commented out. It happens after I call django.setup(), and I'm trying to create a REST API. Traceback (most recent call last): File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/main.py", line 18, in <module> django.setup() File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/ColeHoward/PycharmProjects/Face_Recognition_App/venv/lib/python3.7/site-packages/django/apps/registry.py", line 252, in … -
how to show graph/chart in django with linear regression
I m new machine learning, I m just working on a project where I have to predict the closing price of a Stock. so I m using linear regression to predict the price. now, I want to show the graph also. What I have done so far: This function is to predict the closing stock price. def get_stock_data(name): try: if model_check(name) == False: data_path = os.getcwd()+"\\StockPrediction\\data\\HISTORICAL_DATA\\" df = pd.read_csv(data_path + name + '_data.csv') df.fillna(df.mean(), inplace=True) X = df.iloc[:, [1, 2, 3]] Y = df.iloc[:, [4]] reg = linear_model.LinearRegression() reg.fit(X,Y) y_today = reg.predict([get_nse_data(name)]) model_path = os.getcwd() + "\\StockPrediction\\data\\saved_data\\" file = model_path + name + ".pkl" joblib.dump(reg, file) return y_today[0][0] else: model_path = os.getcwd()+"\\StockPrediction\\data\\saved_data\\" file = model_path + name+".pkl" model = joblib.load(file) y_today = model.predict([get_nse_data(name)]) return y_today except: return ("Error") framework: Django. -
Charts.js + Django date on X-Axis
I do fear that similar questions have been asked in the past, however I was not able to derive a solution for my specific issue. I am sending data from a Django function to Charts.js The chart gets rendered correctly and displays with the exception of the date formatting on the X-Axis. Django Data: '''class UnitChartData(APIView): def get(self, request, format=None): material_code = request.session['material_code'] plant_code = request.session['plant_code'] qs_mat = DPoList.objects.filter(plant_code=plant_code).filter(material_code=material_code).order_by('delivery_date') unit_price_list=[] for items in qs_mat: if items.gr_received is None or items.invoiced_usd is None: unit_price = 0 unit_price_list.append(unit_price) else: unit_price=items.invoiced_usd/items.gr_received unit_price_list.append(unit_price) date_list=[] for items in qs_mat: date_list.append(items.delivery_date) labels = date_list default_items = unit_price_list data = { "labels": labels, "default": default_items, } return Response(data)''' Chart.js script '''var endpoint = '/d/api/unitchart/data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'PO#', data: defaultData, fill: false, borderColor: [ 'rgba(54, 162, 235, 1)', ], borderWidth: 2 }] }, options: { responsive: true, legend: { position: 'bottom', }, hover: { mode: 'label' }, scales: { yAxes: … -
Django function based view pagination not working😥
I am having problems with my pagination, The number of pages i put in place (5) is not working. UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: QuerySet. def post(request, category_slug): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] categories = Category.objects.all() post = Post.objects.all() tags = Tag.objects.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) posts = post.filter(category=category).order_by('-id') page = request.GET.get('page', 1) paginator = Paginator(posts, 6) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) print(users) context = { 'page_obj': users, } <nav aria-label="Page navigation example"> <ul class="pagination pagination-template d-flex justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"><a href="?page=1" class="page-link"> <i class="fa fa-angle-left" aria-hidden="true"></i><i class="fa fa-angle-left" aria-hidden="true"></i></a></li> <li class="page-item"><a href="?page={{ page_obj.previous_page_number }}" class="page-link"> <i class="fa fa-angle-left" aria-hidden="true"></i></a></li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="page-item"><a href="?page={{ num }}" class="page-link active">{{ num }}</a></li> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item"><a href="?page={{ num }}" class="page-link">{{ num }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"><a href="?page={{ page_obj.next_page_number }}" class="page-link"> <i class="fa fa-angle-right" aria-hidden="true"></i></a></li> <li class="page-item"><a href="?page={{ page_obj.paginator.num_pages }}" class="page-link"><i class="fa fa-angle-right" aria-hidden="true"></i><i class="fa fa-angle-right" aria-hidden="true"></i></a></li> {% endif %} </ul> </nav> -
Problems trying to populate sub form question fields with answers
First time poster here. I have been working on my first project for the last few months. And have spent an absorbent amount of time trying to get this one piece to work. I am able to display my configuration which has a drop down for config type. Depending on the Type selected it will display a list of "Attributes" (Questions) and I would like to have my form so that I can pick a type of config and answer the questions that pertain to that config. The part I am getting stuck on is the line in my view attrib_obj = get_object_or_404(config_attribs, id=1). This will display the first answer correctly for evey config because I hard coded it to show the answer to 1 but it will then display the first answer to every question. I am struggling on how to make this variable to be the id for every question and not just the first one. Thank you for any help. Oh and since i am new to this i am nost sure if i am saving my form correctly either. :) Visual of my Problem My Model class Configuration(models.Model): name = models.CharField(max_length=100, blank=True, null=True) config_type = models.ForeignKey('ConfigType', … -
How to send 200 ok status to facebook api in order to get around the response processing time?
Some problem here ... When I send a message it takes some time to be processed, that is, the payload generates actions that can take about 15 seconds to wait. The problem is that as the api does not receive a response within a certain time limit, it resends the message successively until it gets an ok! def post(self, request, *args, **kwargs): incoming_message = json.loads(self.request.body.decode('utf-8')) for entry in incoming_message['entry']: for message in entry['messaging']: if 'message' in message: if 'text' in message['message']: post_facebook_message(message['sender']['id'], message['message']['text']) else: post_facebook_message(message['sender']['id'], "TODO") elif 'postback' in message: if 'payload' in message['postback']: post_facebook_message(message['sender']['id'], message['postback']['payload']) else: pass return HttpResponse() When I receive a message with a payload I am collecting images from a camera for 10 seconds to send back, however this waiting time generates new messages. How can I bypass this successive reception of messages? -
Django how to assign toggle-switch/checkbox state to a variable and pass it to views.py?
There is a dark mode toggle-switch at the navbar, how can I pass it’s value views.py so it sets the template-name to page-dark.html or page-light.html according to the state of the toggle switch This is my navbar: <div class="navbar-fixed"> <nav> <div class="nav-wrapper teal lighten-1"> <a href="#!" class="brand-logo"><i class="material-icons">assignment </i>Ai-Mo Times</a> <a href="#" data-target="mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a> <ul class="right hide-on-med-and-down"> <li><a href="/">Home</a></li> <li><a href="/newsroom">Newsroom</a></li> <li><div class="switch"> <label> Off <input type="checkbox"> <span class="lever"></span> On </label> </div></li> </ul> </div> </nav> </div> How can achieve this, in case you need to know I’m using Materialize CSS Thanks from now -
How to show date to edit page from database in django?
In my update page I want to show date (OrderConfirmationDate* field ) from database which was stored before in Django. How I can do this. Help will be highly apreciated.. Screenshot is attached. Feel free to take a look . Screen shot Here is my models.py from django.db import models # Create your models here. class Customer(models.Model): customer_name = models.CharField(max_length=120) orderConfirmationDate = models.DateField(null=True) contact_number = models.CharField(max_length=15, blank=True, null=True) address = models.CharField(max_length=200, blank=True, null=True) products = models.CharField(max_length=120) references = models.CharField(max_length=120, blank=True, null=True) remarks_1 = models.CharField(max_length=120) remarks_2 = models.CharField(max_length=120) invoice_number = models.CharField(max_length=120, blank=True, null=True) bKash_Payment_digit = models.CharField(max_length=120) delivery_conformations = models.CharField(max_length=120, blank=True, null=True) notes = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return self.customer_name class Meta: ordering = ["-update"] Here is my views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from .models import Customer from django.db.models import Q from .forms import CustomerCreateForm # Create your views here. def update_customer(request, id): """ Here, update single customer id form customer table :param request: :param id: :return: """ obj = get_object_or_404(Customer, pk=id) form = CustomerCreateForm(request.POST or None, instance=obj) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Customer information successfully Update ') return redirect('customer') return render(request, 'customers/customer_form.html', {'form': form}) def delete_customer(request, id): """ Here, … -
PasswordChangeView not redirecting to PasswordChangeDoneView (or changing the password)
I am trying to use the Django authentication views. My login/logout views are working without a problem. urls.py: from django.urls import path from django.contrib.auth import views as auth_views from account import views urlpatterns = [ path('', views.dashboard, name = 'dashboard'), path('login/', auth_views.LoginView.as_view(), name = 'login'), path('logout/', auth_views.LogoutView.as_view(), name = 'logout'), path('password_change', auth_views.PasswordChangeView.as_view(), name = 'password_change'), path('password_change/done', auth_views.PasswordChangeDoneView.as_view(), name = 'password_change_done'), ] password_change_form.html: {% block body %} <h1>Change your password</h1> <p>Please use the following form to change your password:</p> <div class = 'password-change-form'> <form class="" action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" name="" value="Change"> </form> </div> {% endblock %} password_change_done.html: {% block body %} <h1>Password Changed Successfully</h1> {% endblock %} I can navigate to /password_change and see the form, but when I fill it in and submit it in I am redirected to /login (I have made sure I was already logged in) and the password does not change. Does anyone know what the issue is? -
i couldn't fix the problem createview is missing a queryset
ImproperlyConfigured at /register/ SignUpView is missing a QuerySet. Define SignUpView.model, SignUpView.queryset, or override SignUpView.get_queryset(). Request Method: GET Request URL: http://localhost:8000/register/ Django Version: 3.0.7 Exception Type: ImproperlyConfigured Exception Value: SignUpView is missing a QuerySet. Define SignUpView.model, SignUpView.queryset, or override SignUpView.get_queryset(). Exception Location: D:\ch\env\lib\site-packages\django\views\generic\detail.py in get_queryset, line 69 Python Executable: D:\ch\env\Scripts\python.exe Python Version: 3.8.3 Python Path: ['D:\ch\ch', 'D:\ch\env\Scripts\python38.zip', 'c:\users\dell\appdata\local\programs\python\python38\DLLs', 'c:\users\dell\appdata\local\programs\python\python38\lib', 'c:\users\dell\appdata\local\programs\python\python38', 'D:\ch\env', 'D:\ch\env\lib\site-packages'] Server time: Fri, 12 Jun 2020 15:12:00 +0000 views.py from django.shortcuts import render from .forms import SignUpForm from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. from django.views.generic import TemplateView, CreateView class HomeView(TemplateView): template_name = 'common/home.html' class DashboardView(LoginRequiredMixin,TemplateView): template_name = 'common/home.html' login_url = reverse_lazy('home') class SignUpView(CreateView): from_class = SignUpForm success_url = reverse_lazy('home') template_name = 'common/register.html' urls.py from django.contrib import admin from django.urls import path from apps.common.views import HomeView, SignUpView, DashboardView from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('', HomeView.as_view(), name='home'), path('register/', SignUpView.as_view(), name='register'), path('login/', auth_views.LoginView.as_view( template_name='common/login.html' ), name='login'), path('logout/', auth_views.LogoutView.as_view( next_page='home' ), name='logout'), path('dashboard/', DashboardView.as_view(), name='dashboard'), ] forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional') last_name = forms.CharField(max_length=30, required=False, help_text='Optional') email = forms.EmailField(max_length=254, help_text='Enter a valid email address') class … -
Django Admin: Restrict certain staff users to database records in their own group
I want to build the admin site in a way such that, users in a certain group will be able to perform CRUD operations - to records related to their group only. Is there a way this can be accomplished? -
UnicodeDecodeError at /blog/ 'utf8' codec can't decode byte 0x97 in position 15: invalid start byte
315 316 <div class="col"> 317 <h2 class="h3 mb-0 etheader"><a href='/cards/etnews'>Featured in The Economic Times</a></h2> 318 </div> 319 320 </div> 321 <!-- End Title --> 322 <div class="row mb-3"> 323 324 325 {% for blog in et|slice:":6" %} 326 {% if "Writing for ET" in blog.get_tags%} 327 328 329 <div class="col-sm-6 col-lg-4 mb-3 mb-sm-8"> 330 <!-- Blog Card --> 331 332 <article class="card h-100"> 333 <div class="card-img-top position-relative"> 334 <img class="card-img-top" src="{{blog.get_cover_image}}" alt="Image Description"> 335 <figure class="ie-curved-y position-absolute right-0 bottom-0 left-0 mb-n1" It says the error is in the for the blog in et line. Here I am trying to retrieve data from the MySQL database which has a '—' character instead of the usual '-' which was entered by the user. I want to convert the character into the UTF-8 format. I've tried using force_str in the models page like from django.utils.encoding import force_str ... def get_sub_heading(self): return force_str(self.sub_heading) But it still throws the same error. I am fairly new in Django so I'd request you to give me a small explanation of the solution. -
How to make used one to one relationship object disappear into django admin
I try to write a website for travel company, that we have number of hotels and each hotel have their unique room type as well as price. I create the model like this. from django.db import models class Room(models.Model): room_cat = models.CharField(max_length=100) price = models.OneToOneField('Price' ,unique=True, on_delete=models.CASCADE) class Price(models.Model): period = models.DateField(auto_now=False, auto_now_add=False) rate = models.DecimalField(max_digits=50000, decimal_places=10) class Hotel(models.Model): name = models.CharField(max_length = 150) description = models.TextField(max_length = 200) slug = models.SlugField(max_length = 50) room = models.OneToOneField(Room, primary_key=True, unique=True, on_delete=models.CASCADE) However when I create these object in my django admin, some room types and price has pointed to particular hotel, however these used objects are still in my list when I create new hotel. there are too many sub-categories and item. I need a user-friendly backend to input my data. I read the django document for one to one relationship and admin but I am too frustrated not quite understand. what should I do for this issue? Thanks so much -
How to count how may followers a user has on django
I am currently working on a follow sistem but at the time of counting how many followers a user has, the code doesnt return anything rather than the default 0. For doing this I added signals to my code but it seems that those are wrong or are not being correctly called. Also the code counts how many users the user follows but that works perfecly good. views.py def profile(request, username=None): profile, created = Profile.objects.get_or_create(user=request.user) user = User.objects.get(username=username) if username: is_following = Following.objects.filter(user=request.user, followed=user) following_obj = Following.objects.get(user=user) follower = following_obj.follower.count() following = following_obj.followed.count() args1 = { 'follower': follower, 'following': following, 'connection': is_following, } return render(request, 'profile.html', args1) def follow(request, username): main_user = request.user to_follow = User.objects.get(username=username) following = Following.objects.filter(user = main_user, followed = to_follow) is_following = True if following else False if is_following: Following.unfollow(main_user, to_follow) is_following = False else: Following.follow(main_user, to_follow) is_following = True resp = { 'following': is_following, } response = json.dumps(resp) return HttpResponse(response, content_type="application/json") models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) connection = models.CharField(max_length = 100, blank=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Following(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = models.ManyToManyField(User, … -
Bringing list_display slider of db to the top in django
I have a long list_display with a lot of members in admin.py. In the database (superuser), at the bottom of the page, there is a right/left slider to scroll between them. Can I bring this slider to the top of the table instead of bottom? -
how to ship my python app to none programmers, and without preinstalled python
i have been trying this for a long time and i couldn't find a solution, i used Docker and it didn't done the thing that i want. so my question is, How to build an app in python and ship it to none programmers, my idea is i wanna build a GUI app with PyQt5 and i wanna use Django framework and Sqlite3 and a lot other python modules, and i wanna put them all into a container that will work without any preinstalled Docker or even python, and it will work just fine and lightweight.... is this even possible?! Thanks.