Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load data with user id condition with Django Model?
How to load data from the existing value of the user id? class mmd1(models.Model): userid = models.ForeignKey( 'user.usid', related_name = "User2", verbose_name = 'Partner', ) ttx = models.CharField( _('ttx'), max_length = 100 ) data = models.ForeignKey( 'data', related_name = "data", verbose_name = 'data', limit_choices_to={'id': userid} ) Unable to load data based on user id and error this line: limit_choices_to={'id': userid} How to fix this issue? -
Setting up Angular & Django for frontend & backend
I had a fully-functioning Angular app that was being served on the 4200 local port. I followed a few tutorials and set it up as frontend, with Django as backend. Now, some of the images and resources do not show on the page, even though I can see that they are transferred into to the static folder, inside the assets folder. For example, my app.component.html and app.component.css are as follows with regards to a project logo: <div class="toolbar" role="banner"> <img class="headerlogo" width="150" (click)="goNavigateToPage('')" alt="Angular Logo" src="../assets/Projektlogo.png" /> <div class="spacer"></div> <div class="col-xs-12"> <app-header></app-header> </div> <div class="spacer"></div> <a href="/"></a> <img class="headerlogo" (click)="goNavigateToPage('')" src="../assets/Projektlogo.svg" alt="" height="100" width="150" /> </div> .bg { background-color: #f0abab; background-image: url(../assets/ProjektlogoBackground.png); } But the project logo does not show when I run the Django server... Should we modify all paths such as src="../assets/Projektlogo.png" manually for Angular and Django to work together, or should this be done automatically and I am missing something? -
How to check equal in template?
This is my model. class Ad_company(models.Model): idx = models.AutoField(primary_key=True) subject = models.CharField(max_length=255) memo = models.CharField(max_length=255) content = models.TextField() is_display = models.CharField(max_length=1) writer = models.CharField(max_length=255) write_date = models.DateTimeField() update_date = models.DateTimeField() delete_date = models.DateTimeField() deadline_date = models.DateTimeField() reply = models.IntegerField(blank=True) hits = models.IntegerField(blank=True) ad_apply = models.IntegerField(blank=True) ad_category1 = models.CharField(max_length=255) ad_category2 = models.CharField(max_length=255) ad_place = models.CharField(max_length=255) ad_age = models.CharField(max_length=255) ad_sex = models.CharField(max_length=255) ad_budget = models.BigIntegerField() ad_length = models.CharField(max_length=255) is_done = models.CharField(max_length=1) is_pay = models.CharField(max_length=1) ad_service = models.CharField(max_length=255) ad_object = models.CharField(max_length=255) is_file = models.CharField(max_length=1) ad_require = models.CharField(max_length=255) contract_user = models.CharField(max_length=255, blank=True) And This is my html template code {% if adlist.contract_user == user %} <span class="ad-state full-time">contract</span> {% endif %} adlist.contract_user is asdf and user is asdf same but It doesn't work. I think I need to change string or something? -
how to remove upload image validation in Django?
How can I remove this validation in django? code in Django is like this: image = models.ImageField(upload_to="data", null=True, blank=True) -
custom filtering in django rest framework
I am trying to implement custom filtering in my code and went through the documentation. But I couldnt understand the following snippets from the docs. class UserFilter(django_filters.FilterSet): class Meta: model = User fields = ['username', 'last_login'] # or class UserFilter(django_filters.FilterSet): class Meta: model = User fields = { 'username': ['exact', 'contains'], 'last_login': ['exact', 'year__gt'], } The doc says we can use either one the first or second one but what is the exact difference?? What is the meaning of contains and year_gt? -
Django Serializer is not JSON serializable
I'm trying to serialize an object details which contains ForeignKey and OneToOneField. Here is my Model: user = models.OneToOneField( "User", on_delete=models.CASCADE, null=False, blank=False, verbose_name="User", help_text="The user who subscribed.", related_name="subscription_information", unique=True, ) subscription = models.ForeignKey( Subscription, on_delete=models.CASCADE, null=False, blank=False, related_name="subscription_information", verbose_name="Subscription", help_text="This is the subscription.", ) subscription_type = models.IntegerField( choices=SUBSCRIPTION_TYPES_CHOICES, default=SubscriptionTypes.monthly, null=False, blank=False, verbose_name="Subscription Type", help_text="", ) next_payment_amount = models.FloatField( default=0.0, null=False, blank=True, verbose_name="Subscription Plan Next Payment Amount", help_text=(""), ) next_payment_date = models.DateTimeField( null=True, blank=True, default=None, verbose_name="Next Payment Date", help_text=(""), ) payment_made = models.BooleanField( null=False, blank=True, default=False, verbose_name="Is Payment Made", help_text=( "" ), ) subscription_date = models.DateTimeField( null=True, blank=True, default=None, verbose_name="Subscription Date", help_text="", ) As you see User field is OneToOneField and Subscription field is foreign key. And here is my serializer: class SubscriptionInformationDetailSerializer(serializers.ModelSerializer): class Meta: model = SubscriptionInformation fields = ( "id", "user", "subscription", "subscription_type", "next_payment_amount", "next_payment_date", "payment_made", "subscription_date", ) I want to return serialized SubscriptionInformation with this code: subscription_information = SubscriptionInformation.objects.get(user_id=user.id) serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True) return serializer But it throws this error: Traceback (most recent call last): File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response response = response.render() File "E:\Programming\project\venv\lib\site-packages\django\template\response.py", line 109, … -
download database though sql sentence in Django view
So I have a Django view that downloads a MySQL database table depending on the button selected. The problem is that when I download the tables, the words in the CSV are changed with all commas. So what I wanted is to change the code that I have with SQL sentences. But I don't know how to export that SQL sentence to a CSV later. Help is much appreciated. This is what I have for the moment My Views.py: def download_db(request, mode): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) if mode == 1: writer.writerow(['session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23']) for word in WordDifferentTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="ForWordDifferent.csv"' return response elif mode == 2: writer.writerow(['session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23']) for word in LogicAnaloguiesTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="ForLogicAnalogies.csv"' return response elif mode == 3: writer.writerow(['session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23']) for word in SimilarWInContextTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="ForSimilarWordInContext.csv"' return response elif mode == 0: writer.writerow(['session_id', 'word1', 'word2', 'word3']) for word in WordsTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="WordsTable.csv"' return response return JsonResponse({}, status=304) One of the … -
How to link two databases together?
I have 2 databases that are supposed to be linked by a foreign key: DealershipListing and Dealers. Here are their models: class Dealer(models.Model): dealersName = models.TextField(('DealersName')) zipcode = models.CharField(("zipcodex"), max_length = 15) zipcode_2 = models.CharField(("zipCode"), max_length = 15) state = models.CharField(("state"), max_length=5) address = models.TextField(("Address")) ids = models.BigIntegerField(("ids"), primary_key=True) def __str__(self): return self.dealersName class DealershipListing(models.Model): uniqueID = models.IntegerField(("CarID"), primary_key=True) vincode = models.CharField(('vinCode'), max_length=255) price = models.CharField(('price'), max_length=30) msrp = models.CharField(('msrp'), max_length=30) mileage = models.CharField(('mileage'), max_length=9) is_new = models.BooleanField(('isNew')) first_seen = models.CharField(("first_seen"), max_length=15) last_seen = models.CharField(("last_seen"), max_length=15) model = models.CharField(("Models"), max_length= 255) make = models.CharField(("Make"), max_length=255) year = models.CharField(("Year"), max_length= 4) ids = models.ForeignKey(Dealer, on_delete=CASCADE) color = models.CharField(("ExtColor"), max_length=255, null=True, blank = True) intcolor = models.CharField(("IntColor"), max_length=255, null=True, blank=True) def __str__(self): return self.year + " " + self.make + " " + self.model But when I go check the admin database, the DealershipListing is a dropdown of the names of every dealership in the Dealer model, but the ids on the DealershipListing model is placed in the place of color. What am I doing wrong? How do I connect each car in the DealershipListing to their Dealership by the ids? -
Why the session isn't flushing?
Working on a simple project using Django 3.2. Lately I have put to the project a login/register page. The problem is the when I logout from the account the session isn't flushed. I used the code request.session.flush, and still doesn't work. For better understanding will show the code below: @login_required(login_url='login/') def logoutUser(request): logout(request) request.session.flush() return redirect("/") -
Local Host file into Cloud
I am using Django. I scraped a website and with the help of Django, I make the front-end. In Django, we run python manage.py runserver to run the localhost project. Now the next task is that I can save that file in Cloud so that everyone can access that file without using the"python manage.py runserver" command or by just clicking that file so the front-end can be shown easily. Is there any possible way to do that particular task -
Why are my static files not served when deployed to Heroku server? (Django)
So this is a common mistake for Django users, which is static files not served in production when Debug=False. I've tried many methods to overcome this issue, but still cannot figure out right solution. Below is my settings.py ... DEBUG = False MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'main/static'), os.path.join(BASE_DIR, 'member/static'), os.path.join(BASE_DIR, 'register/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] I don't see how I've done wrong. *One thing that might be a potential cause is that I've set DISABLE_COLLECTSTATIC=1 since the initial deploy to heroku server. remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: -----> No change in requirements detected, installing from cache remote: -----> Using cached install of python-3.7.12 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: -----> Skipping Django collectstatic since the env var DISABLE_COLLECTSTATIC is set. remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: … -
Media Files of a Django App deployed in Azure App Service
Like the tittle says, I have a Django App deployed to Azure App Service through GitHub the thing is, I can't access the media files. I can access the Django Admin site to upload the files to an "uploads" folder which I can find through SSH Link to SSH Image But when I try to fetch that image using https/mysite/uploads/image.jpeg in the Vue App I get a 404 Error, everything else works just fine. This my URLPatterns variable: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('api/v1/', include('commerce.urls')), path('api/v1/', include('ordenes.urls')), path('reporte/ventas/', AlmacenPDFView.as_view(), name='reporte_productos'), path('reporte/finanzas/ordenes/', OrdenesPDFView.as_view(), name='reporte_ordenes'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Question is, How can I get access to those images? or How can I serve the media files? Any help is much appreciated! -
Run scrapy crawler from DRF view
i used scrapy in my project and i want to call my spider with a URL from DRF (Django Rest Framework) View, what is the best way? one of the way i used is : from uuid import uuid4 from django.core.cache import cache from urllib.parse import urlparse from django.core.validators import URLValidator from django.core.exceptions import ValidationError from django.views.decorators.http import require_POST, require_http_methods from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from scrapyd_api import ScrapydAPI from main.models import Quote from scrapy_app.scrapy_app.items import QouteItem import os from iCrawler.settings import BASE_DIR scrapyd = ScrapydAPI('http://localhost:6800') def is_valid_url(url): validate = URLValidator() try: validate(url) except ValidationError: return False return True @csrf_exempt @require_http_methods(['POST', 'GET']) def crawl(request): if request.method == 'POST': url = request.POST.get('url', None) if not url: return JsonResponse({'error': 'Missing args'}) if not is_valid_url(url): return JsonResponse({'error': 'URL is invalid'}) domain = urlparse(url).netloc unique_id = str(uuid4()) settings = { 'unique_id': unique_id, 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } task = scrapyd.schedule('default', 'icrawler', settings=settings, url=url, domain=domain) return JsonResponse({'task_id': task, 'unique_id': unique_id, 'status': 'started'}) elif request.method == 'GET': task_id = request.GET.get('task_id', None) unique_id = request.GET.get('unique_id', None) if not task_id or not unique_id: return JsonResponse({'error': 'Missing args'}) status = scrapyd.job_status('default', task_id) if status == 'finished': try: item = QouteItem.objects.get(unique_id=unique_id) return … -
Django test view fails: (1) unable to logged in a new created user and (2) CBV create view test do not create object in test database
I have a Django project and I want to implent unit tests. I want to test a class based view (CBV) name PatientCreate that need to be authentificated. It is important to not that the sqlite test dabase is already populated with users (data migration). In my PatientTestCase class, I start defining setup where is created a new superuser named 'test' and logged in the new created user. Then, I test if user 'test' is logged in but test fails. If logged in a user already registered in test database (i.e. user named 'admin'), test success. To test for PatientCreate CBV, I write a post request and test if number of patients increase by one. But this test fails, even if I logged in with 'admin'. It seems that patient is not created in test database. Note that, response.status_code = 200. I can not figure out where comes my issue. project architecture - core - urls.py - ecrf - urls.py - views.py tests.py class PatientTestCase(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_superuser( username='test', password='test', email='test@test.fr') # => print(self.user) return test so user is created self.login_success = self.client.login(username='test', password='test') def test_new_patient_is_created(self): self.assertTrue(self.login_success) # => return False with 'test' but will … -
Django REST Framework Serializer: Can't import model
I have a model i am trying to make a serializer out of however i cannot import the model into serializers.py. When i do i get this error: ModuleNotFoundError: No module named 'airquality.air_quality' This is the model i am trying to import class Microcontrollers(models.Model): name = models.CharField(max_length=25) serial_number = models.CharField(max_length=20, blank=True, null=True) type = models.CharField(max_length=15, blank=True, null=True) software = models.CharField(max_length=20, blank=True, null=True) version = models.CharField(max_length=5, blank=True, null=True) date_installed = models.DateField(blank=True, null=True) date_battery_last_replaced = models.DateField(blank=True, null=True) source = models.CharField(max_length=10, blank=True, null=True) friendly_name = models.CharField(max_length=45, blank=True, null=True) private = models.BooleanField() class Meta: managed = True db_table = 'microcontrollers' verbose_name_plural = 'Microcontrollers' def __str__(self): return self.friendly_name serializers.py from rest_framework import serializers from airquality.air_quality.models import Microcontrollers class SourceStationsSerializer(serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = Microcontrollers fields = ['name'] The import is the one the IDE itself suggests i use when i type model = Microcontrollers in the serializer -
It's possible to convert this PHP SQL to Django Query set?
I have 3 models : class Master(models.Model): upload = models.ForeignKey(UploadMaster, on_delete=models.CASCADE, null=True) npp = models.CharField(max_length=12) periode = models.ForeignKey(ParameterPeriode, on_delete=models.CASCADE, null=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, null=True) angsuran = models.CharField(max_length=20) tenor = models.SmallIntegerField(default=0) due_date = models.DateField(null=True) odh = models.SmallIntegerField(default=0) sisa_op = models.BigIntegerField(default=0) angsuran_tertunggak = models.BigIntegerField(default=0) angsuran_terbayar = models.BigIntegerField(default=0) angsuran_perbulan = models.BigIntegerField(default=0) total_denda = models.BigIntegerField(default=0) biaya_tagih = models.IntegerField(default=0) bayar_lancar = models.BigIntegerField(default=0) lunas_normal = models.BigIntegerField(default=0) pelsus = models.BigIntegerField(default=0) total_tagihan = models.BigIntegerField(default=0) credit_type = models.SmallIntegerField(choices=PRODUCT) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) plate_number = models.CharField(max_length=20) salary_date = models.DateField(null=True) nama_bpkb = models.CharField(max_length=120, null=True) last_payment = models.DateField(null=True) last_location_payment = models.CharField(max_length=60, null=True) is_active = models.BooleanField(default=True) update_time = models.DateTimeField(auto_now_add=True) create_time = models.DateTimeField(auto_now_add=True) class StatusCollect(models.Model): code = models.CharField(max_length=10) name = models.CharField(max_length=120) class DataResult(models.Model): from reports.models import StatusCollect master = models.ForeignKey(Master, on_delete=models.CASCADE, null=True) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, null=True) staff = models.ForeignKey(Pic, on_delete=models.CASCADE, null=True) assign_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) upload_master = models.ForeignKey(UploadMaster, on_delete=models.CASCADE, null=True) tgl_waktu_assign = models.DateTimeField(null=True) tgl_waktu_update = models.DateTimeField(null=True) tgl_ptp = models.DateField(null=True) total_ptp = models.BigIntegerField(default=0) phone_number = models.CharField(max_length=14, null=True) keterangan = models.TextField(null=True) cek = models.BooleanField(default=False) status_penyelesaian = models.SmallIntegerField(choices=STATUS_PENYELESAIAN, null=True) status = models.ForeignKey(StatusCollect, on_delete=models.CASCADE, null=True) is_active = models.BooleanField(default=True) create_time = models.DateTimeField(auto_now_add=True) This inside table StatusCollect: | id | code … -
how to get json data from frontside as a input in django?
Actually I m working on Django celery. my leader assign a task that using celery u have to create a task using celery and take Json data as a input from front side and using this celery task then store that Json data in a file. -
how do I the functionality of add new friends reject and delete friend in my user app using django?
Want to Add Friend, Send Friend Request, Accept Friend Requests features in my Django website This is my users>> models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args,**kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) this is my models>> views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) kindly help me out to add friends request functionalities to my project as I'm new to Django, help … -
Bulk update of a model field based on a condition
I have a 5 column model with around 10,000+ lines of data. Now I want to update one column of all the lines based on other column values. -
Failing to get user logged in user object in django
How can I get logged in user in django. When I tried i get the following error 'User' object is not iterable. My code is as follows def createRoom(request): return HttpResponse(request.user) -
html files for django-rest-passwordreset package
I need to set a password reset URL for our website and I used Django rest framework package "django-rest-passwordreset" , I followed the documentations but there is no HTML file to send email in it named "user_reset_password.html", does anybody have it? thank you so much -
'Settings' object has no attribute 'TRANSLATABLE_MODEL_MODULES'
I changed computer. 'Settings' object has no attribute 'TRANSLATABLE_MODEL_MODULES' when I try to run my project on windows computer.I am getting the error. how can i get over this -
Getting Error In Live server TemplateDoesNotExist in django project but in local server same code worked
Hi Every on i am getting error on live server (TemplateDoesNotExist) but when used same code on local server there is no issue found infact rest of all tempalate working, issue face on only one tempalate, can anyone help me out. forms.py class IncentiveForm(forms.ModelForm): start_date = forms.DateField(label='Start Date', required=True, widget=forms.DateInput( attrs={'placeholder': 'Start Date', 'class': 'datepicker form-control'})) end_date = forms.DateField(label='End Date', required=True, widget=forms.DateInput( attrs={'placeholder': 'End Date', 'class': 'datepicker form-control'})) incentive=forms.CharField(label='Incentive Amount', max_length=50, required=True) no_of_trips=forms.CharField(label='No. of Trips', max_length=20, required=True) city = forms.ModelChoiceField(required=True, queryset=City.objects.all()) class Meta: model=Incentive fields= ['start_date','end_date','no_of_trips','incentive','city'] def __init__(self,*args,**kwargs): # self.request = kwargs.pop('request', None) super(IncentiveForm,self).__init__(*args,**kwargs) views.py def incentive_form(request): if request.method == "GET": form=IncentiveForm() return render(request,'hiringprocess/incentive.html',{'form':form}) else: form=IncentiveForm(request.POST) if form.is_valid(): form.save() # uid=Incentive.objects.last() messages.success(request,'Incentive data Created successfully!') urls.py path('incentive/add',views.incentive_form,name="incentive_form") hiringprocess/incentive.html <form roll="form" method="POST" action="/fleet/incentive/add" autocomplete="off"> {% csrf_token %} <div class="box-body"> <div class="col-md-6"> {{ form.start_date|as_crispy_field}} </div> <div class="col-md-6"> {{ form.end_date|as_crispy_field}} </div> <div class="col-md-6"> {{ form.no_of_trips|as_crispy_field}} </div> <div class="col-md-6"> {{ form.incentive|as_crispy_field}} </div> <div class="col-md-6"> {{ form.city|as_crispy_field}} </div> <div class="row"> <div class="col-md-6"> <button type="submit" class="btn btn-primary" style="margin-bottom:20px;"> <span class="glyphicon glyphicon-ok-circle"></span> <span id="btn_txt">Created</span> </button> </div> </div> </div> </form> -
Django migration cannot create model table in DB
I have a model admin_portal.User. I can make migrations files for it, I can see 0001_initial.py under admin_portal/migrations. However, when I run python3 manage.py migrate, I got Operations to perform: Apply all migrations: admin_portal, auth, common_app, contenttypes, knox, sessions Running migrations: Applying admin_portal.0001_initial... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying knox.0001_initial...Traceback (most recent call last): File "/home/lexl/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist In the DB, I only see these tables List of relations Schema | Name | Type | Owner --------+------------------------+-------+-------- public | auth_group | table | user public | auth_group_permissions | table | user public | auth_permission | table | user public | django_content_type | table | user public | django_migrations | table | user Why the user table is not created? admin_portal.0001_initial is applied, I shouldn't have permission issue to create tables, right? -
How to add ordering to Case, When conditions in django
There are two fields: start_date and end_date. (DateField). Standard for sorting. Both start_date and end_date are empty values. (start_date = Null, end_date = Null) Start_date Most recently and end_date is empty values (start_date = not null, end_date = Null) If both start_date and end_date have values, end_date most recently (start_date = not Null, end_date = not Null) If both start_date and end_date have values, start_date most recently (start_date = not Null, end_date = not Null) Ex) I want start end 1. null null 2. null null 3. 2021-10-01 null 4. 2021-09-01 null 5. 2021-09-15 21-09-20 6. 2021-09-01 2021-09-20 7. 2021-09-01 2021-09-15 I tried Model.objects.annotate( order1=Case( When(Q(start_date__isnull=True) & Q(end_date__isnull=True), then=0), When(Q(start_date__isnull=False) & Q(end_date__isnull=True), then=1), When(Q(start_date__isnull=False) & Q(end_date__isnull=False), then=2), output_field=IntegerField() ), ).order_by('order1') result start end 1. null null 2. null null 3. 2021-09-01 null # change 3, 4 4. 2021-10-01 null 5. 2021-09-15 21-09-20 6. 2021-09-01 2021-09-20 7. 2021-09-01 2021-09-15 How can I solve the complicated order by in django?