Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save() saves all fields except ManyToMany field
I have a model "Contest" with one m2m field called "teams" which is related to a model "Team". I overrided the method save. In my save() function (the one that's overriding), I need a queryset (in my save overrinding function) with all the objects related to my team m2m field. The code is self.teams.all() but it won't work because my models is not yet registered in database right ? So I call super().save(*args, **kwargs) now my models is saved and I can get my queryset ? I can't. The queryset is empty, even if I registered team(s). <QuerySet []> Why does super.save() save immediately all the fields except the m2m ? I use exclusively the django admin web site to create models. No manage.py shell or form. My model : class Contest(models.Model): name = models.CharField(max_length=16, primary_key=True, unique=True, default="InactiveContest", blank=True) # Ex: PSGvMNC_09/2017 id = models.IntegerField(default=1) teams = models.ManyToManyField(Team, verbose_name="opposants") date = models.DateTimeField(blank=True) winner = models.ForeignKey(Team, verbose_name='gagnant', related_name='winner', on_delete=models.SET_NULL, blank=True, null=True) loser = models.ForeignKey(Team, verbose_name='perdant', related_name='loser', on_delete=models.SET_NULL, blank=True, null=True) bet = models.IntegerField(verbose_name='Nombre de paris', default=0, blank=True, null=0) active = models.BooleanField(default=False) def save(self, *args, **kwargs): if self._state.adding: self.active = False # Django's id field immitation last_id = Contest.objects.all().aggregate(Max('id')).get('id__max') if last_id is not … -
What's the best way to desplay list of inons using Django?
I'm working on a small project where I have a table named 'icons' that contains paths for stored icons inside folder 'mydjangoproject/app/icons' and I have an endpoint "mydomainname.com/user/icon/< name >" I want the user to be able to replace with the icon that he wants and he gets in return the icon For example if the user took this link mydomainname/user/icon/car.png and used it in an tag or typed it in the browser it would work and show that specific icon What is the best way to do that? -
POST http://localhost:8000/add_new/ 500 - Django
I have a question about django. In my ecommerce website I am trying to add add to cart function. My code is working and I can add to the cart with AnonymousUser. But, when i try to add to cart when I logged in with account, I am having this error: error: Internal Server Error So, it's adding to the cart, but location.reload is not working. I need to restart manually. What is the problem? Please, help! -
Django DetailView dont show data in template
I am completely new to Django CBV and I don't understand why I can't display data in template with using DetailView. I have no errors, just can't display any data in template. I have spent hours trying to figure it out, but I am slowly giving up This is my model: class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title views.py: class ProjectListView(ListView): model = Project class ProjectView(DetailView): model = Project template_name = 'base/single-project.html' (I have tried with get_context_data() and get_object() but the effect was the same) urls.py: urlpatterns = [ path('', ProjectListView.as_view(), name='projects'), path('project/<str:pk>/', ProjectView.as_view(), name='project'),] and the template: {% extends 'main.html' %} <p>{{ object }}</p> <p>{{ object.title }}</p> <p>{{ project.title }}</p> <p>{{ project }}</p> (Here I just tried to see anything) -
My images are not displaying the post.photo.url call on my cpanel hosting
Hello I just put my blog online on cpanel hosting. I managed the display with the whitenoise library of python. The static images work normally. But when I call the image from blogpost to display my image does not appear with post.photo.url. I am under cpanel and I would like to ask for your help to display the images of my blog on my site class Photo(models.Model): image = models.ImageField(verbose_name='image') caption = models.CharField(max_length=128, blank=True, verbose_name='légende') date_created = models.DateTimeField(auto_now_add=True) IMAGE_MAX_SIZE = (1900, 1265) def resize_image(self): image = Image.open(self.image) image.thumbnail(self.IMAGE_MAX_SIZE) image.save(self.image.path) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.resize_image() def __str__(self): return self.caption My models.py class BlogPost(models.Model): slug = models.SlugField() categorie = models.ForeignKey(CategorieBlogs, on_delete=models.CASCADE) image = models.ForeignKey(Photo, on_delete=models.CASCADE) title = models.CharField(max_length=500, verbose_name="titre blog") subtitle = models.CharField(max_length=500, verbose_name="sous titre") contenu = models.TextField(max_length=1500, verbose_name="contenu blog") description = models.TextField(max_length=2000, verbose_name="contenu blog 2") titles = models.CharField(max_length=500, verbose_name="titre 2") photo = models.ImageField(upload_to="photo blog") contenus = models.TextField(max_length=2000, verbose_name="paragraph 2", blank=True) descriptions = models.TextField(max_length=2000, verbose_name="paragraph contenu 2", blank=True) datepub = models.DateField(verbose_name="Date de publication", auto_now_add=True) published = models.BooleanField(default=False) auteur = models.ForeignKey(AuteurPost, on_delete=models.CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("posts:home") def __str__(self): return self.title class Meta: ordering = ['-datepub'] verbose_name = "Blog" My … -
Django apache doesn't work when using a virtual environment
I am trying to deploy my django project on a linux ubuntu server using apache2. I can deploy it correclty when I dont use a virtual venv. I rebuilt my VM and did the same thing but with using a virtual env and it not working. When I visit my website url it give me this error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. here is my /etc/apache2/sites-available/mysite.conf <VirtualHost *:80> ServerName MYIPSERVER ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite/venv/lib/python3.10/site-packages WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /static/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> </VirtualHost> Before without the venv the WSGIDaemonProcess was setup like this WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite but it wasn't working so I changed it for that: WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite/venv/lib/python3.10/site-packages and it still not working. I am not sure where the problem is coming from. my project folder is located into /var/www -
Django - Keep specific fields on form after submit
I have a view that has a simple "save and add another" functionality, that redirects the user to the same page after submit the form. View: def new_planning(request): form = PlanningForm(request.POST) if form.is_valid(): form.save() if 'another' in request.POST: messages.success(request, ('Success!')) return redirect('new_planning') else: return redirect('list_planning') return render(request, 'pages/planning/new_planning.html', context={ 'form': form, }) Form: class PlanningForm(forms.ModelForm): accountplan = ModelChoiceField( queryset=AccountsPlan.objects.filter(active=True).order_by('code'), ) month = forms.DateField( required=True, error_messages={'required': '', }, ) amount = forms.DecimalField( max_digits=9, decimal_places=2, required=True, validators=[ error_messages={'required': '', }, ) class Meta: model = Planning fields = '__all__' The function works as expected and after the submit, the same page is rendered with a blank form. What I want is to keep just the "amount" field blank and keep the data typed in the "accountplan" and "month" fields. Is there a way to do this? I read about instance in the docs, but it doesn't seem to be what I looking for, since I don't want to get the data from the database (if that's possible), but simply keep the last inputs typed in both fields. -
DJANGO - How can i make the statics folder accessible on deploy
in the admin screen, I can access CSS and JS files by typing their url locally but i can't when it is deployed. this is how it works locally this is how it works deployed Online it takes me to the 404 screen while locally it returns the raw file (as i am trying to do) these are my settings for static files in Settings.py STATIC_URL = 'guias/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'guias/static') thanks everyone :D -
Django ._meta and adding to ManyToMany fields
I haven't had much luck finding other questions that helped with this, but apologies if I missed something and this is a duplicate. I'm trying to add to some ManyToMany fields, without having to explicitly type out the names of the fields in the code (because the function I'm working on will be used to add to multiple fields and I'd rather not have to repeat the same code for every field). I'm having a hard time using ._meta to reference the model and field objects correctly so that .add() doesn't throw an "AttributeError: 'ManyToManyField' object has no attribute 'add'". This is simplified because the full body of code is too long to post it all here, but in models.py, I have models defined similar to this: class Sandwich(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) veggies = models.ManyToManyField(Veggie) meats = models.ManyToManyField(Meat) class Veggie(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) class Meat(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) Once instances of these are created and saved, I can successfully use .add() like this: blt = Sandwich(name='blt') blt.save() lettuce = Veggies(name='lettuce') lettuce.save() tomato = Veggies(name='tomato') tomato.save() bacon = Meat(name='bacon') bacon.save() blt.veggies.add(lettuce) blt.veggies.add(tomato) blt.meats.add(bacon) But if I try to use ._meta to get blt's fields and add to them that way, I … -
Django signals don't work with DEBUG=False
I have the following code that work fine in development mode with DEBUG=True. In a nutshell - signal should invalidate a cache. The project running Django 4.0, Python 3.9. signals.py from django.core.cache import cache from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from apps.hub.models import Comment, Marker @receiver(signal=post_delete, sender=Marker, dispatch_uid="marker_deleted") def clear_cache_delete_handler(sender, **kwargs): """Method for clearing a cache on home page after Marker instance has been deleted.""" cache.delete("markers_frontend") @receiver(signal=post_save, sender=Marker, dispatch_uid="marker_updated") def clear_cache_save_handler(sender, **kwargs): """Method for clearing a cache on home page after Marker instance has been updated.""" cache.delete("markers_frontend") I connect them in apps.py from django.apps import AppConfig class HubConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apps.hub' def ready(self): """Register all signals.""" # Implicitly connect a signal handlers decorated with @receiver. from . import signals But whether I set DEBUG=False, signals don't work and as a result cache is not invalidates. I tried both - local machine and a hosting server. Result is the same. What is wrong? -
Django doesn't redirect to the same page
I'm working on a django project website. When submitting a form I need to save the data and show a message with from django.contrib import messagesmodule. It works perfectly with saving data but it never shows the message and redirecting to the same page. Views.py class. def showIndex(request): if request.method == 'POST': contact = Contact() name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') contact.name = name contact.email = email contact.message = message print('yes and no ') messages.success(request, 'Profile details updated.') contact.save() return render(request,'index.html') return render(request,'index.html') and this is the codes in index.html. I have created the form here. <form method="POST" class="u-clearfix u-form-spacing-30 u-form-vertical u-inner-form" style="padding: 10px"> {% csrf_token %} <div class="u-form-email u-form-group u-form-partition-factor-2"> <label for="email-319a" class="u-label u-text-body-alt-color u-label-1">Email</label> <input type="email" placeholder="Enter a valid email address" id="email-319a" name="email" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" /> </div> <div class="u-form-group u-form-name u-form-partition-factor-2"> <label for="name-319a" class="u-label u-text-body-alt-color u-label-2">Name</label> <input type="text" placeholder="Enter your Name" id="name-319a" name="name" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" /> </div> <div class="u-form-group u-form-message"> <label for="message-319a" class="u-label u-text-body-alt-color u-label-3">Message</label> <textarea placeholder="Enter your message" rows="4" cols="50" id="message-319a" name="message" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required=""></textarea> </div> <div class="u-align-left u-form-group u-form-submit"> <a href="#" class="u-btn u-btn-submit u-button-style u-white u-btn-2">Submit</a> … -
How to access return value from apscheduler in a long process function?
Similar topic has been asked before, but my question is different. I want to get the fisrt function's return as a signal to trigger the second function, and the first function need run 2 minutes before it completed. def first_func: #long time run logic here #then has a return return signal def second_func: if 'success string' in signal: #do something def scheduler_func(request): try: scheduler = BackgroundScheduler() # Schedule the load process scheduler.add_job(first_function) scheduler.start() return render(request, 'customer/customer_base.html') except: pass finally: second_func() I have tried use global signal,but the second function not able to get the signal. -
Django ModuleNotFoundError: No module named 'fcm-django' error
I am trying to set up Firebase Cloud Messaging with my Django Rest Framework Backend for sending push notifications, however I keep getting ModuleNotFoundError: No module named 'fcm-django' error when I run python manage.py migrate I have already installed fcm-django using pip install fcm-django This is the error: Traceback (most recent call last): File "C:\Users\Admin\Desktop\DigiLab-Back-End\manage.py", line 22, in <module> main() File "C:\Users\Admin\Desktop\DigiLab-Back-End\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\apps\config.py", line 228, in create import_module(entry) File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'fcm-django' This is what I have done in my Settings.py to integrate FCM from firebase_admin import initialize_app INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Profiling.apps.ProfilingConfig', 'Appointments.apps.AppointmentsConfig', 'Chattings.apps.ChattingsConfig', 'Finance.apps.FinanceConfig', 'Feedbacks.apps.FeedbacksConfig', 'Inventory.apps.InventoryConfig', 'Settings.apps.SettingsConfig', 'Authentication.apps.AuthenticationConfig', 'fcm-django', 'rest_framework', 'corsheaders', ] FIREBASE_APP = initialize_app() FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "test", # true if you want to have only one … -
Why is Django test throwing an error complaining about a column size that is incorrect when I try to run tests?
I have an old project that I'm resurrecting that was built with Python 2. I'm getting it going with a more current version of Python and Django (v3.9 and v4.1.2 respectively). I have the app basically up and running and I just tried to get the automated testing going. But I'm getting this error: django.db.utils.OperationalError: (1074, "Column length too big for column 'body' (max = 16383); use BLOB or TEXT instead") Unfortunately, I have the 'body' column in multiple objects in my models.py, AND each of them is defined as a TextField (e.g. body = models.TextField()). I'm not sure how to post the offending code since the error doesn't specify the exact object. My test is simple as I'm just trying to get testing going: from django.test import TestCase class Test_Countries(TestCase): def setUp(self): pass def test_basicCompare(self): self.assertEqual(1, 1) Before running the test (python manage.py test IFSServices/tests), I've ensured that makemigrations and migrate have succeeded. Any help that anybody could provide to help (incl how to ask a more useful question) would be greatly appreciated. -
django filter: How to filter results with multiple values
I am working on Django and I need to filter records eg: table: Person name age David Abraham Benj 18 so, if I run this, Person.objects.filter(name__icontains="David Abraham") it is working but if I run this, Person.objects.filter(name__icontains="David Benj") it is not working any idea how it works? framework: Django and SQL: Postgres -
Django huey file not processing all tasks
This is very strange. I don't want to setup a Redis service and since my queue has only very little requirements file or sqlite would work just fine. The both work fine on localhost, but when I deploy it to a docker container there are the following issues: SQLite compains that there is an I/O error. The path is set to /tmp, which has read/write permissions. I read that there are issues with CIFS filesystem, not sure if this is the case. Fact it, it doesn't work. Filesystem queue. Tasks are created in the folder, the consumer is starting to process them, but then just stops. Consumer is still running, but not processing any files anymore. Any advice on where to start looking would be appreciated. -
DJango-How to merge two variables together and send them as an argument to the url?
url: 127.0.0.1:8000/name/ url has one parametr, name but name is first_name + last_name in template we resive first_name and last_name How to merge two variables (first_name and last_name) together and send them as an argument (name) to the url??? -
Annotate results from related model method onto model Queryset?
I'm trying to figure out the best / most efficient way to get the 'progress' of a Summary object. A Summary object has X Grade objects - a Grade object is_complete when it has a Level chosen and has 1 or more related Evidence objects. I am trying to tie that Summary 'progress' to a Person. The models.py look like this: class Summary(models.Model): id = models.BigAutoField(primary_key=True) person = models.ForeignKey( Person, on_delete=models.PROTECT, related_name="summaries" ) finalized = models.BooleanField(default=False) class Meta: verbose_name = "Summary" verbose_name_plural = "Summaries" def progress(self): """Return the progress of the summary.""" grades = self.grades.all() finished_grades = ( Grade.complete.all().filter(summary=self).count() ) try: progress = (finished_grades / grades.count()) * 100 class Grade(models.Model): id = models.BigAutoField(primary_key=True) summary = models.ForeignKey( Summary, on_delete=models.PROTECT, related_name="%(class)ss" ) level = models.ForeignKey( Level, on_delete=models.PROTECT, null=True, blank=True, related_name="%(class)ss", ) class Meta: verbose_name = "Grade" verbose_name_plural = "Grades" @property def is_complete(self): if 0 < self.evidences.count() and self.level: return True return False class Evidence(models.Model): id = models.BigAutoField(primary_key=True) grade = models.ForeignKey( Grade, on_delete=models.PROTECT, related_name="%(class)ss" ) comment = models.TextField() My views.py looks like this: class PersonListView(ListView): model = Person template_name = "app/person_list.html" context_object_name = "person_list" def get_queryset(self): people = Person.objects.all().prefetch_related("summaries", "summaries__grades", "summaries__grades__evidences") # There should only be one non-finalized summary # or there will … -
Django back end not sending response message back to React front end
I am currently working on a e-commerce project using django and react. I finished building my create order route and it is working fine in terms of adding the order and orderItem to the database. (I am checking from the admin panel). However the issue is that for some reason I am not able to see the response on the front end even though I am returning it. This is my react component making the reuest PlaceOrder.jsx const handleCreateOrder = async () => { let body = {}; body.user = userContextEmail; body.totalPrice = totalPrice; body.shippingAddress = shippingAddressString; const items = {}; for (let i = 0; i < cart.length; i++) { let itemId = cart[i].id; let itemQuantity = cart[i].quantity; items[itemId] = itemQuantity; body.items = items; } let response = await fetch("http://127.0.0.1:8000/base/orders/create", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(body), }); let result = await response.json(); console.log(result.data); // NOTHING BEING DISPLAYED ON MY CONSOLE }; urls.py path('orders/create', order_views.createOrder) order_views.py @api_view(['POST']) def createOrder(request): data = request.data # print(data) profile = Profile.objects.get(username=data['user']) totalPrice = data['totalPrice'] shippingAddress = data['shippingAddress'] try: order = Order.objects.create( profile = profile, totalPrice = totalPrice, shippingAddress = shippingAddress ) except: message = {'detail': 'An error has occured during … -
show or know LDAP attributes in django
I have a project in django where i try to connect with ldap server. All seems works well, because when i login in django, the user is added to the django database. The problem is that I made a custom user with the department field in django and I want to get a concret attribute from ldap and assign with the field department, but when I login i see in django logs this line: search_s ('ou=xxx,o=xxx, 2 '(uid=%user)s)') returned 1 objects cn=usern_name,ou=xxx,o=xxx Creating Django user user_name Populating Django user user_name cn=user_name,ou=xxx,o=xxx does not have a value for the attribute aaeAppAdd Then I see in department field in Django user database that is empty. How I can see or get the user_object attributes (print, etc) that the LDAP offer when i login correct? These are my config files. settings.py # Config to authenticate with LDAP import ldap from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion, GroupOfNamesType AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) basedn = "ou=xxx,o=xxx" AUTH_LDAP_SERVER_URI = 'ldap://ldapserver:389' AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch(basedn, ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "department": "aaeAppAdd" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": {"console": {"class": … -
how to apply template for django ModelViewset class
hello i am stuck and i can't apply my html to this class please help class ProductViewSet(ModelViewSet): queryset = Product.objects.prefetch_related('images').all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter pagination_class = DefaultPagination permission_classes = [IsAdminOrReadOnly] search_fields = ['title', 'description'] ordering_fields = ['unit_price', 'last_update'] -
django.db.migrations.exceptions.MigrationSchemaMissing error Connecting Postgres to Django?
This is my first time that i am using other database than sqlite3 with django ,so i go ahead with postgres ,install it on my machine and created the user and db but after config the setting.py when i migrate i got this error # database config DB_NAME = 'django_chat_db' DB_USER = "django" DB_PASSWORD = "password" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': 'localhost', 'PORT': '5432', } } ERRORs Traceback (most recent call last): File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.InsufficientPrivilege: permission denied for schema public LINE 1: CREATE TABLE "django_migrations" ("id" bigint NOT NULL PRIMA... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\migrations\recorder.py", line 70, in ensure_schema editor.create_model(self.Migration) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\base\schema.py", line 447, in create_model self.execute(sql, params or None) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\base\schema.py", line 199, in execute cursor.execute(sql, params) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File … -
It is impossible to add a non-nullable field Error when extending Abstract User
I want to extend the Base Abstract User Model and this is the extended model: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=25) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) address = str(street) + str(street_number) + str(city) + str(code) + str(province) But I get this message popup: It is impossible to add a non-nullable field 'password' to student without specifying a default. This is because the database needs something to populate existing rows. However I haven't added a new password field and all the existing password fields (for the superuser) already have a value. What should I do? When I add a default value and try to migrate it, it complains that there is no such table as 'mainApp_student'. -
Is there any way to overwrite the default operation id , tag, name ,description of generated drf api schema?
Is there any way to overwrite the default operationid,name,tag,type,summary, description of generated drf api schema? -
Learning Better Way of Doing It (Django Models)
I am doing Django and I have 4 models. District, Province, Schools and User. The District belongs to a Province, in the School model/table there are the foreign keys to which the school belong. In the User table, I have district, province and school foreign keys. these tuples were named province or district in the tables they are FKs. The error I was getting was a conflict and needed to add a related_name. I need someone to explain to me the value for related_name. From my reading, it is showing the table name, If the FK is in the Comments model then the related_name='comments'. In my case I have three FK in the User model so how do I manage this? I hope this tries to explain my query.