Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model formset - data for first nested child form missing in post method
I am using Django 3.2 and crispy-forms 1.11.2 I have a model and form defined like this: /path/to/myapp/models.py class Foo(models.Model): pass class FooChild(models.Model): parent = models.ForeignKey(Foo, on_delete=models.CASCADE) title = models.CharField(max_length=16) /path/to/myapp/forms.py class FooChildForm(ModelForm): class Meta: model = FooChild fields = "__all__" class FooChildFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = 'post' self.layout = Layout( 'title', ) self.render_required_fields = True /path/to/myapp/views.py class FooCreateView(CreateView): model = Foo def __init__(self, **kwargs): super().__init__(**kwargs) self.choice_formset = inlineformset_factory(Foo, Child, form=FooChild, extra=9) def get(self, request, *args, **kwargs): form = self.form_class() p = self.model() formset = self.choice_formset(instance=p) helper = ChildFormSetHelper() helper.template = 'bootstrap/table_inline_formset.html' helper.form_tag = False return render(request, 'myapp/create.html', {'form' : form, 'formset': formset, 'helper': helper}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST or None) if form.is_valid(): new_foo = form.save(commit=False) new_foo.creator = request.user new_foo.save() formset = self.choice_formset(request.POST or None, instance=new_foo) formset.save() # <- formset loses first element # request.POST.get('choices-0-title') # 'Choice Two' <- (expected 'Choice One') # request.POST.get('choices-1-title') # 'Choice Three' # request.POST.get('choices-2-title') # 'Choice Four' # request.POST.get('choices-3-title') # 'Choice Five' /path/to/myapp/templates/myapp/create.html {% block content %} <div class="container-lg"> <form id="frm-foo-create" method="post"> {% csrf_token %} <div class="row" style="margin: 30px 0px;"> <div class="col-lg-12"> <h2>Create a New Foo</h2> <br /> {% crispy form %} {{ form|as_crispy_errors }} {% crispy … -
why my dropdown menu not working on some page
I tried to learn django a few day ago and make a simple website use that, but for a reason my dropdown in home page didn't work but in another page it's work properly. Here my html template for that <div class="dropdown-menu"> {% for category in links %} <a class="dropdown-item" href="{{ category.get_url }}">{{category.category_name}}</a> {% endfor %} </div> and here my code for django urls.py urlpatterns = [ path('', views.store, name='store'), path('<slug:category_slug>/', views.store, name='product_by_category'), ] and here my code for links references def menu_links(request): links = Category.objects.all() return dict(links = links) i don't know why in my home page the dropdown button didn't work but in another page it work. i tried to find on my navbar templates and i think there is no problem there but the dropdown still not working and i tried to find on settings.py(to check installation app) but i did it anyone have idea where the problem is? -
How to hide nested object's name in Django Rest Framework serializer?
I have two models: Company and ContactCompany Company model is a base model and ContactCompany has some specific fields. They are connected via a foreign key. There are two serializers CompanySerializer and ContactCompanySerializer. Models: class Company(CoreModel): name = models.CharField( max_length=128, verbose_name=_("Company Name"), unique=True, ) address = models.TextField(null=True, blank=True, verbose_name=_("Address")) sector = models.ForeignKey( "contact.Sector", on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_("Sector"), related_name="companies", ) city = models.ForeignKey( City, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_("City"), related_name="companies", ) class ContactCompany(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="contact_companies", null=True, blank=True, ) note = models.TextField(null=True, blank=True, verbose_name=_("Note")) website = models.CharField( null=True, blank=True, max_length=128, verbose_name=_("Website") ) Serializers: class ContactCompanySerializer(serializers.ModelSerializer): company = CompanySerializer() integration_requirements = serializers.ListSerializer( child=serializers.CharField(), required=False, ) statuses = StatusSerializer(many=True, read_only=True) current_status = StatusSerializer(required=False) contact_people = ContactPersonSerializer(many=True, read_only=True) responsible_company = serializers.CharField( source="responsible_company.name", read_only=True ) class Meta: model = ContactCompany fields = ( "id", "company", "website", "responsible_company", "note", "integration_requirements", "current_status", "statuses", "contact_people", ) class CompanySerializer(serializers.Serializer): name = serializers.CharField() is_active = serializers.BooleanField(required=False) city = serializers.CharField(source="city.name", required=False, allow_null=True) country = serializers.CharField( source="city.country.name", required=False, allow_null=True ) sector = serializers.CharField( source="sector.name", required=False, allow_null=True ) Example json response: { "id": 1, "company": { "name": "Company name", "is_active": true, "city": "City", "country": "Country", "sector": "Clothing" }, "website": "test", "note": "Note" } In the json response I want to delete … -
Django 3.2.8 deploy to Heroku fails, gunicorn config.py file is missing
Has anyone run across this issue when trying to deploy Django to Heroku? I am using nothing but a standard clean Django 3.2.8 build. It runs properly locally and puts up the successful install web page. However, when deployed to Heroku I get an error (ModuleNotFoundError: No module named ‘config’) and the system ‘crashes’. I can’t figure out why the gunicorn config.py file is ‘missing’ from the install. I have seen about 5 others have this same issue, without any resolution. Where in the build process in the config.py file created? -
Django Rest Framework two Serializers for the same Model
I'm pretty sure there's a better way to do this: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('category', 'id', 'title', 'image', 'slug', 'author', 'excerpt', 'content', 'status', 'published') class FrontendPostSerializer(serializers.ModelSerializer): author = AuthorSerializer(many=False, read_only=True) category = CategorySerializer(many=False, read_only=True) class Meta: model = Post fields = ('category', 'id', 'title', 'image', 'slug', 'author', 'excerpt', 'content', 'status', 'published') PostSerializer is gonna look like this { "category": 1, "id": 45, "title": "Lorem Ipsum - Lorem ipsum dolor sit amet consectetur", "image": "http://localhost:8000/media/posts/car_SxXcUTV.jpg", "slug": "lorem-ipsum-lorem-ipsum-dolor-sit-amet-consectetur", "author": 4, "excerpt": "Officiis iure rerum voluptates a cumque velit \nquibusdam sed amet tempora. Sit laborum ab, eius fugit doloribus tenetur \nfugiat, temporibus enim commodi iusto libero magni deleniti quod quam \nconsequuntur! Commodi minima excepturi repudiandae velit hic maxime\ndoloremque.", "content": "Officiis iure rerum voluptates a cumque velit \nquibusdam sed amet tempora. Sit laborum ab, eius fugit doloribus tenetur \nfugiat, temporibus enim commodi iusto libero magni deleniti quod quam \nconsequuntur! Commodi minima excepturi repudiandae velit hic maxime\ndoloremque.", "status": "published", "published": "2021-10-01T14:46:34.872576Z" } FrontendPostSerializer is gonna look like this { "category": { "name": "django" }, "id": 45, "title": "Lorem Ipsum - Lorem ipsum dolor sit amet consectetur", "image": "http://localhost:8000/media/posts/car_SxXcUTV.jpg", "slug": "lorem-ipsum-lorem-ipsum-dolor-sit-amet-consectetur", "author": { "username": "luigi.verdi" }, "excerpt": "Officiis iure rerum voluptates … -
Getting PK from another table that isn't user - Django REST framework
I need help with the following problem please. I've managed to connect a user's id to another table, but I can't seem to replicate the same process when connecting a table to another's primary key. What am I doing wrong? MODEL Parent model class TestDataTwo(models.Model): user = models.OneToOneField("auth.User", related_name="testdatatwo", on_delete=models.CASCADE) test_name = models.CharField(max_length=1024, null=True, default="N/A") Child model class TestDataThree(models.Model): user = models.OneToOneField("auth.User", related_name="testdatathree", on_delete=models.CASCADE) sdgdata = models.OneToOneField(TestDataTwo, related_name="testdatatwo", on_delete=models.CASCADE, default=-1) test_name_again = models.CharField(max_length=1024, null=True, default="N/A") SERIALIZER Parent serializer class TestDataTwoSerializer(serializers.ModelSerializer): class Meta: model = TestDataTwo fields = ( "id", "user_id", "test_name", ) Child serializer class TestDataThreeSerializer(serializers.ModelSerializer): class Meta: model = TestDataThree fields = ( "id", "user_id", "test_name_again", ) VIEW Parent serializer class TestDataTwoViewSet(ModelViewSet): queryset = TestDataTwo.objects.all().order_by('id') serializer_class = TestDataTwoSerializer paginator = None # CREATE NEW TESTDATATWO ROW FOR USER def perform_create(self, serializer): serializer.save(user=self.request.user) # GET ALL ENTRIES OF TESTDATATWO FOR SPECIFIC USER, EXCEPT IF SUPERUSER, THEN RETURN ALL def get_queryset(self): # if self.request.user.is_superuser: # return self.queryset # else: return self.queryset.filter(user=self.request.user) # PUT/PATCH def perform_update(self, serializer): serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_200_OK) # DELETE TESTDATATWO ID def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) Child serializer class TestDataThreeViewSet(ModelViewSet): queryset = TestDataThree.objects.all().order_by('id') serializer_class = TestDataThreeSerializer paginator = None # CREATE NEW … -
DRF - URL kwargs - get list in object
I have this kind of url: /store/<pk>/categories I believe it's self-explanatory what it does. In terms of DB relation, Category has a foreign key to Store. I do have a functioning code, but I think there must be a better or more proper way of implementing it. class CategoriesListView(ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = CategorySerializer queryset = Category.objects.all() # TODO: is that right way of doing this? # or there is some sort of lookup parameter that does the same? def get_queryset(self): store = get_object_or_404(Store, pk=self.kwargs['pk']) return store.categories -
Django: custom button in admin change form return bad url for custom view function
I have problems to link my custom button from change_form.html to my view function. pic : admin change form custom button change_form.html {% extends "admin/change_form.html" %} {% load i18n %} {% block title %} Send Email {% endblock %} {% block content %} {% if request.resolver_match.url_name == 'requests_requests_change' %} <div class="submit-row"> {% csrf_token %} <a href="{% url 'requests:send-email' original.pk %}" class="button" style="background-color: #F08000;float: left">Request Subscription </a> </div> {% endif %} {{ block.super }} {% endblock %} views.py from django.shortcuts import render, redirect def send_email(request, requests_id): return redirect('') # or whatever to test the url urls.py from django.urls import path from . import views app_name = 'requests' urlpatterns = [ path('<int:pk>/send-email/', views.send_email, name='send-email'), ] main project urls.py 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.site.urls), # admin site administration path('requests/', include('requests.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) pic: error message Any help would be great! Thanks! -
Is there a way to enable django DEBUG mode using nginx?
I deployed my project on served with nginx and gunicorn. When I am trying to access a particular endpoint there is an error: "500 Internal Server Error", that is bad, so I have decided to enable django debug mode, but nothing has changed. Instead of informative traceback, I get an uninformative http status code, so how can I change it? -
Rendering multiple image blob ulrs using react result in corrupted images
I'm trying to build an app that takes an image file as input, posts it to the server, and receives a styled image as blob URL. The problem is that some of the received images are sometimes corrupted. There is no pattern here and some of them are randomly corrupted. And sometimes it works fine with no corrupted images. Here are the relevant code snippets. I'm using django-rest framework for the backend. var styled_images = [] function StyleTransferCarousel() { const [styledImages, setStyledImages] = useState([]) const [styled, setStyled] = useState(false) // this function gets the image blob from server const getStyledImage = async (model) => { var formData = new FormData() ... try { const { data } = await axios.post('/style_transfer/stylev2/', formData, config) return data } catch (error) {...} } // this function gets the image blob untill the size of image list is equal to available models and re-renders async function getStyledImages() { var styledImageDict = {} for (let i = 0; i < models.length; i++) { var model_i = models[i] var data = getStyledImage(model_i) data.then(data => { styledImageDict = { image: "data:image/png;base64," + data.image, model: models[i] } styled_images = styled_images.concat([styledImageDict]) if (styled_images.length !== models.length) { setLoader(false) setStyledImages(styled_images) //react hook … -
Django CKEditor add YouTube plugin
I was trying to find answer for my question, but still couldn't figure it out. I have my model with field: description = RichTextUploadingField(verbose_name='Description', config_name='special') In settings.py I have: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', "removePlugins": "stylesheetparser", 'toolbar_Custom': [ ['Bold', 'Link', 'Unlink', 'Image'], ], }, 'special': { 'toolbar': 'Special', 'enterMode': 2, 'height': 500, 'width': 1100, "removePlugins": "stylesheetparser", 'extraAllowedContent': 'iframe[*]', 'toolbar_Special': [ ...... { 'name': 'youtube', 'items': ['Youtube',] }, ], } } And it works, but youtube icon doesn't display on my toolbar. Searching for solution I read I have to put youtube-plugin in ckeditor config. So in my folder project (where all apps are created) I created ckeditor/ckeditor/plugins/youtube/. Like on attached image. . Unfortunately the option to add youtube video still don't display on toolbar. Is there something I'm doing wrong or need to do something else? -
How i change url in Django framework
i'm try to make some website using django and i got some error message like this Request URL: http://127.0.0.1:8000/store.html Using the URLconf defined in greatkart.urls, Django tried these URL patterns, in this order: admin/ [name='home'] store/ ^media/(?P<path>.*)$ The current path, store.html, didn't match any of these. the problem is when i tried to click button it's allways print ./store.html not the ./store it's my html code for the button <a href="./store.html" class="btn btn-outline-primary float-right">See all</a> and this is my django for urls.py (main) urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('store/', include("store.urls")) ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) this urls.py(store) urlpatterns = [ path('', views.store, name='store'), path('<slug:category_slug>/', views.store, name='product_by_category'), ] views.py def store(request, category_slug = None): return render(request, 'store/store.html', context) anyone have some idea? i want to fix it without change html code because I've tried it and when i click on the buttons twice that make some error because the url print the ./store twice -
Django authentication: index for staff and index for user (2 templates)
I have 2 functions currently working, one is a specific view for is_staff users, the other for any users. Right now after staff logs in they can add path /dashboard to the URL and can access the route, while normal users cannot view it. That is expected and good. Problem: I want to at login, to redirect user.is_staff straight to this path /dashboard, instead of going to index first. The functions somehow I think I have to merge: (views.py) 1 @staff_member_required 2 def staff_dashboard(request): 3 users = User.objects.all() 4 customer = Customer.objects.all() 5 accounts = Account.objects.all() 6 context = { 7 'users': users, 8 'customer': customer, 9 'accounts': accounts 10 } 11 return render(request, 'bank_app/dashboard.html', context) 12 13 14 @login_required 15 def index(request): 16 customer = Customer.objects.filter(user=request.user) 17 accounts = Account.objects.filter(user=request.user) 18 context = { 19 'customer': customer, 20 'accounts': accounts 21 } 22 return render(request, 'bank_app/index.html', context) (urls.py:) urlpatterns = [ path('dashboard', views.staff_dashboard, name='staff_dashboard'), path('', views.index, name='index'), path('create', views.create, name='create'), path('createaccount', views.createaccount, name='createaccount'), path('details/<int:pk>', views.details, name='details'), ] When user is_staff, show "dashboard/"(dashboard.html), not ""(index.html) *I also have extension template seen below but that did not fix the issue: 28 <p>Welcome {{ user }}</p> 29 30 {% if user.is_staff %} … -
Default/Initial value for Django forms field (required=True) after POST-request (bound forms)
I tried all the solutions here on Stackoverflow but they all use required=False. How can I set a default value for a required form-field every time, even after a post request (when the form is bound)? # forms.py class MyForm(forms.Form): name = forms.CharField(required = True) def __init__(self, *args, **kwargs): super(editSonde_KundenAdminPanel, self).__init__(*args, **kwargs) self.initial['name'] = "foo bar" #Views.py def index(request): if request.method == 'GET': form = MyForm() if request.method == 'POST': form = MyForm(request.POST) #After this step, the form doesn't have an initial value anymore... if form.is_valid() #Do Stuff -
login a user without login() function in django
I have used the User model for storing data of normal user but I want to store data of some special user in other model but than how will I be able to authenticate these special users and login them .Can I use the authenticate() and login() functions with other model also other than User model? -
How can I get one object when we select object from dependent dropdown list in django
(I am working on dependent dropdown list in Django) I have two dropdown lists first is Company and second is Car. when I select company Name from first dropdown list like Toyota all cars are coming related to Toyota Company, when I select any car from second dropdown (Car Dropdown) then it's showing nothing against Toyota I only need one car which I have selected, How can I do this ? Any one can help ? It is showing empty page like this Here is my code models.py class Car(models.Model): CarID = models.AutoField(primary_key=True) CarName = models.CharField(max_length=500, blank=True, null=True, verbose_name="Car Name") company = models.ForeignKey(Company, verbose_name="Company Name", on_delete=models.CASCADE, default="") type = models.ForeignKey(CarType, verbose_name="Vehicle Type", on_delete=models.CASCADE) CarImage = models.ImageField(upload_to='productimg', verbose_name="Vehicle Image") RefNo = models.CharField(max_length=500,verbose_name="Ref No", null=True, blank=True) ChassisNo = models.CharField(max_length=500,verbose_name="Chassis No", null=True, blank=True) ModelCode = models.CharField(max_length=500,verbose_name="Model Code", null=True, blank=True) EngineSize = models.CharField(max_length=500,verbose_name="Engine Size", null=True, blank=True) Location = models.CharField(max_length=500,verbose_name="Location", null=True, blank=True) Version = models.CharField(max_length=500,verbose_name="Version/Class", null=True, blank=True) Drive = models.CharField(max_length=500,verbose_name="Drive", null=True, blank=True) Transmission = models.CharField(max_length=500,verbose_name="Transmission", null=True, blank=True) mfdate = models.DateField(auto_now_add=False, blank= True,null=True, verbose_name="Manufacturing Date") Mileage = models.CharField(max_length=500,verbose_name="Mileage", null=True, blank=True) EngineCode = models.CharField(max_length=500,verbose_name="Engine Code", null=True, blank=True) steering = models.ForeignKey(Steering, verbose_name="Steering", on_delete=models.CASCADE, default="") ExtColor = models.CharField(max_length=500,verbose_name="Ext Color", null=True, blank=True) Fuel = models.CharField(max_length=500,verbose_name="Fuel", null=True, blank=True) Seats = models.CharField(max_length=500,verbose_name="Seats", … -
Getting no reverse match at /post in django
I have been facing this issue. And I have a url name post-page-detail but then also getting error please See the error screenshot below. My html page <a href="{% url "post-detail-page" slug=post.slug %}"> <h2>{{post.tractor_company}} || {{post.tractor_model}}</h2> <pre><h5>{{post.implimentaion}}</h5> {{post.farmer}} Uplode Date : {{post.date}}</pre> </a> </div> URLs.py from . import views urlpatterns = [ path("",views.starting_page,name = "starting-page"), path("posts",views.posts,name = "post-page"), path("posts/<slug:slug>",views.post_detail,name="post-detail-page"), ] -
Celery SchedulingError - Redis : Authentication required
I have'a scheduled task in celery like this. #my_app.tasks @shared_task(ignore_results=True) def my_task(): print("running") #settings.py CELERY_BEAT = { 'my_scheduled_task': { 'task': 'my_app.tasks.my_task', 'schedule': datetime.timedelta(minutes=5) }, } I'm using rabbitMQ for broker. When i run the celery worker with beat. I'm getting this error : SchedulingError("Couldn't apply scheduled task my_scheduled_task: Authentication required.",) versions: celery==4.3.0 django-redis==4.8.0 -
nginx: [emerg] host not found in upstream when dockerizing a django/react project
I'm trying to dockerize a django/react project but i'm running into this error when running docker-compose up. i don't understand where the error come from. i'm new to docker. my goal is to deploy the frontend and the backend separately in one server. nginx: [emerg] host not found in upstream [emerg] 1#1: host not found in upstream "backend:8000" in /etc/nginx/conf.d/default.conf:2 nginx_1 | nginx: [emerg] host not found in upstream "backend:8000" in /etc/nginx/conf.d/default.conf:2 here is my code django's Dockerfile ENV DJANGO_SECRET_KEY $DJANGO_SECRET_KEY ENV DJANGO_CORS_ORIGIN_WHITELIST $DJANGO_CORS_ORIGIN_WHITELIST RUN mkdir /backend WORKDIR /backend COPY requirements.txt /backend/ EXPOSE 8000 RUN pip install -r requirements.txt COPY . /backend/ RUN python manage.py makemigrations RUN python manage.py migrate react's Dockerfile FROM node USER root WORKDIR /frontend COPY . /frontend ARG API_URL ENV REACT_APP_HOST_IP_ADDRESS $API_URL RUN yarn RUN yarn config set ignore-engines true RUN yarn build server's config upstream api { server backend:8000; } server { listen 8080; location /api/ { proxy_pass http://api$request_uri; } # ignore cache frontend location ~* (service-worker\.js)$ { add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; expires off; proxy_no_cache 1; } location / { root /var/www/frontend; try_files $uri $uri/ /index.html; } } docker-copose.yml version: '3' services: backend: build: context: ./ruelle_backend args: DJANGO_ALLOWED_HOSTS: http://ruelle-online.fr DJANGO_SECRET_KEY: anis1807 DJANGO_CORS_ORIGIN_WHITELIST: … -
It is possible to modify a env variable in django constance without reloading server?
I'm working with django constance to define some dynamic variables. When I modify some variable, the changes are not applied, so I have to stop django server and run again to see the applied changes according to that variable. Is there any way to change these variables without reloading the server? django constance painel -
Further filter the results of queryset in django
I have two basic models in django named Applications and Status and a third one to track the application statuses, named TrackApplicationStatus. So, every time the status of the application changes, a new record is added to the TrackApplicationStatus table. The current status of each application is the status of the most recent record of that table. The models are defined as: from django.db import models class Application(models.Model): name = models.CharField(max_length=100) class Status(models.Model): name = models.CharField(max_length=100, blank=False, unique=True) class TrackApplicationStatus(models.Model): created_at = models.DateTimeField(auto_now_add=True) application = models.ForeignKey(Application, on_delete=models.CASCADE, related_name='statuses') status = models.ForeignKey(Status, on_delete=models.SET_NULL, related_name='applications_status', null=True) class Meta: get_latest_by = ['created_at'] ordering = ['-created_at'] On the first step, I am retrieving the current statuses of each application with the following django query: current_statuses = TrackApplicationStatus.objects.order_by('application_id', '-created_at').distinct('application_id') The produced SQL query is the following: SELECT DISTINCT ON ("api_trackapplicationstatus"."application_id") "api_trackapplicationstatus"."id", "api_trackapplicationstatus"."created_at", "api_trackapplicationstatus"."application_id", "api_trackapplicationstatus"."status_id" FROM "api_trackapplicationstatus" ORDER BY "api_trackapplicationstatus"."application_id" ASC, "api_trackapplicationstatus"."created_at" DESC What I want to do next, is to get all applications with a specific status. In SQL terms I would apply a WHERE clause on the above result table as follows: SELECT sub.application_id FROM ( SELECT DISTINCT ON ("api_trackapplicationstatus"."application_id") "api_trackapplicationstatus"."created_at", "api_trackapplicationstatus"."application_id" as application_id, "api_trackapplicationstatus"."status_id" as status FROM "api_trackapplicationstatus" ORDER BY "api_trackapplicationstatus"."application_id" ASC, "api_trackapplicationstatus"."created_at" … -
make admin interface accessible while using uwsgi
I added uwsgi to serve up the Django app. but I wanted to still have access to the Django admin. but I seem to have made it so that all addresses on the localhost:8000 always point to that same index.html file. I'm fresh to the whole WSGI thing and setting up for production. What did I do wrong and how can I get the admin interface to correctly rout and display? I appreciate any help. Thank you. wsgi app application( { "REQUEST_METHOD": "GET", "SERVER_NAME": SimpleLazyObject(get_allowed_host_lazy), "REMOTE_ADDR": "127.0.0.1", "SERVER_PORT": 80, "PATH_INFO": "/admin/", "wsgi.input": b"", "wsgi.multiprocess": True, }, lambda x, y: None, ) urls.py urlpatterns += static("/media/", document_root=settings.MEDIA_ROOT) + [ url(r"^static/(?P<path>.*)$", serve), url(r"^", views.homepage, name="homepage"), url(r"^admin/", admin.site.urls), ] views.py def homepage(request): application_url = os.environ.get("APPLICATION_URL", "") dashboard_url = os.environ.get("DASHBOARD_URL", "") admin_url = os.environ.get("ADMIN_URL", "") return TemplateResponse( request, "home/index.html", {"application_url": application_url, "dashboard_url": dashboard_url, "admin_url": admin_url}, ) uwsgi.ini [uwsgi] die-on-term = true enable-threads = true http = :$(PORT) module = project.wsgi:application static-map = /static=/app/static master = true processes = 4 ignore-sigpipe = true ignore-write-errors = true disable-write-exception=true -
django celery kombu.exceptions.EncodeError
from sys import pycache_prefix when i run this gettging below error celery_task.delay(event_data) error: File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps return cls( File "/usr/lib/python3.8/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/home/ubuntu/baby_prod_backend/env/lib/python3.8/site-packages/kombu/utils/json.py", line 58, in default return super().default(o) File "/usr/lib/python3.8/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' kombu.exceptions.EncodeError: Object of type AttributeDict is not JSON serializable my celery task app = Celery("settings", broker=BASE_REDIS_URL) app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() CELERY_EAGER_PROPAGATES_EXCEPTIONS = True app.conf.broker_url = BASE_REDIS_URL app.conf.update( task_serializer="pickle", result_serializer="json", accept_content=["json", 'pickle'] ) @app.task(serializer='json') def partial_bid_created_event(event): transactionHash = transactionHash.hex() transaction_processed = ProcessTransaction.objects.filter(tnxid=transactionHash, event=event["event"]).count() if transaction_processed: return {"msg": "transaction already created"} please take a look what can be the issue . here using this task i am doing something in my django database below i added inside setting.py CELERY_EAGER_PROPAGATES_EXCEPTIONS = True CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' CELERY_ACCEPT_CONTENT = ['pickle', 'json'] tryed using json and pickle both not working . -
Migration does not create column in database
makemigrations and migrate are working fine with no error. but when i check database it does not created heres the model: class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,related_name='sub_service') service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) service_description = models.TextField( null=True, blank=True) duration = models.CharField(max_length=100,null=True,blank=True) I have added duration field later and its not giving me any error while running api django.db.utils.ProgrammingError: column service_list_services.duration does not exist LINE 1: ...", "service_list_services"."service_description", "service_l... i have tried deleting migration files and then migrating but still.. its not giving error while migrating but doesnot create row. tried this python manage.py migrate --fake still same -
'SettingsReference' object has no attribute '_meta'
Getting this error after changing the custom user table in the mid-project also after changing the name of the custom user class.