Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom model form on admin tabular inline gives Integrity Error
I have made a custom model form so that I can change the header text: forms.py class AddRoomAddRoomExtrasForm(ModelForm): roomextrafields = forms.ModelChoiceField(queryset=RoomExtra.objects.all(), label=_('Room Extras')) class Meta: model = RoomExtra fields = ('roomextrafields', ) admin.py class RoomExtraInLine(admin.TabularInline): model = Room.roomextra.through extra = 1 verbose_name = _('extra') verbose_name_plural = _('extras') form = AddRoomAddRoomExtrasForm class RoomAdmin(admin.ModelAdmin): model = Room inlines = [RoomExtraInLine, ] exclude = ['roomextra', ] models.py class Room(models.Model): roomextra = models.ManyToManyField( to='hotel.RoomExtra', related_name='room_extras', ) but I get the error: IntegrityError at /admin/hotel/room/add/ NOT NULL constraint failed: hotel_room_roomextra.roomextra_id TRACEBACK Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/hotel/room/add/ Django Version: 2.2.9 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'users', 'hotel', 'reservation', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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') Traceback: File "/Users/leonhughes/Documents/virtualenvs/django/hlms/env/lib/python3.8/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) File "/Users/leonhughes/Documents/virtualenvs/django/hlms/env/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py" in execute 383. return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: hotel_room_roomextra.roomextra_id) was the direct cause of the following exception: File "/Users/leonhughes/Documents/virtualenvs/django/hlms/env/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/leonhughes/Documents/virtualenvs/django/hlms/env/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Users/leonhughes/Documents/virtualenvs/django/hlms/env/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/leonhughes/Documents/virtualenvs/django/hlms/env/lib/python3.8/site-packages/django/contrib/admin/options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/leonhughes/Documents/virtualenvs/django/hlms/env/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. … -
How to automatically update a field depending on the user who changed it in Django?
Context:In the Blog part of page any registered User can post, but all posts that are from non superuser accounts have to be approved by an admin on the Admin page where I registered the model as well. This functions as intended. My question: How can I make it so that if a Blog Post gets updated by a superuser(doesn't matter what kind of a change for example: when admin opens one single post and adds in a further text in the body of the post, or deletes some part of a text because it seems malicious or fake), that it is automatically approved(The field approved gets then set to TRUE)? I already thought of adding a further field in the model called changed_by and have it initially null. CODE: blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class BlogPost(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) approved = models.BooleanField(default=False) changed_by = models.ForeignKey(User, default=None) # I am planning to use this but how? def __str__(self): return self.title def get_absolute_url(self): return reverse('blogPost-detail', kwargs={'pk': self.pk}) blog/admin.py from django.contrib import admin from .models import BlogPost def approve_multiple_posts(modeladmin, request, … -
custom user model making the emails unique but not case sensetive?
so I have a custom user model to make the users sign up/in using emails instead of a username the problem is I grab the email as it's entered in the form and save and my model is assigning this field to be unique so it's case sensitive. so you see the problem if a user entered the email uppercase he can't log in till he enters the email similar to that of the signup page. my model class MyUser(AbstractUser): username = None email = models.EmailField(unique=True) the form class SignupForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = MyUser fields = ('email', 'password1', 'password2') and this is the view to send confirmation emails to the users def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your Sentizer account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( subject=mail_subject, body=message, to=[to_email], reply_to=[to_email],headers={'Content-Type': 'text/plain'}, ) email.send(fail_silently=False) messages.info(request,"Please confirm your email to be able to login") return HttpResponseRedirect(reverse_lazy('accounts:login')) else: form = SignupForm() return render(request, 'accounts/signup.html', {'form': form}) and thanks for ur help. -
Looking for a better way to do timezone based notifications in Django 3
I'd like to send an email to all users who have not entered a journal entry today. I'd like to give them until 8PM their local time to enter the journal entry, and got this working, but the code is fugly and I'm wondering if there's a more efficient way to accomplish my goal. I currently save the user's timezone offset when they sign up. <style> #clientTimezone { opacity: 0; width: 0; float: left; } </style> .... <form class="signup form-default row" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} <input type="text" name="client_timezone" id="clientTimezone" required /> .... <script> $(document).ready(function(){ var d = new Date(); $('#clientTimezone').val(moment().format('ZZ')) }) </script> And then the email code is in my dailyreminder.py management command, which triggers every 10 minutes. I'd like to continue doing this without using celery, if possible. import arrow from datetime import datetime, timedelta from django.utils import timezone from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternatives from django.conf import settings from dashboard.models import Entry from dashboard.emails import email_daily_reminder from redwoodlabs.models import UserProfile from identity.strings import GLOBAL_STRINGS LOCAL_TIME_TO_EMAIL = 20 # 8:00 PM MAX_LOCAL_TIME_TO_EMAIL = 24 # 12:00 AM USER_BATCH_SIZE = 10 class Command(BaseCommand): help = 'Email … -
How to have 2 domains with same codebase?
There should be two sites with the following domain and any port: domain.name1 domain.name2 Both of these sites should point to the single codebase. I want to create a common feature that will print "Hello World!" on the browser. domain.name1 should print "Hello World!" with a "Red" color. domain.name2 should print "Hello World!" with a "Green" color. I have no idea where to start exactly. Help would be appreciated. -
I need help in models.py
I have an issue in my code I have made coupon system in the website and I want to make sure that client use code only one time and if he enters again did not add the points in his profile any suggestion, I tried to make a list and append the name of the customer if he take the points but it does not work. -
What change the name of file my frontend search from backend?
My backend is using Django. My static files is using https://docs.djangoproject.com/en/3.0/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.StaticFilesStorage to storage my internal files. When i access my files from my site, the request search for this file: internal.6a7c4d7e1c1e.css. This name is generated somehow i don't know in my front. The problem is, a week ago my site is going without any erros. But when i tag my commit to 0.0.1 and i make my release the site is looking for this internal.4188f59d19d7.css. But this file don't exists im my folder and the site goes without styles. The Django put all my static files to /home/developer/collected_static/. The main.css (Which is my principal file is there). Also i have other files internal files like: external.004173246553.css internal.241e6043ba27.css internal.6a7c4d7e1c1e.css internal.a9a9e1a85ca5.css internal.f6d3eedfe205.css main.2bd12da67323.css main.81c12e8cbd67.css main.d3f7640e234d.css external.009bd21e09d2.css internal.2d4b4f251635.css internal.7092cae68a42.css internal.b173cdd8c8ff.css main.048ff141018e.css main.431950216205.css main.88db1011af20.css main.d6e12dd31035.css..... From another releases but these others releases i don't tag my commit. I understanding the necessity of these files: from Django: The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server..... But i dont understanding why he is looking for a file that's not there, … -
ajax + django, random on click button
I have a little problem whit using django and ajax. Haave a code views.py def rand(request): data = {} action = request.POST.get('action') if action == 'NeedRandom': data['result'] = random.randint(0,1000000) else: data['result'] = 'Error' return render(request, 'registers/myaction.html', data) urls.py urlpatterns = [ path('myaction/', views.rand, name='my-action'), ] and some one script $(document).ready(function(){ // Forming csrf_token function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie != '') { let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }; let data = {} $('.mybutton').on('click', function(e){ data['action'] = 'NeedRandom'; data['csrfmiddlewaretoken'] = getCookie('csrftoken'); SendAjax(); }); function SendAjax(){ $.ajax({ url: 'http://localhost:8000/myaction', method: 'POST', data: data, cached: true, success: function(data){ console.log(data); }, error: function(e){ console.log(e); } }) } }) And buttom at files myaction.html {% extends 'base.html' %} {% block content%} <input type="submit" class="mybutton" value="random number"> {% endblock %} when i click on the button i have at template page html code, but not random number why? who can help me? -
cannot access variables defined before for loop
I cannot access variables which is defined before for loop even though i tried printing them after condition they are not printing. Please help how can I access those variable in my for loop. I want to check condition for appending in a list. I tried putting global in for loop this is giving me error "global variable assigned before declaration" cal = dp[0].goal_id.calories if cal == '1500': bf = 250 lu = 500 prw = 150 pow = 150 d = 450 elif cal == '2000': bf = 400 lu = 500 prw = 200 pow = 400 d = 500 checkrandom = [] for i in range(0,len(dp)): if total_cal < int(dp[i].goal_id.calories): if dp[r].day_time == 0 and breakfast < bf: print('bf') list.append([j,dp[r].name,dp[r].calories,'Breakfast']) breakfast = breakfast + dp[r].calories if dp[r].day_time == 1 and lunch < lu: print('lunch') list.append([j,dp[r].name,dp[r].calories,'Lunch']) lunch = lunch + dp[r].calories if dp[r].day_time == 2 and pre_workout < prw: print('preworkout') list.append([j,dp[r].name,dp[r].calories,'Pre-Workout']) pre_workout = pre_workout + dp[r].calories if dp[r].day_time == 3 and post_workout < pow: print('postworlpit') list.append([j,dp[r].name,dp[r].calories,'Post-Workout']) post_workout = post_workout + dp[r].calories if dp[r].day_time == 4 and dinner < d: print('dinner') list.append([j,dp[r].name,dp[r].calories,'Dinner']) dinner = dinner + dp[r].calories else: break print(list) return render(request,'diet_plan.html',{'table':list}) -
NoReverseMatch at /accounts/login
I am trying to make a login page just like i've made a register page on django but i don't no for what reason it's is saying that the url is not found the error and the files i'm working in -
Using FCM with diango and flutter
I have a django backend server and I want to send notification to my flutter app. I want to use Firebase Cloud Messaging for this. My question is, do I need to store something in my database to send notification to the app? I was planning to use django_push_notification on the backend side. -
Django static files does not load while in the root directory
I am new to django and i store my static files in root dir then i can't make them load on the browser. configurations settings.py STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR = [ STATIC_DIR, ] template file <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Index</title> </head> <body> <h1>{{temp}}</h1> <h2><a href="#">Click here</a> to veiw user details</h2> <img src="{% static "user/images/smile.png"%}" alt="oh oh didn't show"/> </body> </html> -
this.$apollo always undefined
I'm trying to use apollo (+ vue, django) but for some reason it won't get loaded/used in a component,this.$apollo is always undefined. <script> import { GET_ALL_USERS_QUERY } from '../js/graphql/queries/userQueries.js' export default { name: 'GraphQLTest', data() { return { users: [], loading: true } }, async mounted() { this.loading = true this.users = await this.$apollo.query({ query: GET_ALL_USERS_QUERY }) this.loading = false } } </script> [Vue warn]: Error in mounted hook (Promise/async): "TypeError: Cannot read property 'query' of undefined" main.js import Vue from 'vue' import { router } from './routes.js' import store from './store.js' import { createProvider } from './apollo.js' import App from './App.vue' Vue.config.productionTip = false new Vue({ router, store, provide: createProvider(), render: h => h(App), }).$mount('#app') Why is apollo never loaded? something missing in the config? -
"Permission denied" when trying to access static files after deployment
Having issues loading static files in my django app after deployment. I know I am supposed to set static_root as the path to where I want to create the static folder and then run python manage.py collectstatic (not sure if I have to do this if I already have a static folder). Here is the structure of my project gradboost -->__pycache__ -->classroom __init__.py apps.py decorators.py forms.py models.py urls.py ------>templates ------>templatetags -->django_school __pycache__ __init__.py settings.py urls.py wsgi.py -->public -->static -->templates -->tmp manage.py passenger_wsgi.py public_html This is what I currently have on settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = '/gradboost/public/static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Running collectstatic returns this error message PermissionError: [Errno 13] Permission denied: '/gradientboostmvp' -
Elastic Beanstalk error while deploying Django project
I'm getting the following error. [Tue Jan 21 16:04:55.908186 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] mod_wsgi (pid=2102): Exception occurred processing WSGI script '/opt/python/current/app/vspmschool/vspmschool/wsgi.py'. [Tue Jan 21 16:04:55.908338 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] Traceback (most recent call last): [Tue Jan 21 16:04:55.908382 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] File "/opt/python/current/app/vspmschool/vspmschool/wsgi.py", line 16, in <module> [Tue Jan 21 16:04:55.908387 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] application = get_wsgi_application() [Tue Jan 21 16:04:55.908393 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Tue Jan 21 16:04:55.908404 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] django.setup(set_prefix=False) [Tue Jan 21 16:04:55.908410 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup [Tue Jan 21 16:04:55.908413 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Jan 21 16:04:55.908419 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ [Tue Jan 21 16:04:55.908422 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] self._setup(name) [Tue Jan 21 16:04:55.908427 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup [Tue Jan 21 16:04:55.908430 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] self._wrapped = Settings(settings_module) [Tue Jan 21 16:04:55.908435 2020] [:error] [pid 2102] [remote 127.0.0.1:17592] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ [Tue Jan 21 16:04:55.908438 2020] [:error] … -
Django + Celery application on Heroku works locally but worker timeout when deployed
I have a Django + Celery application using RabbitMQ that works fine locally (when calling heroku local), but fails to execute tasks when deployed. There seems to be an a 'worker timeout' that occurs each time the task is called. The versions of the components: Django (3.0.1), celery (4.4.0). The Heroku logs: 2020-01-21T15:38:48.828631+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="<REDACTED>" host=<REDACTED> request_id=c59b92be-9b39-4a36-a1d0-e646c9b1f694 fwd="<REDACTED> " dyno=web.1 connect=1ms service=30000ms status=503 bytes=0 protocol=https 2020-01-21T15:38:49.822330+00:00 app[web.1]: [2020-01-21 15:38:49 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:10) 2020-01-21T15:38:49.823866+00:00 app[web.1]: [2020-01-21 23:38:49 +0800] [10] [INFO] Worker exiting (pid: 10) 2020-01-21T15:38:49.982428+00:00 app[web.1]: [2020-01-21 15:38:49 +0000] [14] [INFO] Booting worker with pid: 14 The RabbitMQ worker according to the logs seems to be running fine: 2020-01-21T15:33:53.899791+00:00 app[worker.1]: [2020-01-21 23:33:53,899: INFO/MainProcess] mingle: searching for neighbors 2020-01-21T15:33:54.969851+00:00 app[worker.1]: [2020-01-21 23:33:54,969: INFO/MainProcess] mingle: all alone 2020-01-21T15:33:55.055792+00:00 app[worker.1]: [2020-01-21 23:33:55,055: INFO/MainProcess] celery@aaec950b-24bd-4d29-8c43-c8eeb71e58de ready. Procfile: web: gunicorn gotcha.wsgi --log-level debug worker: celery -A gotcha worker -l info I've tried running a simple task (just prints a string) on Heroku via the heroku run python manage.py shell command, and that also seemed to run without stopping. Force exiting results in the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/kombu/utils/functional.py", line 43, in __call__ return self.__value__ … -
How can I rewrite these 2 views to 1 view?
How can I rewrite these 2 views to 1 view? serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'first_name', 'last_name', 'email', 'gender', 'ip_address', ] class StatisticSerializer(serializers.ModelSerializer): class Meta: model = Statistic fields = ['clicks', 'page_views', 'date'] class UserStatisticSerializer(serializers.Serializer): user = serializers.SerializerMethodField() max_date = serializers.SerializerMethodField() min_date = serializers.SerializerMethodField() def to_representation(self, instance): ... return data views class UserListApiView(ListAPIView): serializer_class = UserSerializer queryset = User.objects.all() pagination_class = UsersSetPagination class StatisticAPIView(RetrieveAPIView): serializer_class = UserStatisticSerializer queryset = User.objects.all() models class User(AbstractUser): username = models.CharField(max_length=40, blank=True, null=True) email = models.EmailField(unique=True, db_index=True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=GENDER_MALE) ip_address = models.GenericIPAddressField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class Statistic(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='statistics') date = models.DateField(db_index=True) page_views = models.PositiveSmallIntegerField() clicks = models.PositiveSmallIntegerField() -
What is the rule for default value in Django fields?
I scratch my head trying to figure out why a default value is required on some but not all fields. For example the documentation says models.CharField() has only one mandatory option which is max_length but python manage.py makemigration return an error when a default value isn't provided. And I have the same error for some of my models.ForeignKey() fields. Could you explain why and when a default value should be provided? models.py class Algo(models.Model): strategy = models.ManyToManyField(Strategy, related_name='strategy') name = models.CharField(max_length=12) # <-- Return an error !? class Meta: verbose_name_plural = "algos" def __str__(self): return self.name -
How to get label value on view in django
I just want to know how can I post label value on Django view. like I can get textbox value using request.POST['textboxname'] -
How to implement video calls over Django Channels?
I would like to create an app that enables users to make video calls. I found some insight here, but unfortunately, the answer doesn't explain neither what third party services can be used, nor any meaningful insight on integrating WebRTC. I have managed to create a Django WebSocket based live chat using Channels, and I figured the "get user media". But I was totally overwhelmed by Peer2Peer connection. How can I integrate the WebRTC over Django Channels? Or is there a simpler way/third party service I could use? my consumers.py: from channels.generic.websocket import AsyncWebsocketConsumer from channels.consumer import AsyncConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name self.user = self.scope["user"].username # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] user = text_data_json['user'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': user } ) # Receive message from room group async def chat_message(self, event): message = event['message'], user = event['user'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': … -
Django - Clone model object in Class based ListView
I have a list.html with lots of records and a column containing a button to clone the specific record like this {% for betr in object_list %} .... <td><button type="button" class="btn btn-first" onclick="window.location='../clone/{{betr.ID}}';"><span class="fas fa-copy" style="font-size: 1rem;"></span></button></td> {% endfor %} my urls.py looks like this urlpatterns = [ ... path('update/<int:pk>/', UpdateView.as_view(), name='update'), path('clone/<int:pk>/', CloneView.cloneRecord(), name='clone'), ... ] and my views.py contains a clone view with a function to clone the record and open the UpdateView with the cloned record for editing class CloneView(LoginRequiredMixin): login_url = '/accounts/login/' model = mymodel def cloneRecord(self,**kwargs): record = mymodel.objects.filter(id=self.request.GET['ID'])[0] record.id = None record.save() return http.HttpResponseRedirect(reverse('/update/', kwargs={'pk':record.id})) At the moment i am receiving following error TypeError: cloneRecord() missing 1 required positional argument: 'self' What am i missing? Any help is appreciated. -
How can I include a ManyToMany field into django admin fieldsets?
I have two models: Python 3.7 class ClassOne(models.Model): name = models.CharField(max_length=10, default='') class ClassTwo(models.Model): name = models.CharField(max_length=20, default='') class_ones = models.ManyToManyField(ClassOne) Now I would like to show ClassOne in django-admin with all ClassTwo's listed. I already tried to create a Tabular (admin.TabularInline) or create a method in ClassOne as following: def get_class_twos(self): return self.classtwo_set.all() and include that method in the fieldsets, but that did not work either. Neither did directly putting classtwo_set.all() or classtwo_set in the fieldset list. -
How to render django formset in row
I would like to render each form in a django formset into x amount of forms per row. For example, if the formset has 5 forms to display, I would like two forms in the 1st row, two forms in the 2nd row, and the last one in the 3rd row. Bear in mind that I would want to specify the max number of forms per row. So far, this is what I have: <form method="POST" enctype="multipart/form-data" style="margin-left: 40px; margin-right: 40px"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors }} {% for forma in formset.forms %} {% cycle 'row1' 'row2' %} <div class="card "> <div class="card-header bg-secondary"> {{ forma.attackPatternID.value }} : {{ forma.attackPatternName.value }} </div> <div class="card-body"> {{ forma.attackPatternRating }} {{forma.selectionReason }} </div> <div class="card-footer"> {{ forma.attackPatternID.value }} : {{ forma.attackPatternName.value }} </div> </div> {% endfor %} <input class="btn bg-success" type="submit" value="Update" /> </form>``` But I am still getting the each form in the formset 1 per row. If there is a form in the formset, I would first create card a bootstrap card to the form fields in the card-body. This is what I would like: Form 1 Form 2 Form 3 Form 4 Form 5 But I am … -
How to rename GraphQL type field autogenerated from Django model?
I've a model in Django with some fields. Let's say this exemplary one: # <app>/models.py from django.db import models class Something(models.Model): first_field = models.Charfield() second_field = models.Charfield() I use DjangoObjectType from graphene_django to map Django models to GraphQL types. # <app>/schema.py from graphene_django import DjangoObjectType from .models import Something class SomethingType(DjangoObjectType): class Meta: model = Something Cause of auto camelcasing the model field second_field results in secondField in the GraphQL type. Now I'd like to rename the GraphQL type field from secondField to somethingFancy. How can I get this done easiest? -
Allow to create ForeignKey relation under specific condition
I am struggling with given scenario. I have a following model: class Location(models.Model): COUNTRY = 1 REGION = 2 region_type_choices = ((COUNTRY, 'country'), (REGION, 'region')) name = models.CharField(max_length=120, blank=False) country_code = models.CharField(max_length=10, blank=False) region = models.CharField(max_length=10, choices=region_type_choices) is_recommended = models.BooleanField(default=False) countries = models.ForeignKey('Location', related_name='related_countries', on_delete=models.DO_NOTHING) What I'd have to achieve here is: you can only add a new object to countries relation if a Region instance you are trying to add has region attribute set to country and the base instance is set to region. In example: country = Location(name='test', region=1) region = Location(name='test2', region=2) region2 = Location(name='test3', region=2) region.related_countries.add(country) <-- this is valid country.related_countries.add(region) <-- this is invalid region.related_countries.add(region2) <-- this is also invalid Is this even possible to achieve with single table in Django? I've already tried overriding post_save and save signals but that didn't seem to work. I'd appreciate any tips.