Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Relation does not exist" after delete migration files
Can you please explain, why I get some issue after deleting migration files from database and in local? If the relation does not exist, how can I create this relation? I have active ForeignKey, but uncommented and commented the field and trying makemigrations, migrate, migrate --fake didn't work for me anyway. -
Django-axes Errors: 'Settings' object has no attribute . .
I've run into a lot of attribute errors when using django-axes. Whenever I fix one of them by setting the default attributes, more start showing up. I followed the documentation for installation. Here is my code... settings.py """ Django settings for ChatTest project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! if('SECRET_KEY' in os.environ): SECRET_KEY = os.environ["SECRET_KEY"] if('SECRET_KEY' not in os.environ): SECRET_KEY = 'o1(-!s0um*rj47xv8vk@)pdq3)2c1o-et!v!rnqq3p4m(9592k' #Secret key I use for local development DEBUG = True ALLOWED_HOSTS = ['.railway.app','localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'Chat.apps.ChatConfig', 'django_cleanup.apps.CleanupConfig', 'axes', ] 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', 'axes.middleware.AxesMiddleware', ] X_FRAME_OPTIONS = 'DENY' ROOT_URLCONF = 'ChatTest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = … -
Showing data on frontend from sql databases using django
For fetching data from databases, I usually see people create a class in models.py and they migrate it, and then they fetch data from databases and show it on the front-end. my question is, i already have a database which has student_info table and has lots of data. I don't want to define student_info class in models.py and do migration. Instead, since i already have student_info data in sql database. so I want to fetch it directly. can i do so? one method i know of doing the same, is directly connecting sql server in views.py as; mydb=mysql.connector.connect(host="localhost",user="root",password="******",database=database_name) and fetching the data and passing it as variable in index.html. But the problem is, it fetches data only once, and if i refresh the page where local server is running, all the content will disappear, and server will report Broken pipe from ('127.0.0.1', 59579) and to see the data, again i need to restart the sever. Kindly looking for a better approach to show data on front-end from the existing databases -
how to get messages (data) in real time from database using ajax and django
i want to get messages in realtime using ajax and django for the backend, i have written the logic to send the messages and that is working, but i want to get a message immediately another user sends me a message without having to refresh the page, i tried using ajax interval but it seem i am not getting a hang of how to properly use the interval and forloop in ajax, what is it that i should do to achive the result i want? directs.html <div class="chat-wrapper"> {% for direct in directs %} {% if direct.sender == request.user %} <div class="chat-message-right pb-2"> <div> <a href=""><img src="{{ direct.sender.profile.image.url }}" class="rounded-circle mr-1" alt="img" width="40" height="40" /></a> <div class="text-muted small text-nowrap mt-2" style="font-size: 10px; color: rgba(180, 180, 180, 0);"><p style="font-size: 10px; color: black;">{{direct.date|timesince}} ago</p></div> </div> <div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3"> <!-- <div class="font-weight-bold mb-1">Sharon Lessman</div> --> {{direct.body}} </div> </div> {% else %} <div class="chat-message-left pb-2"> <div> <a href=""><img src="{{ direct.sender.profile.image.url }}" class="rounded-circle mr-1" alt="img" width="40" height="40" /></a> <div class="text-muted small text-nowrap mt-2" style="font-size: 10px; color: rgba(180, 180, 180, 0);"><p style="font-size: 10px; color: black;">{{direct.date|timesince}} ago</p></div> </div> <div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3"> <!-- <div class="font-weight-bold mb-1">Sharon Lessman</div> --> {{direct.body}} </div> … -
Making a json structure with nested serializers concept
I'm trying to make an api with Django Rest Framework , the api format looks like this, I'm new to nested serializer concept so I've tried to make relational models and nested serializer that is available in the documentation but it doesn't work for me , is there anyone who can help ? { "devices": { "device": [{ "type": "MP", "time": "18/05/2022, 15:15:10", "MP_name": "MP1", "SN": "EMSMP001", "plant_name": "Greenaftech", "gatway_name": "gw1", "adress": 1, "baud_rate": 9600, "voltage": 230, "current": 10, "active_power": 2.3, "reactive_power": 0.01, "apparent_power": 2.3, "FP": 0.99, "frequency": 49.98 }, { "type": "TP", "time": "18/05/2022, 15:15:10", "TP_name": "TP1", "SN": "EMSMP002", "plant_name":"Greenaftech", "gatway_name":"gw1", "adress": 12, "baud_rate":1, "UA":1, "UB":1, "UC":1, "UAB":1, "UBC":1, "UAC":1, "IA":1, "IB":20, "IC":43, "frequency":11, "Pa":88, "Pb":30, "Pc":23, "Pt":42, "Qa":21, "Qb":31, "Qc":49, "Qt":82, "Sa":63, "Sb":83, "Sc":10, "St":39, "FPa":54, "FPb":43, "FPc":34, "FPt":87, "THDV":56, "THDI":74, "max_demand":2, "count_E":8, "count_Er":55 }, { "type": "VFD", "time": "18/05/2022, 15:15:10", "vfd_name": "VFD1", "SN": "EMSMP002", "plant_name":"plant1", "gatway_name":"gw3", "adress": 7, "baud_rate":1, "c00":8, "c01":8, "c02":8, "c03":8, "c04":8, "c06":8, "c07":8, "c12":8, "c13":8, "c14":8, "c15":8, "c16":8, "c17":8, "c18":8, "c19":8, "c20":8, "c21":8, "c23":8, "c24":8, "c25":8, "c27":8 }, { "type": "MP", "time": "18/05/2022, 15:15:15", "MP_name": "MP2", "SN": "EMSMP001", "plant_name": "plant1", "gatway_name": "gw3", "adress": 1, "baud_rate": 9600, "voltage": 230, "current": 10, "active_power": 2.3, "reactive_power": 0.01, … -
Django urls + React Route
i have the next djnago urls.py: urlpatterns = [ path('register',views.registerPage, name="register"), path('login',views.loginPage, name="login"), path('logout',views.logoutUser, name="logout"), path('',views.index), path('createcompany',views.index), # path('',views.index, name='home'), path('test',views.index, name='test'), path('admin',views.administrare_view,name='admin'), ] and React route: <Router> <Drawer /> <Routes> <Route path="/" element={<Home />}/> <Route path="/createcompany" element={<RegisterPage />}/> <Route path="/login" element={<LoginPage />}/> <Route path="/test" element={<TestPage />}/> <Route path="/admin" element={<AdminPage />}/> </Routes> </Router> When i press the logout button it chnage the link to /logout but dosen't logout the user. If i type manually the link or i refresh the page the user is gonna to logout. The menu dynamically created from React const menuList=[ { id:1, text:"Profile", icon:<PersonIcon sx={{ color: 'gray' }} />, link:'/profile', }, { id:2, text:'Logout', icon:<LogoutIcon sx={{ color: 'gray' }} />, link:'/logout', }, ] <Tooltip title='Profile' placement='bottom' arrow enterDelay={500}> <IconButton onClick={userAvatar_Click} size="small" sx={{ ml: 2 }} aria-controls={open ? 'account-menu' : undefined} aria-haspopup="true" aria-expanded={open ? 'true' : undefined} > <Avatar sx={{ width: 32, height: 32 }}>M</Avatar> </IconButton> </Tooltip> <Menu anchorEl={anchorEl} id='account-menu' open={open} onClose={userAvatar_Close} onClick={userAvatar_Close} PaperProps={{ elevation: 0, sx: { overflow: 'visible', filter: 'drop-shadow(0px 2px 8px rgba(0,0,0,0.32))', mt: 1.5, '& .MuiAvatar-root': { width: 32, height: 32, ml: -0.5, mr: 1, }, '&:before': { content: '""', display: 'block', position: 'absolute', top: 0, right: 14, width: 10, height: 10, bgcolor: … -
How to extract profile_pic of a user when they are signing in from Google
I'm making a django website, I have 2 login methods. One is the default email password login and another is by logging in from Google. What I want is when the user logs in from google django should automatically fetch the profile_pic of that user and save it in my user model. Here's my models.py for accounts app from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, Group # Custom User Manager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name=None, **extra_fields): if (not email): raise ValueError("Email Must Be Provided") if (not password): raise ValueError("Password is not Provided") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, first_name, last_name, **extra_fields) def create_user_with_groups(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', False) user = self._create_user(email, password, first_name, last_name) group = Group.objects.get(name='Content Writer') user.groups.add(group) print(user.groups) return user def create_superuser(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, first_name, last_name, **extra_fields) # Custom user Model class … -
django nonrelated inlines with more models
Django nonrelated inlines with more models I have more than one model not related to each other I want in admin panel to fill these models together in one form this package is help https://pypi.org/project/django-nonrelated-inlines/ but I need an example for that !! -
Django/Vue -> Heroku: Static files not loading at production server
Static files load when DEBUG=True (locally and at the dev server), but not when DEBUG=False (production). STATICFILES_DIRS is set to my dist dir created by Vue, and dist is not in the .gitignore. Heroku runs collectstatic on every deploy by default (I have not changed this). The actual error is a 404 when trying to load any static file. The whitenoise package is being used. I've updated the middleware settings, and wsgi.py according to the docs, and have the settings variable which enables compression via whitenoise set (also according to the whitenoise docs). whitenoise usually works fine with other apps. I'm not sure what's wrong with this. The difference is that I'm using Vue for the first time. I'd never used a js framework before. Can anyone help? -
Is there a way or a tool which can help to map a line in server side script to its corresponding generated line in html page?
Which tool can be I used to determine which line in server side script has generated which line of code in html page in dynamic web application. for example in django application can we know which line of code in the django-template has generate which line of code in the corresponding html page -
how to extract data from an html form using django?
So guys i have a normal html form with some text input for a user registration, the form is like this: <form id="signup-form" action="#" method="post"> <label for="name">Full Name</label> <input autocomplete="off" type="text" name="username" id="name" class="name"> <label for="email">Email Adderss</label> <input autocomplete="off" type="email" name="emailAdress" id="email" class="email"> <label for="phone">Phone Number - <small>Optional</small></label> <input autocomplete="off" type="text" name="phone" id="phone"> <label for="password">Password</label> <input autocomplete="off" type="password" name="password" id="password" class="pass"> <label for="passwordCon">Confirm Password</label> <input type="password" name="passwordCon" id="passwordCon" class="passConfirm"> <input type="submit" form="signup-form" value="Signup Now" id="submit"> </form> and i wanna know how can i store the values of each input when the button is submitted and save them in the database, is there a way to call the input field by its ID and store it in Django? -
Pass HTML for value to django view (for querying database models)
I have a form input inside my HTML page and want the figure ID that is entered inside the form to be passed into my django view to do a query, displaying info for the figure with the matching ID. My form: <form metohd="GET" id="figure_choice_form"> <label for="figure_id">Enter ID</label> <input type="text" id="figure_id" name="figure_id"> <button> Submit </button> </form> My views.py def from_DB(request): #request being the ID entered from the form figures_list = Figure.objects.filter(id=request) context = {"figures_list":figures_list} return render(request,"app1/data_from_DB.html",context) -
How can I pass the post's id through the client during testing in Django?
def test_sharing_post_through_email(self): form = {'name': 'Martin', 'email': 'exampel.example@gmail.com', 'to': 'Martinals@gmail.com'} response = self.client.post('/<int:id>/share/', data={'post': self.post, 'form': form}) response.user = self.user self.assertEqual(response.status_code, 200) self.assertIsInstance(response.context, dict) self.assertEqual(response.context['sent'], True) how can I pass the ID to the url there? -
How to make AlpineJS "re-render" component after HTMX swap
I'm trying to integrate Django + AlpineJS + HTMX. All is going well, except when I try to swap some HTML that is already a part of a AlpineJS component. If I swap the html the component renders correctly only after the second swap. template <div id="cart-row" x-data="{selectedOrderItem: {{item_id|default:'null'}} }"> <div id="cart-holder"> <table id="cart"> <thead> <tr> <th style="width: 10%">CANT</th> <th>Product</th> <th style="width: 15%">TOTAL</th> </tr> </thead> <tbody> {% for item in items %} <tr id="product{{item.product.id}}" :class="{ selectedOrderItem: selectedOrderItem == {{item.id}} }" @click="selectedOrderItem = {{item.id}};" > <td>{{item.quantity}}</td> <td>{{item.product.name}}</td> <td>{{item.get_price}}</td> </tr> {% endfor %} </tbody> </table> </div> <div id="right-menu"> <div id="table-buttons" hx-swap-obb="true"> {% for item in items %} <div class="" x-cloak x-show="selectedOrderItem == {{item.id}}"> <button class="addButton" hx-trigger="click" hx-target="#cart-row" hx-swap="outerHTML" hx-post="{% url 'add_to_cart' idOrder=order.id idProduct=item.product.id %}?cartAction=1" > + {{item.id}} </button> </div> {% endfor %} </div> </div> For example, if I hit the add to cart button, the #cart-row div is swapped, but the :class="{ selectedOrderItem: selectedOrderItem == {{item.id}} }" binding only works the second time. It's like AlpineJS doesn't realize that the content has been swapped. Is there any way that I can make the whole component "re-render / re-initialize"? Or what is the right way to do that swap? -
Django file uploads not working; Getting 404 error when trying to retrieve them. Page not found (404) does not exist
I made a custom user model that users can get to upload their profile pics and documents. I made the view to update these details and insert them into the database. However, when I try to retrieve the file I get a 404. They were never uploaded in the first place, even though the file field has been populated with the name and path. Funny thing is that when I use the admin site; i.e. 127.0.0.1:800/admin, everything works correctly. What I'm I doing wrong? I'm losing my mind here. The entire code base is at my GitHub The full error message is: Page not found (404) “C:\Users\Bosire Allan\PycharmProjects\eric\media\6244238d0f84e.png” does not exist Request Method: GET Request URL: http://127.0.0.1:8000/media/6244238d0f84e.png Raised by: django.views.static.serve I have configured my MEDIA_ROOT and urls.py settings correctly, I think. from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls, name='admin'), path('', include('application.urls')), path('', include('django.contrib.auth.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My settings.py STATIC_URL = 'static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] My models.py class User_data(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) dob = models.DateField(blank=True, null=True) city = models.CharField(max_length=20, blank=True, null=True) highQ = models.CharField(max_length=20, choices=EDUCATION, … -
How to start and stop stream in which uses nginx rtmp and Django
I am an absolute beginner with NGINX and RTMP module. I am working on a project which involves a live streaming app. I want to link this Nginx rtmp server to my django server which runs on port 8000. This is what I made up my nginx.conf file after going through multiple tutorials. What I understood from following the tutorials is that application is endpoint in rtmp so i put the url next to it, also I understand that hls video will be stored in the folder path that I provide along push/hls_path.I have a doubts now, do I need to define two applications(as it done) for start stream and stop stream or they can be clubbed together into one application. Please clarify my doubts and correct me. Thank You! Nginx configuration for RTMP upstream and HLS downstream worker_processes auto; events { worker_connections 1024; } # RTMP configuration rtmp { server { listen 1935; # Listen on standard RTMP port chunk_size 4000; application rtmp://localhost/api/livevideostreams/startstream { # Live status live on; # Turn on HLS hls on; hls_fragment 3; hls_playlist_length 60; # disable consuming the stream from nginx as rtmp deny play all; # Push the stream to the local HLS … -
{% for projects in profile.project_set.all %} is not displaying anything
I have been learning django through a video course and in the video course the guys has used {% for projectss in profile.project_set.all %} {{ projectss.title }} {% endfor %} To display List of projects Here is my Model.js file of project model class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) id = models.UUIDField(default = uuid.uuid4 , primary_key=True, unique=True, editable=False) And Here is my Model.js of Users model class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False, unique=True) The guy in video is doing the same thing its working for him but not me. -
Application Error while deploying django website please help me to get this issue resolve
2022-06-25T12:44:34.000000+00:00 app[api]: Build started by user mohammedvaraliya2661392@gmail.com 2022-06-25T12:45:01.176068+00:00 app[api]: Deploy 6cc5ee0c by user mohammedvaraliya2661392@gmail.com 2022-06-25T12:45:01.176068+00:00 app[api]: Release v13 created by user mohammedvaraliya2661392@gmail.com 2022-06-25T12:45:11.000000+00:00 app[api]: Build succeeded 2022-06-25T12:45:17.901599+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=textutilssystem.herokuapp.com request_id=a3bdba23-2b85-4c0d-91d8-0477bc1b3c2f fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:45:18.769362+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=textutilssystem.herokuapp.com request_id=7ffe54ce-071f-4f63-9d44-7b507a47c08d fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:48:55.291051+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=textutilssystem.herokuapp.com request_id=f18e05e7-9e02-497a-9179-a7eb94129a4d fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:48:56.133916+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=textutilssystem.herokuapp.com request_id=5882a3a1-f662-40a4-be6e-5cfea3786bc4 fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:49:10.243644+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=textutilssystem.herokuapp.com request_id=39f5b3c5-1811-4a32-824a-591a9faa4b0b fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https 2022-06-25T12:49:11.446623+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=textutilssystem.herokuapp.com request_id=bc10901a-cdcf-470f-b7d1-3944646dc935 fwd="103.56.227.229" dyno= connect= service= status=503 bytes= protocol=https -
IntegrityError at /signup UNIQUE constraint failed: auth_user.username ---> In django
When I click on sign in button I get integrity error!! I have checked in my admin site and all users are properly visible which i had signed up . But when I click sign in button with entries already registered in admin , my code crashes and gives integrity error!! This is my views.py from django.http import HttpResponse from django.shortcuts import redirect, render , HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate , login # Create your views here. def home(request): return render(request,"authentication/index.html") def signup(request): if request.method=="POST": username=request.POST.get('username') fname=request.POST.get('fname') lname=request.POST.get('lname') email=request.POST.get('email') pass1=request.POST.get('pass1') pass2=request.POST.get('pass2') myuser=User.objects.create_user(username,email,pass1) #creating user myuser.first_name=fname myuser.last_name=lname myuser.save() messages.success(request,"Your account has been successfuly created") return redirect('/signin') return render(request,"authentication/signup.html") def signin(request): if request.method=='POST': username=request.POST.get('username') pass1=request.POST.get('pass1') user=authenticate(username=username,password=pass1) if user is not None: login(request,user) return render(request,"authentication/index.html") else: messages.error(request,"Bad credentials") redirect('home') return render(request,"authentication/signin.html") def signout(request): pass -
Problem with passing kwargs in django rest
I have created simple endpoint about user detail with default_lookup = pk and, if pk == 9_999_999_999 I wish to return user that is already logged in. My problem i assume is with kwargs, am i doing something wrong? class UserDetailView(generics.RetrieveUpdateDestroyAPIView): serializer_class = UserSerializer queryset = User.objects.all() def get(self,*args,**kwargs): pk = kwargs.get('pk') print(kwargs) print(f"pk {pk}") if pk == 9999999999: kwargs['pk'] = self.request.user.id print(kwargs) return self.retrieve(self,*args,**kwargs) and output: {'pk': 9999999999} pk 9999999999 {'pk': 13} Not Found: /api/users/9999999999 -
Adding Plus minus button in form with POST and scrf_tocken
With Django I generate a list of items, with the number of them. To be more convenient, I would like to add a plus and a minus button. I found a simple solution, but when I try to put this in my form with the POST method, if click the page refresh or POST ? I don't want to refresh the page every time, I have a validate button and all the value will be treat in one time. <form class"form-inline" action="{% url 'stock:stock' %}"method="post" >{% csrf_token %} {% for stock in stocks %} <div> <button id="minusButton">-</button> <input type="number" name="stock" id="stock" value="{{stock.stock}}" > <button id="plusButton">+</button> </div> {% endfor %} </form> <script> textInput = document.querySelector('#numberInput'); plusButton = document.querySelector('#plusButton'); minusButton = document.querySelector('#minusButton'); plusButton.onclick = () => textInput.value = parseInt(textInput.value) + 1; minusButton.onclick = () => textInput.value = parseInt(textInput.value) - 1; </script> If anyone know how to manage? -
How to serve media files correctly in django subdomains (using django-hosts) in development?
I have this model Blog and using it in 'blog' subdomain created with 'django-hosts'. My subdomains in 'hosts.py': from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'blog', 'blog.urls', name='blog'), host(r'(|www)', settings.ROOT_URLCONF, name='www'), ) And Blog model - Note that 'title_image' field powered by 'sorl.thumbnail' and 'content' field is a 'django-ckeditor' uploadable field: class Blog(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('author'), on_delete=models.CASCADE, related_name='blog_author') title = models.CharField(verbose_name=_('title'), max_length=200) title_image = ImageField(verbose_name=_('title image'), blank=True) content = RichTextUploadingField(verbose_name=_('content')) I've' created a simple ListView for blog that show every blog title, content and title_image to viewer: class BlogListView(ListView): """Everyone can see all blogs""" template_name = 'blog/templates/blog/blog_list_view.html' model = Blog context_object_name = 'blogs' And my blog.urls: from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.BlogListView.as_view(), name='blog_list_view'), ] When I'm using my blog subdomain (eg: blog.localhost:8000/) it doesn't show any image to me whether it's the title_image or any image in django-ckeditor powered 'content' field. But when I'm not using subdomain and instead use 'blog' app as other 'URLCONF' path (eg: localhost:8000/blog/) I can see every images without any problem. Anyone knows why using subdomains, media files does not shown and how to fix it? -
Couldn't to rollback migrations: Value Error
I have tryed to roll back, cause have some migration conflicts, but it wrotes me: ValueError: The field accounts.Ninja.id_team was declared with a lazy reference to 'mission.team', but app 'mission' doesn't provide model 'team'. Trying python manage.py migrate accounts 0052. [X] 0050_goal_id_ninja [X] 0051_ninja_id_user [X] 0052_alter_ninja_id_user [ ] 0053_alter_ninja_id_user [ ] 0054_remove_ninja_id_team [ ] 0055_remove_ninja_id_user [ ] 0056_remove_goal_id_ninja [ ] 0057_ninja_id_user [ ] 0058_remove_ninja_id_user [ ] 0059_ninja_id_team_ninja_id_user [ ] 0060_remove_ninja_id_user [ ] 0061_delete_ninja [ ] 0062_ninja [ ] 0063_delete_ninja [ ] 0064_ninja [ ] 0065_ninja_id_team_ninja_id_user [ ] 0066_remove_ninja_id_team [ ] 0067_ninja_id_team [ ] 0068_remove_ninja_id_team [ ] 0069_ninja_id_team Note. I have the model Team in mission app. -
Django: User matching query does not exist in django
i wrote a function to send message using django and ajax, when i submit the message form it shows this error User matching query does not exist., i have tried getting the user in ajax like this: <input type="hidden" name="to_user" id="to_user" value="{{active_direct}}"> <script type="text/javascript"> $(document).on('submit', '#chat-form', function (e) { e.preventDefault(); let _to_user = $("#to_user").attr("name") $.ajax({ //some code here }) </script> but it keeps showing the same error when i submit the form, i have already written the server side with django but i think there is something i am not getting right. views.py @login_required def Directs(request, username): user = request.user messages = Message.get_message(user=user) active_direct = username directs = Message.objects.filter(user=user, reciepient__username=username) directs.update(is_read=True) for message in messages: if message['user'].username == username: message['unread'] = 0 context = { 'directs': directs, 'messages': messages, 'active_direct': active_direct, } return render(request, 'directs/direct.html', context) def SendDirect(request): if request.method == "POST": from_user = request.user to_user_username = request.POST['to_user'] body = request.POST['body'] to_user = User.objects.get(username=to_user_username) Message.sender_message(from_user, to_user, body) # return redirect('message') success = "Message Sent." return HttpResponse(success) directs.html <form id="chat-form"> {% csrf_token %} <div class="input-group"> <input type="hidden" name="to_user" id="to_user" value="{{active_direct}}" /> <input name="body" id="body" type="text" class="form-control" placeholder="Type your message" /> <button class="btn btn-primary" type="submit">Send</button> </div> </form> <script type="text/javascript"> $(document).on("submit", "#chat-form", function … -
Django ElasticSearch rest framework suggestion duplicate result
I am writing a API which will auto-suggest when I a type something but it is working, it is returning the results without query and even sometime duplicate value. This is is my API views: from django_elasticsearch_dsl_drf.filter_backends import ( SuggesterFilterBackend ) from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet from django_elasticsearch_dsl_drf.constants import ( SUGGESTER_COMPLETION, ) from users.paginations import LotPagination class SuggestionsAPIView(DocumentViewSet): document = ProductDocument serializer_class = ProdcutTitleSerializer filter_backends = [ SuggesterFilterBackend, ] suggester_fields = { 'title': { 'field': 'title', 'suggesters': [ SUGGESTER_COMPLETION, ], 'options': { 'size': 20, 'skip_duplicates':True, }, }, } and when I make API request, I pass parameter like this: http://127.0.0.1:8000/search/product/?title=Ar In my database, there are lots of duplicate title but when it return the search results in suggestion, it should not show the duplicate title. Can anyone please help me in this case? Why is it not working? or should I do it another way?