Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django + nginx on Docker (400) Bad Request
Although I tried every method raised in StackOverFlow, I cannot solve the problem. When I want to login my site, the error shows up. What I tried ALLOWED_HOSTS = ['*'] Removing underscore from the name of hosts Putting the name of upstream in nginx.conf Putting some stuff for nginx.conf as the following nginx.conf file settings.py ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") env.prod DEBUG=Fault DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] ecap nginx.conf upstream ecap { server web:8000; } server { listen 80; location / { proxy_pass http://ecap; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } location /mediafiles/ { alias /home/app/web/mediafiles/; } } docker-compose.prod.yml version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn ecap.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - ./static_volume:/home/app/web/staticfiles - ./media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: log ecap5-nginx-1 | 192.168.192.1 - - [15/Oct/2022:10:17:30 +0000] "POST /login/%7Burl%20'Login'%20%%7D HTTP/1.1" 400 157 "-" "-" "-" I appreciate your cooperation. -
CORS policy Error in react app while Zoho meeting api integrations
I have been trying to integrate zoho meetings with my application(React is front end and django is backend). While fetching the access token i'm getting the following error. Access to fetch at 'https://accounts.zoho.com/oauth/v2/token?code=1000.53axxxxxxxxxxxxxxxxxxxxxxxxxx2e8e5eb43cfe53005f8d93490&client_id=1000.PGPL8RK7R54UR7JSNKTM2ZRETSF4CI&client_secret=xxxxxxxxxxxxxxxxxxx&redirect_uri=http://localhost:3000/app_store/zoho_meet&grant_type=authorization_code' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. here is my axios code part` headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', "Access-Control-Allow-Origin": "*", } }) const url = `https://accounts.zoho.com/oauth/v2/token?code=${zcode}&client_id=1000.xxxxxxxxxxxxxxxI&client_secret=92821f12d14cf11162891xxxxxxxxxxxxxxxxxxxx&redirect_uri=http://localhost:3000/app_store/zoho_meet&grant_type=authorization_code` publicAxios.get(url) .then((res)=>{ console.log(res) }) .catch((err)=>{ console.log(err) }) ` can anybody here help me what steps did i missed here -
Internal server error(digital ocean) django
I wish you can help me with this issue I deployed my project to Ubuntu 22.0 droplet 3 days ago with nginx and gunicorn and certbot everything was working fine but yesterday i was going to update the project and first I installed wkhtmltopdf after that i restarted the server and the website keep gives me Internal server error i dont know what happen to the sever corrupt it like that i wish you could help me I tried to restart ngnix and gunicorn should i need to do something else im new with wkhtmltopdf so i dont understand how this can happen -
do some things same time in the Django unit test
How can I test if two users can reserve the same car simultaneously? def test_if_two_users_can_reserve_the_same_car_simultaneously(self): with patch.object( timezone, "now", return_value=make_aware( datetime.datetime.combine( datetime.date.today() + datetime.timedelta(days=1), datetime.time(10, 30, 0) ), timezone=pytz.timezone("UTC"), ), ): self.client.login(username=self.user.username, password=self.PASSWORD) url = reverse("booking-list") data = { "book_for": datetime.datetime.combine( datetime.date.today() + datetime.timedelta(days=1), datetime.time(11, 30, 0) ), } response = self.client.post(url, data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) with patch.object( timezone, "now", return_value=make_aware( datetime.datetime.combine( datetime.date.today() + datetime.timedelta(days=1), datetime.time(10, 30, 0) ), timezone=pytz.timezone("UTC"), ), ): self.client.login( username=self.another_user.username, password=self.PASSWORD ) url = reverse("booking-list") data = { "book_for": datetime.datetime.combine( datetime.date.today() + datetime.timedelta(days=1), datetime.time(11, 30, 0) ), } response = self.client.post(url, data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) This is how I wrote it, but in the unit test, it runs line by line. So first one will create then move to second one but I want them both run at same time. (Please answer with an example) -
simple song CRUD application with a music app
simple song CRUD application. In our models.py file inside the “musicapp” application we created, you are expected to add the following Models and Attributes. Model: Artiste, Song, Lyric Attributes for “Artiste” : first_name, last_name, age Attributes for “Song”: title, date released, likes, artiste_id Attributes for “Lyric”: content, song_id As you might have guessed, there is a relationship between all three Models. An Artiste can have multiple songs, and a song can have multiple lyrics.A song must only belong to one Artiste and a lyric must only belong to a song. -
How to authenticate a user in django unit test when rest framework's DEFAULT_AUTHENTICATION_CLASSES is 'JWTStatelessUserAuthentication'?
I had a Django project with the following settings: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] and in the unit testing phase, I used to assign a Token to an existing user to authenticate the user: def setUp(self): self.user = User.objects.create(username='u1') self.client = APIClient() token = Token.objects.create(user=self.user) self.client.credentials(HTTP_AUTHORIZATION="Token " + token.key) but now, in my current project, I don't authenticate users, instead, I use these settings: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTStatelessUserAuthentication', ], SIMPLE_JWT = { 'ALGORITHM': '...', 'SIGNING_KEY': '...', } and user authentication stuff is in another project and authentication tokens have an expiration time! How can I authenticate a user in my unit testing?! Is there any solution to this issue? -
How to use dj-rest-auth with many clients
I'd like to have many different clients be able to access my django website (more specifically its API) but I'm not sure how to do this with django-allauth, dj-rest-auth and simplejwt. My current client app is using the built in django template engine and is set up with django-allauth for social authentication (Google etc). It's working using the documented installation recommendations. I would now like to create different types of clients that aren't using the django template engine (e.g. Angular, Vue, flutter mobile etc) but I'm confused how dj-rest-auth is used so that it scales to support any number of client types. Using Google social sign in as an example, when I create a new client, I have to register a new redirect_uri specific to that client. To test this all out, I created a simple flask app with a single link so that I can retrieve a "code/access_token" before sending it to my Django app. The link is created using the following... var codeRequestUrl = `https://accounts.google.com/o/oauth2/v2/auth?\ scope=email&\ access_type=offline&\ include_granted_scopes=true&\ response_type=code&\ state=state_parameter_passthrough_value&\ redirect_uri=http%3A//127.0.0.1:5000/callback&\ client_id=${clientId}`; ...and the code is retrieved at the '/callback' endpoint in flask... @app.route("/callback", methods=['GET']) def redirect(): code = request.args.get('code', '') req = requests.post('http://127.0.0.1:8000/api/dj-rest-auth/google/', data={'code':code}) return "done..." ...from … -
Django IntegrityError (1048, "Column 'item_id_id' cannot be null")
The error posted is Integrity Error 1048 column cannot be null IntegrityError at /Supply/supplyItems (1048, "Column 'item_id_id' cannot be null") Request Method: POST Request URL: http://127.0.0.1:8000/Supply/supplyItems Django Version: 4.1.1 Exception Type: IntegrityError Exception Value: (1048, "Column 'item_id_id' cannot be null") Exception Location: C:\Users\63966\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py, line 80, in execute Raised during: Supply.views.SupplyItem Python Executable: C:\Users\63966\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.6 Python Path: ['D:\CIT\3rd Year\IM 2\New ' 'folder\sarisaristoreproject\sarisaristoreproject\sarisaristoreproject', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\63966\AppData\Local\Programs\Python\Python310', 'C:\Users\63966\AppData\Local\Programs\Python\Python310\lib\site-packages'] Server time: Sat, 15 Oct 2022 07:25:53 +0000 Here is my models.py class Supplier(models.Model): supplier_id = models.AutoField(primary_key=True) company_name = models.CharField(max_length=20, null=False) company_address = models.CharField(max_length=50, null=False) company_num = models.IntegerField(null=False) def __str__(self): return str(self.company_name) class supplyItem(models.Model): item_id = models.ForeignKey('Items.Items', on_delete=models.CASCADE) supplier_id = models.ForeignKey(Supplier, on_delete=models.CASCADE) numOfItemsS = models.IntegerField() Items model from different App: class Items(models.Model): item_id = models.AutoField(primary_key=True) item_name = models.CharField(max_length=50, null=False) item_qty = models.IntegerField(null=False) item_prc = models.FloatField(null=False) purchase = models.ManyToManyField('registration.Customer', through='Purchase.purchasedItem', related_name='items', blank=True) sell = models.ManyToManyField('registration.Employee', through='Sell.sellItem', related_name='items', blank=True) def __str__(self): return self.item_name My views.py class HomeView(View): template = 'supply.html' def get(self, request): return render(request, self.template) class SupplyItem(View): template = 'SupplyItems.html' def get(self, request): form = SupplyItemForm() return render(request, self.template, {'form': form}) def post(self, request): form = SupplyItemForm(request.POST) if form.is_valid(): form.save() return render(request, self.template, {'form': form}) Forms.py class SupplyItemForm(ModelForm): itemID = forms.ModelChoiceField(widget=forms.Select(), queryset=Items.objects.only('item_id'), label='Item … -
ProgrammingError at / relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se
i dont know why am getting this django_session does not exist error its working when am running it on localserver but when i have deployed to heroku i am getting this error , is anyone help me to resolve this issue coz am not able to figure out , what is it In settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'home.apps.HomeConfig', 'blog.apps.BlogConfig' ] DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "<name>", "USER": "<username>", "PASSWORD": "<pass>", "HOST": 'localhost', "PORT": '5432', } } here i have added my credentials -
Django sesssions and Microsoft OAuth 2.0 authorization code flow: what is the right way?
In my web app I collect some data from a user and save them in request.session. Then I need to obtain MS Graph access/refresh tokens. So I request an authorization code. After that I need to return to the initial user's sessions. app_name = 'sua' urlpatterns = [ path('', WizardView.as_view(), name='main'), path('cauth', CloudAuthView.as_view(), name='cauth'), ] class CloudAuthView(View): def get(self, request): auth_code = request.GET.get('code', '') if auth_code: session_key = request.GET.get('state', '') s = SessionStore(session_key=session_key) s['auth_code'] = auth_code print(f'auth_code: {request.session.session_key}; {request.META.get("HTTP_REFERER")}') return redirect(reverse('sua:cauth')) print(f'get: {request.session.session_key}; {request.META.get("HTTP_REFERER")}') auth_url = _get_auth_url(state=request.session.session_key) print(auth_url) return redirect(auth.get_auth_url(state=request.session.session_key)) Logs: Starting development server at http://127.0.0.1:43814/ Quit the server with CTRL-BREAK. [15/Oct/2022 13:30:53] "GET / HTTP/1.1" 200 5528 [15/Oct/2022 13:30:59] "POST / HTTP/1.1" 302 0 get: es52sm9fxogmhwgja3nkgzel2g9declx; http://127.0.0.1:43814/ auth_url: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A43814%2Fcauth&scope=offline_access+User.Read+Files.Read+User.Read.All+User.ReadWrite.All+Directory.Read.All+Directory.ReadWrite.All+Files.ReadWrite.All+Sites.FullControl.All&response_type=code&state=es52sm9fxogmhwgja3nkgzel2g9declx&client_id=xxx [15/Oct/2022 13:30:59] "GET /cauth HTTP/1.1" 302 0 auth_code: j92mb1ougcqjhvr50xsfufap1jayru5s; http://127.0.0.1:43814/ [15/Oct/2022 13:31:00] "GET /cauth?code=0.AUIAGvBhs...&state=es52sm9fxogmhwgja3nkgzel2g9declx&session_state=2794f2aa HTTP/1.1" 302 0 get: j92mb1ougcqjhvr50xsfufap1jayru5s; http://127.0.0.1:43814/ [15/Oct/2022 13:31:00] "GET /cauth HTTP/1.1" 302 0 [15/Oct/2022 13:31:00] "GET / HTTP/1.1" 200 5668 -
filtering an queryset in an Inline object in Django Admin
The contest is an inventory app of an e-commerce project. As expected, there's a Product model. In an attempt to normalize the DB schema, I have created these additional models: ProductType (ForeignKey relationship in Product) ProductSpecification (a FK in ProductType) ProductInventory (with a FK to Product) ProductSpecificationValue (FK to both ProductSpecification and ProductInventory) I hope this makes sense - each ProductType has many Products, and also many Specifications. ProductInventory (suggestions of a better name are welcome), with a FK to product, is a model with SKU and quantity fields. And the fun part - it has a ManyToMany relationship to ProductSpecification, through ProductSpecificationValue. Now the part where I am lost is adding this whole thing to Django Admin site. I can create ProductTypes and Products without any problem, and a ProductTypeAdmin has an inline to add those specs:. @ admin.register(ProductType) class ProductTypeAdmin(admin.ModelAdmin): inlines = [ ProductSpecificationInline, ] The problem starts when I try to add a ProductInventory entity. Because it's associated with a given ProductType, I want to limit the choice of inlines to only those which are related to the same ProductType. class ProductSpecificationValueInline(admin.TabularInline): model = ProductSpecificationValue def get_formset(self, request, obj=None, **kwargs): # obj is always the current Product … -
How to retrieve all Variants of a single Product in a single JSON object per Product- Django Rest Framework
The way I am doing it is like in getProductList function in my views.py and it is giving me each product with its variants in different objects like so: JSON: [ { "prod_id": { "id": 3, "prod_name": "CRUISER-149S-DEERCALF", "category": 2 }, "size_id": { "id": 2, "name": "26" }, "color_id": 2, "image_id": { "id": 10, "prod_image": "/media/products/IMG_7617_ftgqoa.jpg" } }, { "prod_id": { "id": 3, "prod_name": "CRUISER-149S-DEERCALF", "category": 2 }, "size_id": { "id": 3, "name": "27" }, "color_id": 2, "image_id": { "id": 10, "prod_image": "/media/products/IMG_7617_ftgqoa.jpg" } } ] Is there a way to maybe make it more optimized? like have only one object that has all the info of a single product like size for example can be a property with values of all sizes in it like size: [26, 27] instead of a different object if a size is different. models.py class Products(models.Model): prod_name = models.CharField(max_length=200) category = models.ForeignKey(Categories,null=True, on_delete=models.SET_NULL) def __str__(self): return '%s'%(self.prod_name) class Variants(models.Model): prod_id = models.ForeignKey(Products, on_delete=models.CASCADE) size_id = models.ForeignKey(Size, null=True, on_delete=models.SET_NULL, related_name='variants') color_id = models.ForeignKey(Color, null=True, on_delete=models.SET_NULL, default='') image_id = models.ForeignKey(Image,null=True, on_delete=models.SET_NULL, default='') def __str__(self): return '%s %s %s %s %s %s %s'%(self.id , self.prod_id, self.size_id, self.image_id, self.color_id, self.quantity, self.price) serializer.py class ProductsSerializer(serializers.ModelSerializer): # variants = serializers.StringRelatedField(many=True) … -
Overriding create() for class based generic views
How can I perform some logic prior to saving a record within my generic view? I believe the actual saving logic occurs within super().create(). class WalletListCreateAPIView(generics.ListCreateAPIView): queryset = Wallet.objects.all() serializer_class = WalletSerializer def create(self, request, *args, **kwargs): # Some logic here prior to saving return super().create(request, *args, **kwargs) For instance, I would like to create the value for balance instead of relying on the value from the request class Wallet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=34) balance = models.DecimalField(default=0, max_digits=16, decimal_places=8) slug = models.SlugField(max_length=34, blank=True, null=True) -
RASA 3.2.0 Server Coonection with Django Server
I want to connect Rasa 3.2.0 with Django for a Frontend Webchat. I have gone through this link: - https://www.youtube.com/watch?v=XMAw_bKTLbA and this link: - https://forum.rasa.com/t/rasa-chatbot-blank-page/55721/6. But somehow it is not connecting and showing Blank White Page. Here is the Template HTML File: - {% load static %} <link rel="stylesheet" href="{% static 'Chatroom.css' %}"/> <div class="chat-container"></div> <script src="{% static 'Chatroom.js' %}"></script> <script type="text/javascript"> var chatroom = new window.Chatroom({ host: "http://localhost:5005/webhook", title: "Rasa Assistant", container: document.querySelector(".chat-container"), welcomeMessage: "Hi, I am AIChatbot!", speechRecognition: "en-US", voiceLang: "en-US" }); chatroom.openChat(); </script> I also tried changing the Chatroom.js and .css file which was coming from AWS S3 Bucket...still get same problem. -
How do you connect an amazon rds to a django app
I have added the correct name, engine, user, password etc. Then I modified the inbound security rules to give my computer access to the database and I still cant connect the postgres database to the django app does anyone know what could cause this? I keep getting this error port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? -
OperationalError at / no such column: accounts_customer.user_id
i have been following this tutorial I was going smoothly but i got an error .i am not sure how to resolve it .I added onetoone relationship to the customer with user model.And now got this user. `models.py enter code here from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import User class customer(models.Model): user=models.OneToOneField(User,null=True,on_delete=models.CASCADE) id=models.UUIDField(primary_key=True,default=uuid.uuid4) name=models.CharField(max_length=200,null=True) phone_no=models.CharField(max_length=200, validators [RegexValidator(r'^\d{1,10}$')],null=True) email=models.EmailField(max_length=200,null=True) def __str__(self): return self.name class tag(models.Model): name=models.CharField(max_length=200,null=True) def __str__(self): return self.name class products(models.Model): categories=[ ('indoor','indoor'), ('outdoor','outdoor') ] name=models.CharField(max_length=200,null=True) price=models.FloatField(null=True) manufacturedate=models.DateTimeField(auto_now_add=True,null=True) description:models.TextField(null=True) categories=models.CharField(max_length=200,null=True,choices=categories) tag=models.ManyToManyField(tag) def __str__(self): return self.name class order(models.Model): status=[ ('pending','pending'), ('out of stock','out of stock',), ('Delivered',('Delivered')) ] ordered_date=models.DateTimeField(auto_now_add=True) status=models.CharField(max_length=200,null=True,choices=status) customer=models.ForeignKey(customer,null=True,on_delete=models.SET_NULL) product=models.ForeignKey(products,null=True,on_delete=models.SET_NULL) def __str__(self): return self.product.name I am really confused . I am stuck here for a while.It was all fineuntil i added onetoone relationship. views.py enter code here from multiprocessing import context from django.shortcuts import render,redirect from django.contrib.auth.models import Group from .models import * from .forms import CreateCustomer,CreateOrder,CreateUser from .filters import FilterSearch from django.contrib.auth import logout,login,authenticate from django.contrib import messages from django.contrib.auth.decorators import login_required from .decorators import allowed_users,admin_only def registeruser(request): if request.user.is_authenticated: return redirect('home') else : form=CreateUser() if request.method=='POST': form=CreateUser(request.POST) if form.is_valid(): user=form.save() group=Group.objects.get(name='customer') user.groups.add(group) login(request,user) return redirect('home') context={'form':form} return render(request,'accounts/registeruser.html',context) def loginuser(request): if request.user.is_authenticated: return redirect('home') … -
How to get a django instance to have one to many users relation
I have a company table as follows: class Company(models.Model): users = models.ManyToManyField(settings.AUTH_USER_MODEL, default=None) My plan is that a given company instance can have more than one user account tied to it. But from above, when a company is created, the users field is ending up with all the users in the users table. That is not I want. I want that users are manually added rather than just populating the field with all users in the database: How can I set this up so that a given company instance can only have the users added to it rather than all database users? -
What is the best way to make logs with React and Python(Django)?
If I have a frontend with React and a backend with Python Django, how can I integrate custom logs? If I need to store which functions were pressed and when? Example: We have a PostgreSQL database and there is a file called Logs.txt. When the user opens a specific route, we need to save the time and route name in this file. Also, if there are some buttons that run some functions, we also need to save the time and function name in this log file. Do I need to every time to make a simple request to the backend to save new data about users' pressed history? Or is there some better approach? -
Django doesn't process POST request's payload from axios
I have React + Django REST Framework stack. DRF works as API and React as SPA. And I'm really confused why POST request doesn't work. If any additional information is required, please, ask me. In React I'm making POST request with axios like following: axios .post( '/api/auth/register/', registrationInfo, { headers: { "Content-Type": "application/json" } } ) .then((response) => { setRegistrationStatus(response.data.status) }) .catch((error) => { console.log(error) }) The frontend part of request seems to work fine. Payload and headers are shown: , In DRF My serializer for registration look like this: class RegistrationSerializer(UserSerializer): password = serializers.CharField(max_length=200, write_only=True, required=True) email = serializers.EmailField(required=True, write_only=True, max_length=200) class Meta: model = CustomUser fields = ['id', 'email', 'password', 'phone', 'first_name', 'last_name', 'is_active', 'created_at', 'modified_at'] def create(self, validated_data): try: user = CustomUser.objects.get(email=validated_data['email']) except ObjectDoesNotExist: user = CustomUser.objects.create_user(**validated_data) return user ...and views: class RegistrationViewSet(viewsets.ModelViewSet, TokenObtainPairView): serializer_class = RegistrationSerializer permission_classes = (AllowAny,) http_method_names = ['post'] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=self.request.query_params) serializer.is_valid(raise_exception=True) user = serializer.save() refresh = RefreshToken.for_user(user) res = { "refresh": str(refresh), "access": str(refresh.access_token), } return Response({ "user": serializer.data, "refresh": res["refresh"], "token": res["access"] }, status=status.HTTP_201_CREATED) The output of DRF when making request is confusing. In developer tools-network the response is {"email":["This field is required."],"password":["This field is … -
Celery Beat sending all periodic tasks as due on restart even if they have just run
I am running a celery worker and celery beat with DatabaseScheduler. I am running these on Heroku along with a django web application. They are being used to send emails and texts at regular intervals, Once per day at midnight for emails and 730am for texts. I have defined the tasks manually using a chrontab in Periodic Tasks table, but I have also tried defining them in the codebase using celeryapp.conf.beat_schedule, both behave the same. The tasks look like this periodic tasks in django admin The issue I am having is that Heroku restarts its dynos once per day as a policy, and when this happens, the celery beat dyno runs my periodic tasks for some reason. The debug log reads "Scheduler: Sending due task" as if it is normal, whether they are due then or not. I do not know why this is happening. I have celery results running as well with postgres backed task results and that looks like this, where I have the tasks running at the correct times (midnight and 730am), but also at some random time when heroku restarts the dynos. How can I stop the tasks from running when this restart happens? Why are … -
Django Queryset return all if field is empty when there is OneToMany relationship
I have an html page in which one can search for a car based on several criteria. How do I tell django orm to return all if a field is empty? I checked this question and implemented the same idea of the first answer but it doesn't work for the foreign fields especially the model field, which if left empty, I get this error. Here are my classes class City(models.Model): name = models.CharField(max_length=10, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) class PowerSource(models.Model): source = models.CharField(max_length=8) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Manufacturer(models.Model): manufacturer = models.CharField(max_length=45) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class CarModel(models.Model): model = models.CharField(max_length=45) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) manufacturer = models.ForeignKey(Manufacturer, related_name='car_models', on_delete=models.CASCADE) class Car(models.Model): color = models.CharField(max_length=10, null=True) year = models.IntegerField(null=True, validators=[MinValueValidator(datetime.today().year-120), MaxValueValidator(datetime.today().year+1)]) num_passengers = models.IntegerField(validators=[MinValueValidator(1)], null=True) transmission = models.CharField(max_length=9, null=True) status = models.CharField(max_length=4, null=True) price = models.IntegerField(validators=[MinValueValidator(1)], null=True) bhp = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) city = models.ForeignKey(City, related_name='cars', on_delete=models.CASCADE) power_source = models.ForeignKey(PowerSource, related_name='cars', on_delete=models.CASCADE) model = models.ForeignKey(CarModel, related_name='cars', on_delete=models.CASCADE) For example, if I choose a manufacturer and leave other fields empy I should get all cars from that manufacturer regardless of color, year, etc. However, I … -
Multistepform with multiple images Django
Hi I am doing a multistepform in django that can add multiple image data (description and image). All my mutistepform is okay and adding to the database if it does not have add another entry button like my media. I would like to add multiple media files in the database. How can I achieve it? Below are my snippets of the codes. Models class IncidentMedia(models.Model): incident_general = models.OneToOneField(IncidentGeneral, on_delete=models.CASCADE) media_description = models.TextField(max_length=250, blank=True) incident_upload_photovideo = models.ImageField(default='user.jpeg', upload_to='incident_report/image') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.id Views def multistepformexample(request): # if request.method!="POST": # return redirect ('user_reports') profile = get_object_or_404(UserProfile, user=request.user) if request.method == 'POST': form = UserReportForm(request.POST or None, request.FILES or None) form_general = IncidentGeneralForm(request.POST or None, request.FILES or None) # form_people = IncidentRemarksForm(request.POST or None, request.FILES or None) form_media = IncidentRemarksForm(request.POST or None, request.FILES or None) form_remarks = IncidentRemarksForm(request.POST or None, request.FILES or None) try: if form.is_valid() and form_general.is_valid() and form_remarks.is_valid(): date=request.POST.get("date") time=request.POST.get("time") address=request.POST.get("address") city=request.POST.get("city") pin_code=request.POST.get("pin_code") latitude=request.POST.get("latitude") longitude=request.POST.get("longitude") description=request.POST.get("description") # accident_factor = AccidentCausation.objects.get(pk=request.id) # accident_subcategory = AccidentCausationSub.objects.get(pk=request.id) # collision_type = CollisionType.objects.get(pk=request.id) # collision_subcategory = CollisionTypeSub.objects.get(pk=request.id) # crash_type = CrashType.objects.get(pk=request.id) accident_factor1 = request.POST.get("accident_factor") accident_factor = AccidentCausation.objects.get(pk=accident_factor1) # accident_subcategory1 = request.POST.get("accident_subcategory") # accident_subcategory = AccidentCausationSub.objects.get(pk=accident_subcategory1) collision_type1 = request.POST.get("collision_type") collision_type = … -
Custom django CharField returns a Path instance
I have a model that tracks details of files (but does not serve the file itself). Currently, I am using a CharField to store the path, but it gets cumbersome to constantly convert that field to a Path instance. Model looks like this: class MyFile(models.Model): path = models.CharField(max_length=100) checksum = models.CharField(max_length=32) content_last_updated = models.DateTimeField(null=True) @property def is_image(self) -> bool: return Path(self.path).suffix == '.jpg' I tried to define a custom Field by subclassing CharField class PathnameField(models.CharField): def from_db_value(self, value, expression, connection): return Path(value) if value is not None else value If I substitute this field class in the model, nothing breaks but the field type is still a str. afile = MyFile.objects.create(path=Path('foo/bar.txt'), checksum='000') afile.refresh_from_db() assert isinstance(afile.path, Path) Has anyone tried this? -
save logs of database changes into database in django
I need to save log for changes of some tables into database so admin can read the logs and track users activities for example, I need to save logs of user table changes with these infos datetime chage happend, user who changed the user info (can be user him/her self or admin), fields that changed with their new values. this is my code the problem is, I don't know is this best practice?, is there any package for it, how can I access the user who made changes? and of course it is not just for user table. class CustomUser(AbstractUser): __pre_save_fields = {} def _get_field_value_dict(self): return {field.attname: getattr(self, field.attname, None) for field in self._meta.concrete_fields} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__pre_save_fields.update(self._get_field_value_dict()) def save(self, **kwargs): in_memory_field_value_dict = self._get_field_value_dict() changed_fields_new_value_dict = dict( filter(lambda t: self.__pre_save_fields[t[0]] != t[1], in_memory_field_value_dict.items()) ) super().save(**kwargs) self.__pre_save_fields.update(self._get_field_value_dict()) if changed_fields_new_value_dict: UserChangeLog.objects.create(insert_edit_by_user_id=1, last_data=str(changed_fields_new_value_dict)) class UserChangeLog(models.Model): datetime_created = models.DateTimeField(auto_now_add=True) insert_edit_by_user = models.ForeignKey(AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) last_data = models.TextField() -
centos7 django codes not showing
I wrote my codes. I took them to the server and along with that, I did the operations on this site (http://wiki.centos-webpanel.com/how-to-deploy-django-apps-using-apache-with-mod-wsgi-and-nginx). I am encountering this problem. How can i solve it. sites:www.diyetzone.com