Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to hold and then display employee information on a page?
I hope everyone's doing well. I am making a little Time Attendance Application where the employee Checks in and Checks out. I am making this a Web App based on the Django python framework. I want to understand the best way to hold the data of these employees but then also display it in a separate page for each employee. So far, I've made a table in my MySQL like: INSERT INTO employees (employee_id INT(50), first_name VARCHAR(25), last_name VARCHAR(30), age INT(80), mobile_no VARCHAR(16), email VARCHAR(100) Everytime I want to create a new employee, I have a page that opens and takes in the employee's details and inserts everything to the database. I also have a table on the homepage (that only the admin can see) that displays the employees and their details but if we click a tr, I want it to open a page containing that employee's details so I can change anything I want or even delete that employee. I understand that the page will have to fetch the details about that employee from the database and then anything I change and save the changes of, will be modified in the database. It's just like how you would … -
Model changes done in tasks not persisting
I am trying to call a task to be completed asynchrously because it takes a long time to complete and the request will timeout if I wait for it to be completed (I'm doing some processing on an image and getting the results). When I put prints into the task, I see it's getting executed, so I know it's not an issue with that. When I save the model, it acts like it saved but doesn't actually permanently save it. project > project > settings.py import environ env = environ.Env() CELERY_BROKER_URL = env.str('BROKER_URL', 'amqp://qisdvxct:b0iKxulu3z2evLScg1hnCNfWflDEBBm2@lion.rmq.cloudamqp.com/qisdvxct') CELERY_RESULT_BACKEND = 'django-db' INSTALLED_APPS = [ ... 'django_celery_results', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } MEDIA_URL = '%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME DEFAULT_FILE_STORAGE = 'accounting.s3utils.MediaRootS3BotoStorage' MEDIA_ROOT = MEDIA_URL STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') project > project > init.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) project > project > celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. … -
Django unique slug prepopulated_fields problem
I have a minor issue, while i create a game objects, slug field auto populated. For example if i write lorem ipsum, slug field autopopulate in this way "lorem-ipsum". However, when I try to create another object with the same name, I get this error. " this slug already exists " Expected output : lorem-ipsum-1 but it doesn't works admin.py prepopulated_fields = {'slug': ('name',)} models.py name=CharField(max_length=255) slug = models.SlugField(unique=True, max_length=255) def get_unique_slug(self): slug = slugify(self.name.replace('ı', 'i')) unique_slug = slug counter = 1 while Game.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(Game, self).save(*args, **kwargs) -
formset : NOT NULL constraint failed: products_productorder.product_id
i have made a formset from formset_factory dynamically when i hit the add button it'll generate a form, with required fields but in the first form even the form is empty and submit the form it doesnt generate any error report to the user (this field is required) , only show NOT NULL constraint failed: products_productorder.product_id also selete2 only work for the first form <script> $(document).ready(function() { $("#product_id").select2(); }); </script> for the rest forms doesnt work for selecting items by typing its names template.html <form method="POST"> {% csrf_token %} <table class="table form-table table-bordered table-sm"> <thead class="text-center"> <tr> <th>products</th> <th>quantities</th> <th></th> </tr> </thead> <tbody> {% for form_data in formset %} <tr class="item"> <td class="col-sm-6" > <label class="text-danger text-bold"> {{form_data.product.errors}}</label> <label for="textarea2"> </label> {{ form.product | add_class:'form-control select2-list' | attr:'id:product_id' }} </td> <td> <label class="text-danger text-bold"> {{form_data.quantity.errors}}</label> {{ form_data.quantity | add_class:'form-control'}} </td> <td> <button type="button" class="btn btn- danger btn-sm remove-form-row" id="{{ formset.prefix }}"> Delete </button> </td> </tr> {% endfor %} <tr> <td> <button type="button" class="btn btn-sm btn-success add-form-row" id="{{ formset.prefix }}"> Add </button> </td> </tr> </tbody> </table> {{ formset.management_form }} <button type="submit">Submit</button> </form> forms.py class ProductOrderForm(forms.ModelForm): product = forms.ModelChoiceField( queryset=Product.objects.filter(active=True),empty_labe l='') class Meta: model = ProductOrder fields = ['product','quantity'] def __init__(self,*args , … -
How do I restart a python app from within the app itself
Got a Django app that has users going through a setup wizard. After the wizard, the app needs to restart for it to pick the necessary settings. The app is run on Ubuntu 18.04 and monitored using supervisord. Ideally am looking to call systemctl restart supervisord.service from the Django app itself. So I've tried import subprocess subprocess.run("systemctl restart supervisord.service") However, this fails with the error: FileNotFoundError [Errno 2] No such file or directory: 'systemctl restart supervisord.service': 'systemctl restart supervisord.service' H -
How to capture parameters from a URL in Django Rest Framwrek to process it in a view
I am new to Django. I am using Django Rest Framework as an Api Rest but I need to generate an endpoint or url that is going to be passed from the frontend (Angular) to get a custom excel, the question is that for example I will pass the following URL: 127.0.0.1:8000/app_prtg/descarga/P79COL01 and I want to capture the value P79COL01 that would be my filtering value to get my excel file, with this parameter I process in a DRF view and I can generate the excel My Url 127.0.0.1:8000/app_prtg/descarga/P79COL01 My Url Definition router.register(r'descarga',MyExampleViewSet) my view to generate the excel and where I should process what comes in the URL and get the value of P79COL01 class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet): queryset = Interfaces.objects.all() serializer_class = InterfaceSerializer renderer_classes = (XLSXRenderer,) filter_class=InterfacesFilter filename = 'my_export.xlsx' -
ValueError: Cannot assign : must be an instance
So I am very new to Django, and I am trying to save a new instance of a model Ovelse, which has a foreign key that points to another model Okt. I have a view that contains a list over all the Okt instances, which links to all the Ovelse instances connected to each Okt. Models.py class Okt(models.Model): def __str__(self): return '{}, uke {}, dag {}'.format(self.sykel_navn, self.sykel_uke, self.sykel_dag) sykel_navn = models.CharField(max_length=8, default="Sykel 1") sykel_dag = models.CharField(max_length=(1), choices=(SYKEL_DAGER)) sykel_uke = models.CharField(max_length=(1), choices=(SYKEL_UKER)) dato = models.DateTimeField('Dato på treningsøkt: ') notater = models.CharField(max_length=400) class Ovelse(models.Model): okt = models.ForeignKey(Okt, on_delete=models.CASCADE) ovelse_type = models.CharField(max_length=2, choices=MUSKELGRUPPE_CHOICES) ovelse_navn = models.CharField(max_length=20) vekt = models.IntegerField(default=0, name='kg') sets = models.PositiveIntegerField(default=2) reps = models.PositiveIntegerField(default=2) def __str__(self): return self.ovelse_navn views.py class OvelseCreateView(generic.CreateView): model = Ovelse template_name = 'trening/add.html' form_class = OvelseForm def form_valid(self, form): form.instance.okt = self.kwargs.get('pk') return super(OvelseCreateView, self).form_valid(form) forms.py class OvelseForm(forms.ModelForm): class Meta: model = Ovelse exclude = ['okt',] fields = ['ovelse_navn', 'ovelse_type', 'kg', 'sets', 'reps'] def __init__(self, *args, **kwargs): super(OvelseForm, self).__init__(*args, **kwargs) self.fields['ovelse_type'].label = "Muskler brukt" self.fields['ovelse_navn'].label = "Navn på øvelsen" self.fields['kg'].label = "Antall kilo" self.fields['sets'].label = "Antall set" self.fields['reps'].label = "Antall reps" When I try to submit the form, I get the error message: Cannot assign "1": "Ovelse.okt" … -
ModelForm has no model class specified with UpdateView
I using ModelForm, UpdateView and Crispy to create User profile setting. But have some problem. Exception Value: ModelForm has no model class specified. If i write like here it will working: views.py class BaseCustomUserCustomize(UserPassesTestMixin, UpdateView): model = CustomUser fields = '__all__' form_class = CustomUserUpdateForm template_name = 'catalog/edit_account.html' success_url = reverse_lazy('catalog:my-account') def test_func(self): obj = self.get_object() return self.request.user.username == obj.username models.py class CustomUserUpdateForm(ModelForm): class Meta: models = CustomUser fields = '__all__' # ['first_name', 'last_name', 'sex', 'avatar', 'birth_date', 'location'] def __init__(self, *args, **kwargs): super(CustomUserUpdateForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Field( 'username', 'first_name', 'last_name', 'birth_date', 'sex', 'location', 'avatar', ) ) views.py class BaseCustomUserCustomize(UserPassesTestMixin, UpdateView): model = CustomUser form_class = CustomUserUpdateForm template_name = 'catalog/edit_account.html' success_url = reverse_lazy('catalog:my-account') def test_func(self): obj = self.get_object() return self.request.user.username == obj.username I want to create a base form of user's profile setting like here with crispy form. -
django path showing twice in url bar
i'm using django to make a little weather app for uni and i'm trying to link from the index page to a 'detail' page but in the url the path keeps apearing twice... i've tried rewriting out the entire urls.py page (both of them). I've looked online as well but there dosent seem to be much about this (or i'm not looking in the right places) so when i click on 'more info' for day 1 the url bar shows /day1/day1 instead of just /day1 -
Django is not serving static and media files in development but it is serving in production
I am using windows 10 as OS in development environment and Ubuntu 18.04 (AWS) in production. I deployed my application recently (15 days) but now when I see the django is no more serving media and static files in the development server while it is running and serving perfectly in the production server (with DEBUG=True in both the servers). I am using Nginx server with gunicorn at the production server. I have tried almost every answer in the StackOverflow to counter this issue but it is not working. settings.py: # MEDIA: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ... STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' # STATICFILES_DIRS = ('static', ) #STATICFILES_DIRS = (os.path.join('static'), ) main_project/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings # new from django.conf.urls.static import static # new urlpatterns = [ path('', include('stock_management.urls', namespace='stock_management')), path('auth/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ] # if settings.DEBUG: # new # urlpatterns += static(settings.STATIC_URL, # document_root=settings.STATIC_ROOT) # urlpatterns += static(settings.MEDIA_URL, # document_root=settings.MEDIA_ROOT) app/urls.py: from django.urls import path, include from .views import * from django.conf import settings app_name = 'stock_management' urlpatterns = [ # Stock: path('', stock_list, name='homepage'), path('stock/', stock_list, name='stock_list'), path('stock/add', stock_create_view, name='add_stock'), path('stock/<pk>/edit', stock_edit, name='stock_edit'), # … -
Django Web app is successfully deployed on Azure App Service Linux but can only see Azure Default Page
I recently published my Django local git repo to the Azure App Service with Python 3.7 runtime. The deployment said it is successful and active but I only see Azure Default Page when I browse it. I can't find any logs anywhere and it shows no signs of errors. How can I solve this ? Thanks and regards, Rachhek. -
How to solve the problem of 'settings.AUTH_USER_MODEL'?
This is my code. Whenever I makemigrations it is giving me the error of users.Profile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True)._unique = True Id_card_number = forms.CharField(max_length=15, required=True) class Meta: model = UserProfile fields = ['username','email','password1','password2','Id_card_number'] views.py from django.contrib.auth import get_user_model UserProfile = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) models.py from django.db import models from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): Id_card_number = models.CharField(max_length=15) admin.py from django.contrib.auth.admin import UserAdmin admin.site.register(UserProfile, UserAdmin) settings.py AUTH_USER_MODEL = 'users.UserProfile' -
update user profile issue with post_save signal. errors a message are user already exists on update
I have extending user profile with profile model and create an post_save signal. I works well on user creation but seems that there is an issue on update. When I want to update I have messages saying user and email already exists in data table. So nothing is updated. My model.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from authenticate.thumbs import ImageWithThumbsField # transforme les images en thumbs import os def image_name(instance, filename): extension = filename.split('.') extension = extension[-1] return 'avatars/{}.{}'.format(instance.user.pk, extension) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = ImageWithThumbsField(upload_to=image_name, blank=True) # transforme les images en thumbs bio = models.CharField(max_length=100, blank=True) location = models.CharField(max_length=30, blank=True, default='Please fill in info') birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() My forms.py: class UniqueUserEmailField(forms.EmailField): """ An EmailField which only is valid if no User has that email. """ def validate(self, value): super(forms.EmailField, self).validate(value) try: User.objects.get(email = value) raise forms.ValidationError("Email already exists") except User.MultipleObjectsReturned: raise forms.ValidationError("Email already exists") except User.DoesNotExist: pass class SignUpform(UserCreationForm): """ Extends the built in UserCreationForm in several ways: * Adds an email field, which uses the custom … -
Add Cancel/Close button to Django admin model editor
I would like to add a Cancel button to the django default admin model editor to enable going back to previous page in case users decide to cancel editing/creating a model. One Option to do that will be extending the 'admin/submit_line.html' and add a Cancel button to it. However, the default django 'admin/submit_line.html' template already includes a 'Close' button as shown in the code snippet below. <div class="submit-row"> {% block submit-row %} {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save">{% endif %} ... {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew">{% endif %} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother">{% endif %} ... {% if show_close %}<a href="{% url opts|admin_urlname:'changelist' %}" class="closelink">{% trans 'Close' %}</a>{% endif %} {% endblock %} </div> If I copied the above template and override the show_close variable to True, the Close button will be shown and closes the form as expected. But Isn't there a way to configure 'show_close' visibility from the models.py or admin.py classes? -
Autoit install whit Python 2.7 and Windows 64 bit
I tried to install autoit like documentation: pip install -U pyautoit But give 32bit error: WindowsError: [Error 193] %1 is not a valid Win32 application How install on 64 bit? TY -
How to dynamically change content of a web page using Django when the structure is the same for multiple links but the content is different?
I have a design problem I am trying to build my web page and currently working on the projects section where I show off my work. In it, I have a list of projects and each of them has a link that loads a description of four paragraphs and an image of it. Since each project is represented by four paragraphs and an image I wonder if I could use Django to store the information and load them according to the project's link instead of hardcoding everything. I am not sure but I suspect that will have to inject Django code somewhere in my template file but do not know where. I posted the code on Pastebin as well to show the HTML code in StackOverflow so here is the link to segment my project: https://pastebin.com/S7HfCfpg. ` <!DOCTYPE html> <html> <body> {% block content %} <div id='vignereCypherPage'> <h1 id="vignereCypherHeading">VIGENERE CYPHER</h1> <section id="projectsDescriotion" class=""> <div id="firstSection"> <div id="insertImage"></div> <div id="insertTheTwoParagraphs"> <p id="fist"></p> <p id="second"></p> </div> </div> <div id="secondSection"> <p id="third"></p> <p id="forth"></p> </div> </section> </div> {% endblock content %} </body> ` -
Why my app doesnt appear and renders the wrong app template?
Hi I started another app called "A-board" using startapp command and wrote the app name in settings file. But I didnt like the initially set app name so I changed it to "board" in root urlconfig using 'name' parameter. Everthing is fine except the new app doesnt show up in my admin interface. In root urlconfig I tried the home to point to this app by removing the old app and make it Path('', include('A-board.urls"), name ="board")) But the home page throws an error showing The old app's template is rendered instead of my new app even after I removed the old app's urlconfig code snippet. Why does it act like this and what am I missing? Thank you for your answer in advance. -
Run all Django tests
I have this project structure when I run python manage.py test --settings=backend.settings.bitbucket Only tests in backend/core/tests are run. When I run python manage.py test backend.apps.sar --settings=backend.settings.bitbucket or move the files to backend/core/tests, everything works fine... How can I run all the tests at once? -
Django Autocomplete Light - "The results could not be loaded"
I'm using Django-autocomplete-light on a small application. The UI seems to work, and I can select from some visible values. The problem arises when I type one or more letters into the box. Normally it should filter/select the results, instead, I get the error "The results could not be loaded" (see picture). Seems like the jquery is working fine, except for not filtering when I type in the box. Happy to add more code, just not sure what I need to add yet. models.py class Encounter(models.Model): patid = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name=('Patient Name'), related_name='patient') created_by = models.ForeignKey(Users, editable=False, null=True, blank=True, on_delete=models.PROTECT, related_name='encounter_created_by') encounter_date = models.DateField() encounter_label = models.ForeignKey(EncounterReason, on_delete=models.PROTECT, verbose_name=('Encounter Reason'), related_name='fk_reason') class EncounterReason(models.Model): reason = models.CharField(max_length=256, blank=True, null=True) valueset_id = models.CharField(max_length=256, blank=True, null=True) views.py class EncounterReasonAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated: return EncounterReason.objects.none() qs = EncounterReason.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs forms.py class EncounterForm(forms.ModelForm): encounter_date = forms.DateField(initial=datetime.date.today, widget = DateInput()) encounter_notes = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Encounter Notes', 'id': 'editor', 'rows':50, 'cols':25})) encounter_label = forms.ModelChoiceField(queryset=EncounterReason.objects.all(), widget=autocomplete.ModelSelect2(url='encounterreason-autocomplete') ) class Meta: model = Encounter fields = ('__all__') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', include('clinicalviewer.urls')), path('encounterreason-autocomplete/', views.EncounterReasonAutocomplete.as_view(), name='encounterreason-autocomplete'), ] … -
django-dynamic-scrapy do not work with python3.x after upgrading
i am using Scrapy (1.1.2) with Django (1.8.19) and Django dynamic scrapy (0.11.2) on python (2.7), its works fine with me but after upgrading to python 3 i got errors in logs when my spiders run as follow : File "/root/.pyenv/versions/3.4.10/envs/sharq-3.4.10/lib/python3.4/site-packages/scrapy/loader/__init__.py", line 154, in _get_item_field_attr value = self.item.fields[field_name].get(key, default) KeyError: 'photos' i tried to use many python versions (3.4.x, 3.5.x, 3.6.x) with many versions of Django dynamic scrapy but still the problem appears, so the result which i arrived to it that this package do not support python 3 although the documentation says it support pyhthon 3. my question is which part in this packed occurred this problem and where in need to edit in the core of this package to make my upgrade success ? -
Problem with saving multiple records in JSON file to MySQL using django-rest-framework
I'm newbie in django I'm trying to save JSON record using Dango-rest-framework, here is my JSON file. {"result":{"lists":[{"resAccountBalance":"0","resWithdrawalAmt":"0","commStartDate":"20190124","commEndDate":"20190724","resTrHistoryList":[{"resAccountTrDate":"20190723","resAccountTrTime":"070609","resAccountOut":"132795","resAccountIn":"0","resAccountDesc1":"","resAccountDesc2":"BC","resAccountDesc3":"카드출금","resAccountDesc4":"","resAfterTranBalance":"0"},{"resAccountTrDate":"20190722","resAccountTrTime":"071125","resAccountOut":"0","resAccountIn":"17","resAccountDesc1":"","resAccountDesc2":"이자","resAccountDesc3":"2019년결산","resAccountDesc4":"","resAfterTranBalance":"132795"},{"resAccountTrDate":"20190515","resAccountTrTime":"031314","resAccountOut":"0","resAccountIn":"180000","resAccountDesc1":"","resAccountDesc2":"타행이체","resAccountDesc3":"지원금","resAccountDesc4":"","resAfterTranBalance":"626109"}]}]}} I want to save 3 records in 'resTrHistoryList' to MySQL, but only last record({"resAccountTrDate":"20190515","resAccountTrTime":"031314","resAccountOut":"0","resAccountIn":"180000","resAccountDesc1":"","resAccountDesc2":"타행이체","resAccountDesc3":"지원금","resAccountDesc4":"","resAfterTranBalance":"626109"}) is saved. Here is my code. model.py class QuickQuiryBankKDB(models.Model): result = models.TextField() resAccountTrDate = models.CharField(max_length=20, default='1000') resAccountTrDate = models.CharField(max_length=20, default='1000') resAccountTrTime = models.CharField(max_length=20, default='1000') resAccountOut = models.CharField(max_length=20, default='1000') resAccountIn = models.CharField(max_length=20, default='1000') resAccountDesc1 = models.CharField(max_length=20, default='1000') resAccountDesc2 = models.CharField(max_length=20, default='1000') resAccountDesc3 = models.CharField(max_length=20, default='1000') resAccountDesc4 = models.CharField(max_length=20, default='1000') resAfterTranBalance = models.CharField(max_length=20, default='1000') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __unicode__(self): # __str__ on Python 3 return self.QuickQuiryBankKDB serializers.py class QuickQuiryBankKDBSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(QuickQuiryBankKDBSerializer, self).__init__(many=many, *args, **kwargs) class Meta: model = QuickQuiryBankKDB # fields = '__all__' fields = ['result'] views.py class QuickQuiryBankKDBViewSet(viewsets.ModelViewSet): queryset = QuickQuiryBankKDB.objects.all() serializer_class = QuickQuiryBankKDBSerializer def perform_create(self, serializer_class): if (serializer_class.validated_data['result'][2:8] == 'result'): json_text = serializer_class.validated_data['result'] json_unpacked = json.loads(json_text) for i in json_unpacked['result']['lists'][0]['resTrHistoryList']: resAccountTrDate = i['resAccountTrDate'] resAccountTrTime = i['resAccountTrTime'] resAccountOut = i['resAccountOut'] resAccountIn = i['resAccountIn'] resAccountDesc1 = i['resAccountDesc1'] resAccountDesc2 = i['resAccountDesc2'] resAccountDesc3 = i['resAccountDesc3'] resAccountDesc4 = i['resAccountDesc4'] resAfterTranBalance = i['resAfterTranBalance'] serializer_class.save(resAccountTrDate=resAccountTrDate, resAccountTrTime=resAccountTrTime, resAccountOut=resAccountOut, resAccountIn=resAccountIn, resAccountDesc1=resAccountDesc1, resAccountDesc2=resAccountDesc2, resAccountDesc3=resAccountDesc3, resAccountDesc4=resAccountDesc4, resAfterTranBalance=resAfterTranBalance) Hope to have a hint to solve the problem. Thank you! -
Django using reverse OneToOne in filter?
I have two models: class CustomUser(models.Model): ... class Profile(models.Model): user = models.models.OneToOneField(CustomUser) fielda = models.IntegerField() I'm trying to perform a filter query based on the value of a field on the Profile model from the CustomUser model but it's giving me the error name 'profile' is not defined CustomUser.objects.all().select_related('profile').filter(profile.fielda=0) I need to start the selection from CustomUser model because I have to prefetch other models with FK to CustomUser so I cannot simply start from Profile model -
save() prohibited to prevent data loss due to unsaved related object 'task_title'
I am Trying to create Task and inserting it's related information of intermediary model in intermediary table but I am getting below error. save() prohibited to prevent data loss due to unsaved related object 'task_title'. My models.py class Task(models.Model): id = models.AutoField(primary_key=True) task_audit_title = models.ForeignKey(MainAudit,on_delete= models.CASCADE, related_name='audit_title_for_task',verbose_name= ('Audit Title')) task_subtask_name = models.ManyToManyField(SubTask, related_name='subtask_for_task',verbose_name= ('Subtask Title')) task_subject = models.CharField(verbose_name= ('Task Subject'),max_length=100,blank=False) task_description = models.CharField(verbose_name= ('Task Description'),max_length=1000,blank=True) task_assign_to = models.ManyToManyField(User, related_name='task_assign_to', through='TaskComplete') task_assign_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_crt_by') task_deadline = models.DateTimeField(null=True,blank=True) task_perticulars = models.ManyToManyField(Perticular, related_name='task_perticular', blank=True) task_created_time = models.DateTimeField(default=timezone.now) task_modified_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_mod_by', null=True, blank=True) task_modified_time = models.DateTimeField(null=True,blank=True) is_del = models.BooleanField(default=0) class Meta: permissions = ( ("change_temp_delete_task", "Can delete temporarily"), ) def __str__(self): return self.task_subject def get_absolute_url(self): return reverse('create-task') class TaskComplete(models.Model): id = models.AutoField(primary_key=True) task_title = models.ForeignKey(Task,on_delete= models.CASCADE, related_name='assigned_task') is_completed = models.BooleanField(default=0) task_cmt_by_doer = models.CharField(verbose_name= ('Submit Comment'),max_length=100,blank=True) completed_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name = 'task_completed_by') completed_time = models.DateTimeField(null=True,blank=True) My views.py class TaskCraeteView(LoginRequiredMixin,CreateView): model=Task success_message = " Task Craeted successfully!" reverse_lazy('create-task') login_url = 'login' template_name = 'create-task' form_class = TaskCreateForm def form_valid(self,form): print(self.kwargs) for users in form.cleaned_data['task_assign_to']: TaskComplete.objects.create(completed_by=users, task_title= form.instance) form.instance.task_assign_by = self.request.user return super(TaskCraeteView, self).form_valid(form) How Can i insert the data in intermediary table while creating task? I tried to get Primary key … -
django filter duplicates in one table to serialize in json
in the database i have some duplicate Customers and they have one field similar. i can't get json so that this similar field would be the key and other info would be fields inside this key Customers = Customer.objects.values('id','fNameEng', 'lNameEng','crmId').filter( billingId__gt=0, crmId__gt=0).order_by('crmId') this filter selects all the customers with (crmId and billingId) > 0 there are some customers who have same crmId.I want to select duplicates and get them into json like this { "6275": { // this would be crmId "0":{ "id": 5, "fNameEng": "Alise", "lNameEng": "Dupan chang" } "1":{ "id": 10922, "fNameEng": "Alise", "lNameEng": "Dupan chang" } } } but with filter specified above i get something like this { "6275": { // this would be crmId "id": 5, "fNameEng": "Alise", "lNameEng": "Dupan chang" } }, { "6275": { // this would be crmId "id": 12135, "fNameEng": "Alise", "lNameEng": "Dupan chang" } } -
getting datetime when user logs-in
i made a django app which contains a user login form. I have used MySQL database in the app. when the of user logs-in the name and Hashed Password an entry is created in the database. As of now i m trying, to get the datetime in the database when the user logs-In. here's the code form.py from django import forms from django.contrib.auth.hashers import make_password from django.core import validators from first_app.models import Login from django.contrib.auth.models import User #some other code class authForm(forms.ModelForm): class Meta: model= Login fields = ["username","password",] models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User # Create your models here. class Login(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=32) date_and_time = models.DateField(auto_now_add=True) #<-- tried to add but it shows a non editable field def __str__(self): return self.username I want to store the datetime whenever the user logs-In thnx for the help. :-)