Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError at /admin/services/blog/add/blog objects need to have a primary key value before you can access their tags
i'm trying to create a blog by the admin panell. but i'm not able to save. Can you please help. Model.py class blog(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) city_id = models.AutoField(primary_key=True) blog_title=models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) slug = models.CharField(max_length=500, blank=True) tags = TaggableManager() blog_category_name=models.ForeignKey(blog_category,on_delete=models.CASCADE,null=True,blank=True) blog_sub_category_name=models.ForeignKey(blog_sub_category,on_delete=models.CASCADE,null=True,blank=True) written_by = models.CharField(max_length=200, default='sandeep') image_banner= models.ImageField(upload_to='image_banner') medium_thumbnail = models.ImageField(upload_to='medium_thumbnail') content = RichTextField() # RichTextField is used for paragraphs is_authentic=models.BooleanField(default=False) class Meta: # Plurizing the class name explicitly verbose_name_plural = 'blog' def __str__(self): # Dundar Method return self.blog_title def save(self, *args, **kwargs): # Saving Modefied Changes if not self.slug: self.slug = slugify(self.blog_title) For some reason when I'm trying to save the tags and the data I'm getting this error -
How to select UserProfileInfo of a User with a certain PrimaryKey - Django
I'm using Django. In my function accept_request(), I'm trying to select the profile of a user with a certain PrimaryKey. Here's the function: def accept_request(request, pk): book = Book.objects.get(id=pk) print(book.owner.pk) user = request.user user_email = request.user.email owner_profile = UserProfileInfo.objects.get(user=book.owner.pk) owner_house_number = owner_profile.house_number owner_phone_number = owner_profile.phone_number owner_full_name = owner_profile.full_name r = UserRents.objects.get(book_id=pk) r.status = 1 r.save() subject = "{}, your request to rent the book, \"{}\", has been accepted.".format(user, book) body = "You had requested to rent the book, \"{}\". It's been accepted! You can head over to #{} to get the book. You can contact the owner, {}, at +91 {}. Please return the book in the same condition as it was when you got it.\n Hope you enjoy reading the book!".format(book, owner_house_number, owner_full_name, owner_phone_number) sender_email = "pfcbookclub@gmail.com" receiver_email = user_email password = "Zt2.~[3d*.[Y5&5r" # Create a multipart message and set headers message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message["Bcc"] = receiver_email # Recommended for mass emails # Add body to email message.attach(MIMEText(body, "plain")) text = message.as_string() # Log in to server using secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) return redirect("/") This … -
channel_layer.send won't call handler
I have this signal to dispatch an event when a new message is created from django.db.models.signals import post_save from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from django.dispatch import receiver from .serializers import MessageSerializer from base.models import Message @receiver(post_save, sender=Message) def new_message(sender, instance, created, **kwargs): channel_layer = get_channel_layer() if created: chat_group = instance.channel.chat_group for member in chat_group.members: async_to_sync(channel_layer.send)( f"User-{member.user.id}", { "type": "chat_message_create", "payload": MessageSerializer(instance).data, }, ) this is the consumers.py import json from channels.generic.websocket import WebsocketConsumer from api.serializers import UserSerializer class ChatConsumer(WebsocketConsumer): def connect(self): user = self.scope["user"] self.channel_name = f"User-{user.id}" self.send(text_data=json.dumps(UserSerializer(user).data)) def disconnect(self, close_code): pass def chat_message_create(self, event): print("Created") self.send(text_data=json.dumps(event["payload"])) When I create a new message in the admin panel the signal gets called but it does not get dispatched through the websocket, and any debug prints in ChatConsumer.chat_message_create won't even get printed. Thanks in advanced -
Using SearchVectorFields on many to many related models
I have two models Author and Book which are related via m2m (one author can have many books, one book can have many authors) Often we need to query and match records for ingests using text strings, across both models ie: "JRR Tolkien - Return of the King" when unique identifiers are not available. I would like to test if using SearchVectorField with GIN indexes can improve full text search response times - but since the search query will be SearchVector(author__name) + SearchVector(book__title) It seems that both models need a SearchVectorField added. This becomes more complicated when each table needs updating, since it appears Postgres Triggers need to be set up on both tables, which might make updating anything completely untenable. Question What is the modern best practice in Django for adopting vectorised fulltext search methods when m2m related models are concerned? Should the SearchVectorField be placed in the through table? Or in each model? I've been searching for guides on this specifically - but noone seems to mention m2ms when talking about SearchVectorFields. I did find this old question Also, if postgres is really not the way forward in modern Django I'd also gladly take direction in something better … -
Django manytomany filter with contains
I have groups in my app which can have multiple employees and multiple modules class GroupModels(models.Model): model_choices = (('Product', 'Product'), ('Kit', 'Kit'), ('Vendor', 'Vendor'), ('Warehouse', 'Warehouse')) model = models.CharField(max_length=500, choices=model_choices) class Group(models.Model): name = models.CharField(max_length=500, default=0) modules = models.ManyToManyField(GroupModels) employees = models.ManyToManyField(Employee) owner = models.ForeignKey(User, on_delete=models.CASCADE) Now while creating permissions for a particular module e.g. Product, I want to check if the user i.e. employee in any of the groups have this module. How do I do that ? I created two groups with the user, one contains the product and other doesn't and use this : abc = Group.objects.filter(employees__pk=request.user.pk, modules__model='Product').exists() print('abc', abc) return abc Is this the right way to do this? -
Django3 + Apache2. When I use the administrator to upload image in the background, I got Server Error (500)
I'm beginner in Django. In Django3 + Apache2, when I use the administrator to upload image in the background, I got Server Error (500). I go to check the accesslog, it show ""POST /admin/mainapp/product/add/ HTTP/1.1" 500 417". But when I use command "python3 manage.py runserver" to runserver, it work well. I don't know how to solve this probelm, Please help! Following is my code: setting.py from pathlib import Path import os SECRET_KEY = 'django-insecure-ppa-x(eyccb857-@uq$5qx$srwf#%$j4i-j7s=&m8mf0l@0#9_' DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainapp', ] 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', ] ROOT_URLCONF = 'web_2T4GAME.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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 = 'web_2T4GAME.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT = '/var/www/staticfiles' this DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = '/var/www/media' … -
Django rest framework - problem with set in settings subb app name
I have the same problem what is in this question, we're doing the same tutorial . I working on python 3.10.1, Django 4.0, django rest framework 3.13.0. When i try to change name in my category apps.py like Ankit Tiwari wrote, i get a error: ImportError: cannot import name '_Descriptor' from 'functools' (C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.496.0_x64__qbz5n2kfra8p0\lib\functools.py) But when I try like Jeet Patel nothing happens -
Update context of FormView only in certain condition
I have a code in my FormView in Django: class SearchView(LoginRequiredMixin, FormView): template_name = "dic_records/search_form.html" form_class = KokyakuForm success_url = 'search' fetched_data = [] def form_valid(self, form): print(form.cleaned_data) kokyaku_instance = FetchKokyaku(form.cleaned_data['name_search']) err_check = kokyaku_instance.connect() kokyaku_instance.get_data() if err_check is False: messages.error(self.request, "データを出力できませんでした") return super(SearchView, self).form_valid(form) kokyaku_list = list(kokyaku_instance.get_data()) if len(kokyaku_list) == 0: messages.error(self.request, "検索のデータを見つけられませんでした") return super(SearchView, self).form_valid(form) self.fetched_data = kokyaku_list return super(SearchView, self).form_valid(form) def get_context_data(self, **kwargs): """Use this to add extra context.""" context = super(SearchView, self).get_context_data(**kwargs) context['list'] = self.fetched_data return context And I would like to provide a list of value kokyaku_list to my context variable, but only if my form is valid and data are fetched from kokyaku_instance.get_data(). The code above wont pass values -
Django, anonymous user/not authenticated
I am anonymous user even though i logged in, here is views.py: class LoginView(views.APIView): def post(self, request): data = serializers.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) print(f" HEEERE::: {data}") if self.request.method == 'POST': if data.is_valid(): auth = authenticate( username=data.validated_data['email'], password=data.validated_data['password']) print(f" email check : {data.validated_data['email']}") print(f"auth:: {auth}") if auth is not None: login(request, auth) print("Hello World") return redirect("/somelink") else: return HttpResponse("Invalid Credentials") else: return HttpResponse("Data not being validated :O") class LogoutView(views.APIView): def post(self, request): logout(request) serializers.py class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField(write_only=True) def validate(self, data): email = data.get("email") print(f" email here : {email}") password = data.get("password") user = authenticate(username=email, password=password) print(f"{user} username serializer ") print(f"this is data : {data}") if user is not None: return data raise serializers.ValidationError("Incorrect Credentials") in frontend side (React): login component: import React, { useState } from 'react'; import { Link , Redirect} from 'react-router-dom'; import { connect } from 'react-redux'; import { login } from '../actions/auth'; import axios from 'axios'; import Cookies from 'js-cookie'; function Login(){ let [login,setLogin,isLoggedin] = useState({ email: '', password:'' }); let cookie = Cookies.get('csrftoken'); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ e.preventDefault(); axios.post(' http://127.0.0.1:8000/login/',login,{withCredentials:true},{headers: {'Content-Type': 'application/json', 'X-CSRFToken': cookie,'Access-Control-Allow-Origin':'*'}}) .then(res => { console.log(res.data); … -
prepopulated fields in django not working properly
class Theblog(models.Model): blog_image=models.ImageField(upload_to="home/images") blog_title=models.CharField(max_length=150) slug=models.SlugField(max_length=200) blog_description=models.CharField(max_length=200,default="Adsoptimiser") blog_body=RichTextField(blank=True,null=True) blog_date=models.DateTimeField() author=models.CharField(max_length=35,default="Sunil Kumar") blog_meta_keywords=models.TextField(default=" ") blog_meta_description=models.CharField(max_length=1000,default=" ") class BlogAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('blog_title',)} list_display = ('blog_title','blog_date') admin.site.register(metaTag) admin.site.register(Theblog,BlogAdmin) i want to prepulate the slug as the value of the title how to do it i have searchand get to see some ways i try to impliment but nothing is working for me please point out my mistake why this is happening -
Python - Applying condition on after decimal point (in dataframe column)
I have a dataframe which contains a column like below, total_hours 8.31, 5.15, 10.53, 8.69, 10.57, 10.53 14.25, 10.55, 0.0, 10.73, 8.54, 10.55, 0.0, 10.53, 10.52, 10.54 I have to apply condition after decimal point, Those conditions are, ( (<50)it will replace .0), and (>50) it will replace .5)). How can i do it properly??? Thanks in advance,.... -
Field clashes in django orm
I have some problems with Django ORM. I have three classes: transaction.py class Transaction(models.Model): class Status(models.TextChoices): PENDING = 'Pending' PROCESSING = 'Processing' CHARGED = 'Charged' AUTHORIZED = 'Authorized' CANCELLED = 'Cancelled' REJECTED = 'Rejected' ERROR = 'Error' ISSUED = 'Issued' amount = models.DecimalField(max_digits=6, decimal_places=2) # in USD status = models.CharField( max_length=15, choices=Status.choices, default=Status.PROCESSING, ) created_at = models.DateTimeField() updated_at = models.DateTimeField() from_account = models.CharField(max_length=16) to_account = models.CharField(max_length=16) payments.py class Payment(Transaction): order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return f"Payment {super().__str__()}" class Refund(Payment): payment = models.ForeignKey( Payment, on_delete=models.CASCADE, related_name='parent_payment' ) def __str__(self): return f"Refund payment={self.payment.id} {super(Transaction, self).__str__()}" And when I trying to do migration I have this error SystemCheckError: System check identified some issues: ERRORS: booking.Refund.payment: (models.E006) The field 'payment' clashes with the field 'payment' from model 'booking.transaction'. As I understand the problem related to inheritance and its specific in ORM, but I'm not sure -
blog objects need to have a primary key value before you can access their tags
[enter image description here][1] 1 1 i am trying to add blog by the admin. but i am not able to save. it looks some issue at my views. Can you please help. Model.py [enter image description here][2] this is the model.py file code [1]: https://i.stack.imgur.com/NzLUo.png view.py this is the view.py file code [2]: https://i.stack.imgur.com/FJBmN.png -
How to solve Django form attribute not working
All form attributes work fine, except on textarea. This is my code: # forms.py class VineyardForm(forms.ModelForm): class Meta: model = Vineyard fields = [ "name", "text", "wine_rg", "wines", "size", "grapes", "owner", "visits", "region", "regions", "cover" ] labels = { "name": "Vineyard or Property Name", "text": "Vineyard Description and Information", "wine_rg": "Wine Region and Country", } widgets = { "name": forms.TextInput(attrs={"placeholder": "Name of your vineyard..."}), "text": forms.Textarea(attrs={"placeholder": "something"}), "wine_rg": forms.TextInput(attrs={"placeholder": "Where is your vineyard located: region and country..."}), } When I look into the page inspector, I see this code: I think the problem is because I'm using ckeditor. Any suggestion? -
How to upload a file from an html into Django forms
Everytime I upload a file, forms.is_valid() = False. below is my views.py: def upload_pdf(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): # this is always FALSE!!! # write file into folder first text = handle_uploaded_file(request.FILES['file']) print("text") return HttpResponseRedirect('pdfExtractor_app/result.html') else: print("form not valid") form = UploadFileForm() return render(request, 'pdfExtractor_app/upload.html', {'form': form}) Here is my forms.py: from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() Here is my upload.html file: <body> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </body> I input a title and a file, but I get the form never gets read in views.py. This is what's I get form.errors <ul class="errorlist"><li>file<ul class="errorlist"><li>This field is required.</li></ul></li></ul> [15/Dec/2021 21:10:56] "POST /upload_pdf/ HTTP/1.1" This is what's in the Querydict: <QueryDict: {'csrfmiddlewaretoken': ['b123ASDDoddfkkdzrPXa5P2kKEsp7dBASXQWXfffwwdffgKGLGVVffML'], 'title': ['as'], 'file': ['UsabilityTest.pdf']}> Thank you! -
ValueError at /register/ save() prohibited to prevent data loss due to unsaved related object 'user'
I am building a site in django but my registration is not working whenever i click submit i face this error i am setting up a profile for an user i am not sure this the right way so if there are better ways to do this plese do comment ValueError at /register/ save() prohibited to prevent data loss due to unsaved related object 'user'. Please Help , also i am a beginner a brief answer would be very much apperciated Here is the view : def register(request): profiles = UserProfilePage() forms = CreateUser() if request.method == 'POST': profiles = UserProfilePage(request.POST, request.FILES) forms = CreateUser(request.POST) if forms.is_valid() and profiles.is_valid(): user = forms.save() profile = profiles.save(commit=False) profile.user = user profile.save() group = Group.objects.get(name='user') user.groups.add(group) username = forms.cleaned_data.get('username') password = request.POST.get('password1') user = authenticate(request, username=username, password=password) login(request, user) messages.success(request, 'Account was successfully created for ' + username) return redirect('Login_Page') ctx = { 'forms': forms, 'profiles': profiles, } return render(request, 'Register.html', ctx) Forms: class CreateUser(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ['username', 'email', 'password1', 'password2'] help_texts = { 'username': 'This is your identification value so it must be unique' } def __init__(self, *args, **kwargs): super(CreateUser, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = … -
How to efficiently set order data for a parent object and its subs with recursion using python?
I used django for a model named Topics and the table data in the mysql database with default order value 1 like this: id has_sub_topic parent_id subject_module_level order 1 0 NULL 1 1 2 0 NULL 2 1 3 0 NULL 3 1 27 1 NULL 25 1 28 0 27 25 1 29 0 27 25 1 31 1 NULL 25 1 32 0 31 25 1 33 0 31 25 1 34 0 NULL 25 1 40 1 27 25 1 41 1 40 25 1 42 0 41 25 1 43 0 40 25 1 44 1 40 25 1 45 0 44 25 1 47 1 44 25 1 48 0 47 25 1 I want to set the order data based on its subject_module and its parent. So, the data in the table would be like this: id has_sub_topic parent_id subject_module_level order 1 0 NULL 1 1 2 0 NULL 2 1 3 0 NULL 3 1 27 1 NULL 25 1 28 0 27 25 1 29 0 27 25 2 31 1 NULL 25 2 32 0 31 25 1 33 0 31 25 2 34 0 NULL 25 3 40 1 27 … -
How to use choices in a model from a table previously populated with a fixture
I have the following model: class Countries(models.Model): region = models.CharField(max_length=250, null=False, blank=False) country = models.CharField(max_length=250, null=False, blank=False, unique=True) I populate the model via python manage.py loaddata db.json (JSON fixture) After the model is populated, I would like to use those regions and countries as 'options' for another model field class Project(models.Model): project_code = models.CharField(max_length=250, null=False, blank=False) status = models.CharField(#when creating a new project: default - active max_length=250, null=True, blank=True, default=PROJECT_STATUS_DEFAULT, choices=PROJECT_STATUS, ) region = models.CharField( max_length=250, null=False, blank=False, default=, #I would like to use here the options available in the Countries model choices=, #I would like to use here the options available in the Countries model ) country = models.CharField( max_length=250, null=False, blank=False, default=, #I would like to use here the options available in the Countries model choices= #I would like to use here the options available in the Countries model ) I did some research and it is clear to me how to use choices from a constants.py file, but I have not found a good explanation on how to use it with previous populated models. -
py manage.py runserver prints 'Python'
command 'py manage.py runserver', 'py -m manage.py runserver' just print 'Python' py --version Python 3.9.5 you can inspect manage.py file below Can you help me please? I watched related question and tried some of them, but still have had no progress -
Django nGix webserver no accepts api post Cron Job
there is web gui running and the function the function add_analyzer_recods() is executed by a cron job because its testing some ip stuff in development all works fine, de script is executed and the webpages templates are displaying data in production I have a nGix server and the templates aree displaying propers but as soon the crone job executes a test script the script fails : HTTPConnectionPool(host='127.0.0.1', port=8000): do: python manange.py runserver fixes the problem but that is not a permanent solution , any idea how nGix can handle post request calls? def add_analyzer_recods(self, response, job, _uuid_session): api = "api" response = requests.post("http://127.0.0.1:8000/" + api, json=self.ser(response, job, _uuid_session), headers=self.build_headers()) urls.py urlpatterns = [ path(r'^api$', ApiCallView.as_view()),] -
Django cannot resolve field when annotating
I have the following model: from django.db import models from tvproject_api.models import TVUser class Watched(models.Model): tvuser = models.ForeignKey(TVUser, on_delete=models.CASCADE, related_name='watched_tvuser') show_id = models.IntegerField() season_id = models.IntegerField() date_added = models.DateTimeField() class Meta: unique_together = [['tvuser', 'show_id', 'season_id']] I'm trying to annotate the TVUser model with a count of this by doing, TVUser.objects.filter().annotate(watched_count=Count('watched_tvuser')) But this gives me, django.core.exceptions.FieldError: Cannot resolve keyword 'watched_tvuser' into field. Weirdly, I have another model that looks almost exactly like the Watched model: from django.db import models from tvproject_api.models import TVUser class Watchlist(models.Model): tvuser = models.ForeignKey(TVUser, on_delete=models.CASCADE, related_name='watchlist_tvuser') show_id = models.IntegerField() season_id = models.IntegerField() date_added = models.DateTimeField() class Meta: unique_together = [['tvuser', 'show_id', 'season_id']] And this works totally fine: TVUser.objects.filter().annotate(watched_count=Count('watchlist_tvuser')) Not sure what the problem here is. I'm able to annotate lots of different fields, but the one for watched_tvuser is the only one not working. -
Page with a dynamic number of forms, each form for each table row
The company has workers performing various activities during a day. Each activity has start_time and finish_time. It is usual that workers forget to beep the end of activity (finish_time) and that's because there is a stored procedure read_unended time_from time_to which reads records between time_from and time_to which has not finish_time (is NULL). For example id name day start_time finish_time place activity 38 Thomas 2021-12-03 2021-12-03 08:51:38.000 NULL p1 a1 28 Charles 2021-12-02 2021-12-02 12:29:03.000 NULL p2 a2 49 John 2021-12-06 2021-12-06 11:59:48.000 NULL p3 a3 68 Jessie 2021-12-08 2021-12-08 10:55:12.000 NULL p4 a4 82 Susanne 2021-12-10 2021-12-10 12:38:03.000 NULL p5 a5 There is a form in (forms.py) class FromToForm(Form): start_date = DateField(widget=AdminDateWidget()) start_time = TimeField(widget=AdminTimeWidget()) end_date = DateField(widget=AdminDateWidget()) end_time = TimeField(widget=AdminTimeWidget()) There is a view in (views.py) which displays such a table. def ending(req): from_to_form = FromToForm() result = [] context = { 'form': from_to_form, 'result': result } if req.method == "POST": from_to_form = FromToForm(req.POST) if from_to_form.is_valid(): start = datetime.combine(from_to_form.cleaned_data['start_date'], from_to_form.cleaned_data['start_time']).isoformat() end = datetime.combine(from_to_form.cleaned_data['end_date'], from_to_form.cleaned_data['end_time']).isoformat() with connections["mssql_database"].cursor() as cursor: cursor.execute("EXEC read_unended @dt_od='%s', @dt_do='%s'" % (start, end)) result = cursor.fetchall() context['result'] = result return render(req, 'ending.html', context) else: return render(req, 'ending.html', context) else: return render(req, 'ending.html', context) and an associated … -
Django / Cloudrun / Docker migration failed
I try to create a Django project on Google Cloud Plateform (Cloudrun). I'm following the official tutorial here : https://codelabs.developers.google.com/codelabs/cloud-run-django#7 As I'm trying to execute my first basic migration : gcloud builds submit --config cloudmigrate.yaml \ --substitutions _REGION=$REGION I have this error : Step #2: ModuleNotFoundError: No module named 'app' Here's my project's tree : And my settings.py file : import io import os import environ import google.auth from google.cloud import secretmanager as sm # Import the original settings from each template from .basesettings import * try: from .local import * except ImportError: pass # Pull django-environ settings file, stored in Secret Manager SETTINGS_NAME = "application_settings" _, project = google.auth.default() client = sm.SecretManagerServiceClient() name = f"projects/{project}/secrets/{SETTINGS_NAME}/versions/latest" payload = client.access_secret_version(name=name).payload.data.decode("UTF-8") env = environ.Env() env.read_env(io.StringIO(payload)) # Setting this value from django-environ SECRET_KEY = env("SECRET_KEY") # Allow all hosts to access Django site ALLOWED_HOSTS = ["*"] # Default false. True allows default landing pages to be visible DEBUG = env("DEBUG") # Set this value from django-environ DATABASES = {"default": env.db()} INSTALLED_APPS += ["storages"] # for django-storages if "app" not in INSTALLED_APPS: INSTALLED_APPS += ["app"] # for custom data migration # Define static storage via django-storages[google] GS_BUCKET_NAME = env("GS_BUCKET_NAME") STATICFILES_DIRS = [] DEFAULT_FILE_STORAGE = … -
How to include an attribute of a foreign key in the Django Admin 'Add' page?
I have two following models: models.py: class Coordinates(models.Model): lat = models.DecimalField(max_digits=7, decimal_places=5, null=True) lng = models.DecimalField(max_digits=7, decimal_places=5, null=True) def __str__(self): return f"(lat: {self.lat}, lng:{self.lng})" class Event(models.Model): //other attributes note = models.CharField(max_length=100, blank=True) coordinates = models.ForeignKey(Coordinates, on_delete=models.CASCADE, related_name="event_coordinates") def __str__(self): return f"{self.type} by {self.creator}. {self.number_of_people}/{self.people_needed}." admin.py: from django.contrib import admin from .models import * admin.site.register(User) admin.site.register(Event) What I need to do to show 'lat' and 'lng' fields from cooridinates inside Admin Add page? -
Change _id from ObjectId to normal unique auto increment integer
I am pretty new to Django and web development so all of this is new to me as I am learning. I recently had a Django site setup and working with Postgresql. When I created it, I over complicated things and needed to use Postgresql specifcally because of one of the fields it had that SQLite did not have. Anyways, I am going to redo it (v2) and want to convert to a MongoDB. Right now I have everything set up but I noticed when I create new items from my models in the admin panel, it gets _id:ObjectId("61ba69238db76b91b4bf42f1") in the database. I am guessing this is the primary key? However, Django from my understanding is looking for a normal integer value. So when I am trying to remove things or modify things it gives me the error: Field 'id' expected a number but got 'None'. Should I be creating my own "id" field for each model? Should/can the default _id field be used? Thank you!