Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom User with "USERNAME_FIELD" non-unique in Django
Situation: We have an existing system where current employee logins to the system using their mobile number. But as same mobile number can be used by multiple users, so there is constraint in existing db that, at any moment there can be only one user with given "Mobile Number" and "is_active: True" (i.e their may be other employees registered with same number earlier, but their status of "is_active" would have changed to "false", when they left). Also, only admin can add/register new employees/user. I have created a custom "User" model and "UserManager" as below: models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import UserManager # Create your models here. class User(AbstractBaseUser, PermissionsMixin): """ A class implementing a fully featured User model. Phone number is required. Other fields are optional. """ first_name = models.CharField(_('first name'), max_length=50, null=True, blank=True) last_name = models.CharField(_('last name'), max_length=50, null=True, blank=True) phone = models.CharField( _('phone number'), max_length=10, null=False, blank=False, help_text=_('Must be of 10 digits only') ) email = models.EmailField(_('email address'), null=True, blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user is a staff member.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates … -
Django not picking up overridden translation for third-party applications
I have a third-party application installed which has translation tags in its templates and also provides translations for those in several languages, but I'd like to change a few translations for only one language. I ran the makemessages command and the msgid's for those third-party application show up nicely in my own .po file in the folder I use as LOCALE_PATHS. Then, I added corresponding msgstr's for them, ran compilemessages and expected my translations to override the ones that were provided by the third-party application, but I still see the ones provided by the application. I tried everything up to restarting the webserver, rebuilding the Docker images that I'm using, etc. etc., but I only get to see my own translations once I remove the application's .mo file, which does indicate that my compilemessages worked as expected, but apparently Django is giving preference to the application's .mo file instead of mine, despite the Django docs stating that the language coming from my LOCALE_PATHS should have the highest precedence. What am I missing here? -
HTML (in Django) not accessing Postgresql after changing from SQLite
Was making a mock blog and was initially using the default database for Django (SQLite). Code was works with SQLite but when transferring over to PostgreSQL database no longer shows on HTML. Admin page seems to load of database fine though so I'm assuming it doesn't have to do with Django logging into database. It might be my views.py but at this point I can't seem to find a solution. Any help would be appreciated! Code down below models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0, "Draft"), (1, "Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) # Create your models here. views.py from django.views import generic from .models import Post from .forms import CommentForm from django.shortcuts import render, get_object_or_404 class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') #context_object_name = 'post_list' template_name = … -
django.db.utils.OperationalError: 3780, "Referencing column and referenced column in foreign key constraint 'S%' are incompatible."
I am trying to migrate all my changes to my development server. I created makemigrations and it was successful but when I try to run "python manage.py migrate" I am facing the below error. Running migrations: Applying hotline.0002_auto_20201023_1559...Traceback (most recent call last): File "C:\Users\Envs\my_glen\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\Envs\my_glen\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "C:\Users\Envs\my_glen\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "C:\Users\Envs\my_glen\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "C:\Users\Envs\my_glen\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (3780, "Referencing column 'outlet_id' and referenced column 'outlet_id' in foreign key constraint 'outlet_distributor_r_outlet_id_6a1221a8_fk_outlet _de' are incompatible.") models.py class OutletDistributorRelation(models.Model): mapping_id = models.CharField(max_length=15, unique=True, null=True) outlet = models.ForeignKey( outlet_detail, on_delete=models.CASCADE, related_name="parent_outlet") distributor = models.ForeignKey( Distributor, on_delete=models.CASCADE, related_name='parent_distributor') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'outlet_distributor_relation' def __str__(self): return str(self.outlet) + "-" + str(self.distributor) Migrations file after running makemigrations migrations.CreateModel( name='OutletDistributorRelation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('mapping_id', models.CharField(max_length=15, null=True, unique=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'db_table': 'outlet_distributor_relation', }, ), migrations.AddField( model_name='outletdistributorrelation', name='distributor', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parent_distributor', to='hotline.Distributor'), ), migrations.AddField( model_name='outletdistributorrelation', name='outlet', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parent_outlet', to='discount_manager.outlet_detail'), ) I don't know the reason why but the distributor Id is getting migrated but the outlet Id is not. … -
Django messages not showing up on redirects, only render
For a couple days now, I've been trying to figure out why my messages don't show up on redirects. All of the dependencies are there in my settings.py file as you can see. I don't think that's the problem because I am getting two messages to show up on signup and login if the user's passwords don't match on signup or if the user enters the wrong password on login. I notice it only works on renders, but not on redirects. I'll post an image of my file structure and also the relevant files next. File structure images: settings.py from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.DEBUG: 'alert-info', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } INSTALLED_APPS = [ ... 'django.contrib.messages', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', ... 'django.contrib.messages.middleware.MessageMiddleware', ... ] TEMPLATES = [ ... 'context_processors': [ ... 'django.contrib.messages.context_processors.messages', ], }, }, ] My urls.py in the main virtual_library folder from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from book.views import * urlpatterns = [ path('admin/', admin.site.urls), # Book paths path('', include('book.urls')), # Added Django authentication system after adding members app path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ]+ static(settings.MEDIA_URL, … -
How to use Django iterator with value list?
I have Profile table with a huge number of rows. I was trying to filter out profiles based on super_category and account_id (these are the fields in the model Profile). Assume I have a list of ids in the form of bulk_account_ids and super_categories list_of_ids = Profile.objects.filter(account_id__in=bulk_account_ids, super_category__in=super_categories).values_list('id', flat=True)) list_of_ids = list(list_of_ids) SomeTask.delay(ids=list_of_ids) This particular query is timing out while it gets evaluated in the second line. Can I use .iterator() at the end of the query to optimize this? i.e list(list_of_ids.iterator()), if not what else I can do? -
Djnago Concat Query Error You might need to add explicit type casts
I am trying to query/filter with annotating generated date field. This is my query: trip = Booking.objects.annotate( end_date=Concat( Extract('start_date', 'year'), Value('-'), Extract('start_date', 'month'), Value('-'), Extract('start_date', 'day') + F('itinerary__days') , output_field=DateField() ) ) expired = booking.filter(end_date__gte=datetime.today()) But fires me the following error: HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. I have researched about this and the error is related with PostgreSQL. I am not getting how to fix this these are my models: class Itinerary(models.Model): days = models.PositiveSmallIntegerField(_("Days"), null=True, blank=True) class Booking(models.Model): itinerary = models.ForeignKey( Itinerary, on_delete=models.CASCADE ) start_date = models.DateField(_("Start Date"), null=True, blank=True) def get_end_date(self): return self.start_date + datetime.timedelta(days=self.itinerary.days) I am not getting how to solve this. I don't have fields named end_date but i am making end_date with annotating with increasing the days from the itinerary table Can anyone tell me what is the possible reason my query not working? -
Uploading multiple photos via django admin
I found an interesting option to upload multiple images in the admin area at a time. I try to do the same for myself. models.py from django.db import models class Album(models.Model): name_album = models.CharField('name album', max_length=50) class Image(models.Model): image_prezents = models.ImageField('Photo', null=True, blank=True, upload_to="media/") album = models.ForeignKey(Album,on_delete=models.CASCADE, related_name='album') admin.py from django.contrib import admin from.models import Image, Album class PhotoInline(admin.StackedInline): model = Image extra = 0 class ImageAdmin(admin.ModelAdmin): inlines = [PhotoInline] def save_model(self, request, obj, form, change): obj.save() for afile in request.FILES.getlist('photos_multiple'): obj.photos.create(image=afile) ##????? admin.site.register(Album, ImageAdmin) And I just can't figure out what's in the line obj.photos.create (image = afile) for the photos parameter. Tell me please. I am new to django. -
local variable 'all_inf' referenced before assignment
i am new in django. so i am trying to create a CRUD application using Django but I am getting "local variable 'all_inf' referenced before assignment " this error while trying to build it here is my view.py -- coding: utf-8 -- from future import unicode_literals from django.shortcuts import render from .forms import Create from enroll.models import User Create your views here. def add_show(request): if request.method == 'POST': crt = Create(request.POST) if crt.is_valid(): username = crt.cleaned_data['name'] useremail = crt.cleaned_data['email'] user_contact = crt.cleaned_data['contact_number'] save_to_db = User(name=username, email=useremail, contact_number=user_contact) save_to_db.save() crt = Create() else: crt = Create() all_inf = User.object.all() return render(request, 'index.html', {'form': crt, 'info': all_inf}) -
Deployment of client environment on registration
I want to deploy a django app per client whenever a new client registers. For registration i also have a django app where clients can register (running in a kubernetes namespace) such that after registeration of a client inside the django register app, the actual django app environment for the client is deployed. I would like to automate this process in such a way: As soon as customer registers in the register app, the customer registration data from django register app is transferred to the newly created client django app environment. Any broad ideas or concepts on how to achieve this? -
l'm receiving a broken password reset link when using django.contrib .... reset email
from django.urls import path, NoReverseMatch from django.conf import settings from django.contrib.auth import views as auth_views from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('login.html', views.login2, name='login2'), path('register.html', views.register, name='register'), path('logoutUser', views.logoutUser, name='logoutUser'), path('music.html', views.music, name='music'), path('profile.html', views.profile, name='profile'), path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name="password_reset_complete"), path('oauth/', include('social_django.urls',namespace='social')), ] so I'm using this default password reset in Django and l get to send the email and receive it but the problem is that the reset link that will redirect me to the form is broken the port is missing, and if l fix the port in the URL after l click it works and takes me to the password_reset_confirm this is the reset link l receive http://localhost/reset/MQ/ac5zx3-f826598ef65286489c632fd68ecb1175/ -
How to use Django ORM with Panel?
Summary I want to implement an interactive dashboard using panel in a Django application using data from a database. First I've followed the example in the panel docs and it's working fine in my Django project. In that example, the data is calculated in a simple function and a plot is displayed. I can use the widgets and get the expected results. For my application, instead of calculating the data without external dependencies, I want to aggregate data from a database depending on a date range which is chosen by the user in the UI. So I have to gather this data inside the param.Parametrized instance, as far as I understand. Therefore I've tried to use a query on the database ORM instead of calculating values. What I've tried In order to keep it simple here and to stay with the example, I've created a model for the sine values in my Django app (called dashboard): from django.db import models class SineValue(models.Model): x = models.FloatField() y = models.FloatField() and inserted some values: DELETE FROM dashboard_sinevalue; INSERT INTO dashboard_sinevalue (id,x,y) VALUES (1,1,1); INSERT INTO dashboard_sinevalue (id,x,y) VALUES (2,2,4); INSERT INTO dashboard_sinevalue (id,x,y) VALUES (3,3,9); Then I've replaced the calculation of the … -
Serializer behaviour with null=False fields in DRF
I've encountered a weird behavior that I don't quite get. For the model class Tenant: name = models.CharField(max_length=155) country = models.CharField(max_lengh=155) I'm using this serializer: class Serializer(serializers.ModelSerializer): class Meta: model = Tenant fields = (name,) This set up will allow me to save a tenant instance that doesn't have a country supplied even though the null=True should be enforced on the DB level (Postgres). Only when I add country to the fields, will it enforce the null=False constraint. This seems quite unintuitive to me. -
Django IIS - why is my website not loading?
I have been following these videos to get my Django website running using Python FASTCGI Handler in Internet Information Services. All seems OK however when I browse to the website it simply returns the Internet Information Services homepage. Does anyone have any ideas? If you need further information please detail this and I will be sure to post any coding. https://www.youtube.com/watch?v=CpFU16KrJcQ https://www.youtube.com/watch?v=APCQ15YqqQ0 Best, Neil -
Django: Assign Route to Order Based on User Input of Location
In my create order view, I am trying to automatically assign the respective route based on the location the user inputs. Basically, every location in the system has a FK to a route. There are many locations within a route. If you select a location to send products to, the route should automatically be tied to. Currently I am able to see the route for an order in my order_list.html page...but when I view the order in the Django admin...the route is not assigned to the order but the location is. I want it to work similarly to how you would assign the current logged in user to an order: form.instance.user = request.user I tried using: form.instance.company = request.user.company But I am getting an attritbute error: " 'WSGIRequest' object has no attribute 'location' " Here is my full "order_create" function: orders/views.py: @login_required(login_url='account_login') def order_create(request): """ A function that takes the users cart with products, then converts the cart into an OrderForm. Then saves the form/order to the database. """ cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): form.instance.user = request.user form.instance.company = request.user.company form.instance.route = request.location.route order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], … -
How to generate multiple 'datetimes' within the same day using 'Faker' library in Django?
I need to generate dummy data for two datetime fields. Currently I'm using Faker library to achieve this: date1= factory.Faker('date_time_this_month') date2= factory.Faker('date_time_this_month') This generates dummy data of 'datetime' type but I want the date to be same in both the fields and the time of date2 must be greater than the date1. Simply put, I need to generate two 'datetime' type data within same day where date1 < date2. -
How to add custom user fields of dj_rest_auth package
Here is the post to add first_name, last_name to the registration view. I want to add some other custom user field beside first_name or last_name. As these field already exist in the user model, He didn't have to edit the user model. But for my case what to do to edit the user model provided by the dj_rest_auth and add some new models? -
Why Django form choice field don't showing initial value from model as selected
Cant get model value to be represented as selected in form choice field. In template I have edit option for my object, and I want to populate all current object values in form fields, but chose fields always will show model default values. Any knowledge how to fix this thought django functionality? So what I have now: my model: class ClientPriceSelection(models.Model): A_B_choice = ( (50.00, 50.00), (25.00, 25.00) ) ... p_four = models.DecimalField(choices=A_B_choice, max_digits=6, decimal_places=2, default=50.00, verbose_name="...", help_text="(---)") my view: addon = get_object_or_404(ClientPriceSelection, id=addon_id) # print(addon.p_four) form = ClientPriceListSelectionForm(request.POST or None, initial={ 'p_one': addon.p_one, 'p_two': addon.p_two, 'p_three': addon.p_three, 'p_four': addon.p_four, 'p_five': addon.p_five, 'p_seven': addon.p_seven, 'p_eight': addon.p_eight, 'p_nine': addon.p_nine, 'p_ten': addon.p_ten, 'p_eleven': addon.p_eleven, 'internal_notes': addon.internal_notes}) context = {"form": form, 'client': get_object_or_404(Client, id=addon.agreement.client.id)} my form: class ClientPriceListSelectionForm(forms.ModelForm): class Meta: model = ClientPriceSelection fields = ['p_one', 'p_two', 'p_three', 'p_four', 'p_five', 'p_seven', 'p_eight', 'p_nine', 'p_ten', 'p_eleven', 'internal_notes'] widgets = { 'internal_notes': forms.Textarea( attrs={'class': 'vLargeTextField', 'cols': '40', 'rows': '10', 'maxlength': '500'}), } -
Django sorting queryset with nested querysets in python
I have a queryset (Group) with a nested queryset (Memberships) with a nested queryset (Credits). This is the output: group = [ { "name": "Group2", "memberships": [ { "username": "test1", "credits": [ { "credits": 1000, "year": 2020, "week": 42, "game_count": 1, "last_game_credits": 10, } ], }, { "username": "test2", "credits": [ { "credits": 1500, "year": 2020, "week": 42, "game_count": 1, "last_game_credits": 0, } ], }, { "username": "test", "credits": [ { "credits": 1000, "year": 2020, "week": 42, "game_count": 1, "last_game_credits": 0, } ], } ] } ] I want to rank the member in Memberships the following way: credits (amount) game_count (amount) last_game_credits (amount) Hence, if two players have an equal amount of credits the one with the highest game_count wins. If that is the same the one with the highest last_game_credits wins. I want the same structure to be returned. Models: class Group(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="memberships", through='Membership') class Membership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="membership", on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) class Credits(models.Model): credits = models.IntegerField() year = models.IntegerField(default=date.today().isocalendar()[0]) week = models.IntegerField(default=date.today().isocalendar()[1]) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="credits", on_delete=models.CASCADE) game_count = models.IntegerField(default=0) last_game_credits = models.IntegerField(null=True) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = NameField(max_length=25, unique=True, View: class GroupSet(generics.ListAPIView): … -
I'm Getting an ApiError while using dropbox as a django storage
I'm using dropbox as a django storage to serve media files and while uploading to dropbox all working fine the files are uploading to the root directory as expected but the uploaded image won't render on the templates, The error that showing ApiError at /index ApiError('304328f4c8384ce99352fc8e9c338f71', GetTemporaryLinkError('path', LookupError('not_found', None))) Request Method: GET Request URL: http://127.0.0.1:8000/index Django Version: 3.1.2 Exception Type: ApiError Exception Value: ApiError('304328f4c8384ce99352fc8e9c338f71', GetTemporaryLinkError('path', LookupError('not_found', None))) Exception Location: /home/raam124/.local/share/virtualenvs/rattota-GtEiaCOf/lib/python3.8/site-packages/dropbox/dropbox.py, line 337, in request Python Executable: /home/raam124/.local/share/virtualenvs/rattota-GtEiaCOf/bin/python Python Version: 3.8.5 Python Path: ['/home/raam124/Documents/rattota', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/raam124/.local/share/virtualenvs/rattota-GtEiaCOf/lib/python3.8/site-packages'] Server time: Fri, 23 Oct 2020 10:02:16 +0000 my static and media files setting os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "media"), ] STATIC_URL = '/static/' MEDIA_URL = '/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn') my dropbox storage settings DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'token here' DROPBOX_ROOT_PATH = '/' and I'm rendering the image using <img alt="" class="card-img img-fluid geeks" src="{{topstory.image.url}}" /> -
STATIC FILES (CSS NOT FOUND) WITH DJANGO
I'm using Django to build a dashboard. The structure of my project is the one below : │ db.sqlite3 │ manage.py │ ├───dashboard │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ │ │ ├───projects │ admin.py │ apps.py │ models.py │ tests.py │ views.py │ __init__.py │ │ ├───static │ ├───css │ │ main.css │ │ sb-admin.css │ │ sb-admin.min.css │ │ │ ├───js │ │ │ │ │ ├───media │ │ │ ├───scss │ │ │ └───vendor │ ├───upload_log │ │ admin.py │ │ apps.py │ │ forms.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ └───__init__.py │ └───templates about.html base.html basedraft.html home.html index.html navigationbar.html upload_log.html ` My settings are as below : STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') #add MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static/media/') #static/ add STATIC_DIRS = [ os.path.join(BASE_DIR, "static"), ] My problem is whenever I try to had css into my template I get the error "http://localhost:8000/static/css/main.css net::ERR_ABORTED 404 (Not Found)". Is there something I didn't understand using static files ? I've through documentation and questions on stackoverflow but I've not been able to fixe the problem. However, my upload_log application actually finds it's way … -
DJANGO gte, lte not showing any results
My Problem: i wan't to check for upcoming events. I saw some posts about gte, lte etc. But if create a model query its not showing any results. My code: @login_required def aufträge(request): aufträge = Aufträge.objects.filter(start_date__gt=datetime.now()) context = {"aufträge":aufträge} return render(request, "aufträge/aufträge.html") my model: class Aufträge(models.Model): creator = models.IntegerField() vehicle = models.ForeignKey(Cars, on_delete=models.CASCADE) customer = models.IntegerField() title = models.CharField(max_length=30) desc = models.TextField(blank=True) start_date = models.DateTimeField() created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title any solutions? -
How to change date formet using Python?
I want to change date formet using Python. i Dont know How to do that. i have date formet shown as below 2020-10-22 12:14:41.293000+00:00 I want to change above date formet into below formet date(2020, 10, 22) i want this formet beacause i want to get different between two dates. with above formet i can get diference by using following code, d0 = date(2017, 8, 18) d1 = date(2017, 10, 26) delta = d1 - d0 print(delta.days) So how to Change date formet as i discussed above.or else if you any other method to find difference between these two dates 2020-10-22 12:14:41.293000+00:00 and 2020-10-25 12:14:41.293000+00:00 without changing formet.let me know that also.I will be thankfull if anyone can help me with this issue. -
Deploying django in repl.it shows 400 error
I get a 400 error when i try to host django in repl.it.I tried googling everything but couldn't find an answer. Please solve it. Thanks -
Make certain fields non mandatory when using a model form in inline formsets Django
I have a Parent Model RouteCard to which I want to add related child line items ProcessOperation(s). For this I am using inline formsets. I have a separate Modelform for the creation of ProcessOperation. I want to be able to create a ProcessOperation with or without certain fields present. ex, stage_drawing and setup_sheet. Therefore I have specified in the __init__ function of the model form that these fields are not required. But when I try to create the ProcessOperation using inline formset, it always gives a validation error that these two fields are required. I am using Django 2.0. Code: Model: class RouteCard(models.Model): routeCardNumber = models.AutoField(primary_key=True) customer = models.ForeignKey(Customer, related_name='process_route_cards', on_delete='PROTECT', null= True, default= None) purchaseOrder = models.ForeignKey(PurchaseOrder, related_name='process_route_cards', on_delete='PROTECT', null= True, default= None) initial_item = models.ForeignKey(Item, related_name='route_card_raw_material', on_delete='PROTECT', null= True, default= None) initial_rawmaterial = models.ForeignKey(Material, related_name='route_card_raw_material', on_delete='PROTECT', null=True, default=None) final_item = models.ForeignKey(Item, related_name='route_card_finished_material', on_delete='PROTECT', null= True, default= None) planned_quantity =models.PositiveIntegerField(default=0) inprocess_quantity = models.PositiveIntegerField(default=0) completed_quantity= models.PositiveIntegerField(default=0) rejected_quantity=models.PositiveIntegerField(default=0) created_by = models.ForeignKey(User, related_name='process_route_cards', on_delete='PROTECT') create_date = models.DateField(null=True) final_inspection_report = models.FileField(upload_to=get_file_save_path_rc, null=True, default=None, max_length=500) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) class ProcessOperation(models.Model): OPERATION_STATUS_CHOICES = ( (1, 'CREATED'), (2, 'ASSIGNED'), (3, 'STARTED'), (4, 'COMPLETED'), (5, 'ON_HOLD'), (6, 'CANCELLED'), (7, 'PARTIALLY_COMPLETED'), (0, 'WITHDRAWN'), ) routeCard=models.ForeignKey(RouteCard, related_name='process_operations', …