Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django signals post_save update
when the student enrollment record (discount type) is updated the student discount (discount type) is also updated, but what should i do if i want to update the student enrollment record (discount type) using student discount (discount type) This is my models.py class studentDiscount(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(pre_save, sender=StudentsEnrollmentRecord) def get_older_instance(sender, instance, *args, **kwargs): try: instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk) except StudentsEnrollmentRecord.DoesNotExist: instance._old_instance = None @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): if not created: older_instance = instance._old_instance if older_instance.Discount_Type != instance.Discount_Type: studentDiscount.objects.filter( Students_Enrollment_Records=instance ).delete() else: return None discount = studentDiscount.objects.filter(Discount_Type=instance.Discount_Type) if created: print("nagsulod") studentDiscount.objects.create( Students_Enrollment_Records=instance, Discount_Type=instance.Discount_Type) else: studentDiscount.objects.create( Students_Enrollment_Records=instance, Discount_Type=instance.Discount_Type) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) strands = models.ForeignKey(strand, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) ESC = models.ForeignKey(esc, on_delete=models.CASCADE,null=True,blank=True) Remarks = models.TextField(max_length=500,null=True,blank=True) if i update the student enrollment record (Discount_Type) the student discount (discount type) update as well but when i … -
Specify the --ssl option for django database connection
When I connect to my database with mysql I specify the option --ssl, or else I get the error SSL connection is required. Please specify SSL options and retry. I know that with MySQL you can connect with a ssl certificate where you have a copy of the certificate locally. With this approach I know how to move forward with Django, as you can specify the option as described here https://stackoverflow.com/a/12285601/2889451 However, in my case I simply pass the option --ssl, and I don't have a local copy of the certificate. How can I enable this option in Django? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': DB_HOST, 'PORT': '', } } -
Django 2.2 - Testing which DB my application is connected to
I'm hoping this will be similar to a few questions which have been previously answered. I was wondering what the full processes are for testing the DB connection string (not the DB name) for the current connected DB in Django is? I see a few methods for printing the name, but across local development and staging, these names will be the same. I need to know more, such as the db engine (e.g., is it PostgreSQL, or is it db.sqlite3. etc etc), and various other DB parameters. I'm currently trying to debug why a Celery beat task is failing to create database entries for the application DB I think I am connected to. I'm performing a simple obj, created = Object.objects.get_or_create() DB method, and on logging created, some are True and some are False. All good so far. However, the admin section of the Django CMS is not showing any more entries to the DB. I believe testing the location and connection strings of the DB the Django application is using might be useful in debugging this ghost object creation...unless someone can advise on similar issues they have had with the Celery daemon not actually persisting a DB create/update etc... -
how to order a queryset in Django model by relational foreign key
I have the following models models.py class Category(models.Model): label = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=255, blank=True) class Expense(models.Model): description = models.CharField(max_length=255, blank=True) amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) category = models.ForeignKey( Category, on_delete=models.CASCADE, null=True, related_name='category' ) class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.order_by("-expense__expense") I'm struggling to how to return a Category list ordered by the most picked category in the Expense model like: <Expense category=3> <Expense category=3> <Expense category=2> <Expense category=3> <Expense category=1> <Expense category=1> I want to return in this order: <Category id=3> <Category id=1> <Category id=2> -
Wagtail: How to pass model instance to a widget and access it in template
I have a model based on Wagtails Page model and I am assigning a custom widget to one of the models fields. Is it possible to make the model instance accessible in the widgets HTML-template when rendering the admin view? I need the widget in the admin view to know which ID the SimplePage has the widget belongs to, i.e. get the value of {{ page.id }}. # models.py class SimplePage(Page): name = RichTextField(blank=True) geom = PointField() content_panels = Page.content_panels + [ FieldPanel("name"), FieldPanel("geom", widget=LeafletWidgetWithMedia()), ] # widgets.py class LeafletWidgetWithMedia(LeafletWidget): include_media = True template_name = "admin/widget.html" I know I can update the context of my widget like so: # widgets.py […] def get_context(self, name, value, attrs): value = None if value in validators.EMPTY_VALUES else value context = super(LeafletWidget, self).get_context(name, value, attrs) context.update(self._get_attrs(name, attrs)) return context But I can't figure how to get my SimplePage instance into the widget to update the context. (I also tried Wagtails before_edit_page hook w/o success.) -
Setting up Django on CentOS 7 using nginx and gunicorn getting 502 gateway
Setting up Django in this new environment and finding that gunicorn sock file is throwing a permission denied error. 2020/01/24 09:52:23 [crit] 2954#0: *1 connect() to unix:/run/gunicorn.sock failed (13: Permission denied) while connecting to upstream, client: 197.237.29.12, server: 165.22.65.26, request: "GET /admin/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin/", host: "165.22.65.26" here's the settings for the gunicorn file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/webapp/fortnox ExecStart=/home/sammy/envs/fortnox/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ fortnox.wsgi:application [Install] WantedBy=multi-user.target and the server embedded in /etc/nginx/nginx.conf since the OS doesn't come with similar setup as Ubuntu so sites-enabled isn't available and trying to add it and link it threw an error so this method recommended is what I went with. server { listen 80; server_name 165.22.65.26; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/webapp/fortnox; } location /media/ { root /home/sammy/webapp/fortnox; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/gunicorn.sock; } } both of them checking status are running ok without issues so what I've got is this recommendation on how the sock file permission from parent down should be namei -l /run/gunicorn.sock f: /run/gunicorn.sock drwxr-xr-x root root / … -
Sending username from django-mysql database to s3
I want to send my username from my mysql to s3 for create directory of that particular username ,What are the options to do this? I got this error in directory structure of s3: django.db.models.fields.related.ForeignKey -
Django - dynamically create formsets for different number of input fields
Currently I'm working on a webpage in django 2.2. I came to a point where user input is required. The problem is, that the number of forms changes depending on the instance of the object. Where the object is composite of multiple objects. So for example at one instance I have like 100 people taking a test with 5 sub tasks. The form i want to archive is one where the data of the people is displayed and an input field for every sup task. At another instance I have a different number of people taking a test with a different number of sub tasks. I had a solution which was rather slow (it took well over 5 mins to render the view/template) because of a forloop which created a form/formset for every person which has taking part on the test. Does anyone could point me at the right direction for this kind of form/formset? Currently I'm stuck with this: class Edit_Punkte(forms.Form): person = None vermerk = forms.ChoiceField( label='', choices=Note.VERMERK, required=False ) zulassung = forms.BooleanField(label='', required=False) punkte = None def __init__(self, e=1, person=None, vermerk=None, zulassung=None, prefix=None, *args, **kwargs): super(Edit_Punkte, self).__init__(*args, **kwargs) formset = forms.modelformset_factory(model=Punkte, fields=('punkte', 'person', 'teilaufgabe'), extra=e) self.punkte = … -
Django, group by one field, only take the latest / max of each group and get back the ORM objects
I have the following Django (3.0) ORM model: class Portfolio(models.Model): code = models.CharField(max_length=20) name = models.CharField(max_length=100) date = models.DateField() created = models.DateTimeField(blank=True, null=True, auto_now_add=True) I want to group them by the code field and for each code only take the portfolio that has the max date I know I can use the following query: Portfolio.objects.values('code').annotate(latest=Max('date')) But it has three problems: It gives me only the code and latest fields, so I lose the other fields It gives back a dictionary, while I want a list of actual Portfolio objects Max works because date is a DateField. It would also work on other numeric field types, but what if I want to order the records by the value of a CharField (lexicographic order), for instance name and take the first record for each group? So, to sum up my question: How do I use Django ORM to retrieve a list of ORM Objects grouped by one or more fields and have back only the first record of each group given an arbitrary "order by" clause? Thanks -
redirecting to a different domain using python django by setting a cookie to a react application
I have a portal application, so users are logging to that application and the application is written in python django (1.8.17), so from the application i will be adding a link when users clicking on that i am redirecting to my another application which is hosted in a different domain. The application is build using react (using cra) and used ngnix for serving the files. Using Docker to build the image and for cicd. Since my application shows some table data i am not using nodejs because i am just consuming some services and showinng that data. So the current problem is as i read more, from django portal you can't add a cookie and redirect, currently i am able to redirect but the cookie is not set for the redirected url. So here is my below python django code for redirect. How can i set a cookie by redirecting @permission_required('users.page_live', login_url='/admin/') def users_view(request): try: user_list = UsersConfig.objects.get(meta_key="ALLOWED_USERS") user_list = [int(x) for x in user_list.meta_value.split(",")] sessionId = 0 if request.user.id not in user_list: redirect_url = "http://mes.meta.in/admin" try: if settings.ENV == 'PROD': redirect_url = "https://data-frontend.production.us.mes.cloud/" else: redirect_url = 'https://data-frontend.staging.us.me.s/' response = HttpResponseRedirect(redirect_url) except Exception as e: print e response = HttpResponseRedirect("/admin") … -
Django internationalisation: how to translate thesaurus models?
I use internationalization in my project. I've just add thesaurus models (below) with 2 classmethod and a templatetags in order to return label in forms and template respectively But I wonder how can I translate text label contain in tables? Should I translate in tables and test for browser language or something like that? Is there an easiest way to do it in Django? models.py # modèle thésaurus repris de l'étude Princesse (C Yao) class Thesaurus(SafeDeleteModel): """ A class to create a thesaurus variable instance. """ _safedelete_policy = SOFT_DELETE_CASCADE the_ide = models.AutoField(primary_key=True) the_lab = models.CharField("Libellé", max_length=150) log = HistoricalRecords() class Meta: db_table = 'adm_the' verbose_name_plural = 'Thesaurus' ordering = ['the_ide'] def __str__(self): return f"{self.the_ide} : {self.the_lab}" @classmethod def options_list(cls, the_ide): """ return the list of response options for a thesaurus variable. """ the = Thesaurus.objects.get(pk=int(the_ide)) the_opts_set = OptionDeThesaurus.objects.filter(the=the) the_opts_list = [(opt.the_opt_cod, opt.the_opt_lab) for opt in the_opts_set] the_opts_list.insert(0, (None, '')) return the_opts_list @classmethod def option_label(cls, the_ide, the_opt_cod): """ Return an response option label. """ the = Thesaurus.objects.get(pk=int(the_ide)) the_opt = OptionDeThesaurus.objects.get(the=the, the_opt_cod=the_opt_cod) return the_opt.the_opt_lab class OptionDeThesaurus(SafeDeleteModel): """ A class to create a response option instance for a thesaurus variable. """ _safedelete_policy = SOFT_DELETE the_opt_ide = models.AutoField(primary_key=True) the = models.ForeignKey(Thesaurus, verbose_name='Thesaurus', related_name='options', on_delete=models.CASCADE) … -
Django javascript fetch post method problem
I have problem with javascript fetch post method Django get my request as key not key => value Javascript async function postData(url = '', data = {}, header) { let body = JSON.stringify(data) let headers = header; const response = await fetch(url, { method: 'POST', credentials: 'include', headers, body}); return await response.json(); } share.onclick = () => { titul = title.value; cont = content.value; postData('createPost/', { title: titul, content: cont, },{ 'X-Requested-With' : 'XMLHttpRequest', 'X-CSRFToken' : csrftoken, "Accept": "application/json", // 'Content-Type': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', }).then((data)=>{ console.log(data); }) }; views.py def js_request(request): if request.method == 'POST': form = PostsForm(request.POST) if form.is_valid(): return JsonResponse({'status' : 'OK'}) return JsonResponse({'status' : 'Maybe', 'request' : request.POST}) return JsonResponse({'status' : 'BAD'}) Chrome Console * status: "Maybe" request: {"title":"scaknsakc","content":"asckcksac"}: "" //// key : ' ' * -
Django rest framework serializer key error
I was using a standard Django user model but then requirements changed and I had to resort to an abstract user model. I updated my serializer to reflect the changes in model fields as well as form fields but I'm now getting an error when attempting to creating a user object. The error message is KeyError: 'unl_email' but also shows up for all the other fields. The validated_data for the create() function in serializers.py appears to be empty when I print. What am I doing wrong? Views.py class SignUp(CreateAPIView): def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def create(self, request, *args, **kwargs): serializer = SignUpSerializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response({"success": "Registration succesful"}, status=status.HTTP_201_CREATED) def perform_create(self, serializer): serializer.save() Models.py class User(AbstractUser): unl_num = models.AutoField(primary_key=True) unl_usu_num = models.IntegerField(blank=True,null =True) unl_date_added = models.DateField(default=timezone.now) unl_name = models.CharField(max_length=256) unl_surname = models.CharField(max_length=256) unl_email = models.EmailField(max_length=200, unique=True) unl_mobile = models.CharField(max_length=256) unl_identity= models.CharField(max_length=256) unl_oss_num= models.CharField(max_length=256) unl_race= models.CharField(max_length=32) unl_gender= models.CharField(max_length=32) unl_disability= models.CharField(max_length=32) unl_location= models.CharField(max_length=256) unl_province= models.CharField(max_length=256) unl_avatar= models.CharField(max_length=256) USERNAME_FIELD = 'unl_email' Serializers.py class SignUpSerializer(serializers.Serializer): class Meta: model = User fields = ('unl_email','password','unl_name', 'unl_surname','unl_mobile','unl_identity', 'unl_oss_num','unl_race','unl_gender','unl_disability', 'unl_location','unl_province','unl_avatar' ) password = serializers.CharField(write_only=True) def create(self, validated_data): user = User.objects.create( unl_email=validated_data['unl_email'], unl_name=validated_data['unl_name'], unl_surname=validated_data['unl_surname'], unl_mobile=validated_data['unl_mobile'], unl_identity=validated_data['unl_identity'], unl_oss_num=validated_data['unl_oss_num'], unl_race=validated_data['unl_race'], unl_gender=validated_data['unl_gender'], unl_disability=validated_data['unl_disability'], unl_location=validated_data['unl_location'], unl_province=validated_data['unl_province'], unl_avatar=validated_data['unl_avatar'] ) user.set_password(validated_data['password']) … -
How to pass queryset in django celery
I'm trying to build Instagram bot using django. I want to implement django celery to run task in the background. Here I'm facing some problem. task.py from celery import shared_task from projects.services.instagram_bot import InstagramBot @shared_task def lazy_post_link_1_task(post_url, current_user, bot_id, email, password, time_interval, comments): instagram_bot = InstagramBot() instagram_bot.comment_on_post(post_url, current_user, bot_id, email, password, time_interval, comments) views.py for bot in lazy_bots: lazy_bot_filter_comments = Comments.objects.all().exclude(botscomment__bot_id=bot.id)[ :int(no_of_comment_for_lazy_bot)] lazy_post_link_1_task.delay(lazy_post_link_1, request.user, bot.id, bot.email, bot.password, lazy_bot_time_interval, lazy_bot_filter_comments) I'm facing error something like this I didn't know what I'm mission -
AttributeError at /admin 'AnonymousUser' object has no attribute 'first_name'
I've deployed my Django project on Heroku. Now when I'm trying to access the admin page url/admin, I'm getting AttributeError at /admin 'AnonymousUser' object has no attribute 'first_name' If I'm running the same code locally, there's no issue with the admin page. It opens fine. So problem is with this line actually in views.py /app/exam/views.py in topic_view Line:59 | fname = request.user.first_name So my problem is why views.py is being called when I'm trying to open the admin site. -
ValueError: Cannot quote parameter value <django.contrib.postgres.fields.jsonb.JsonAdapter
I am getting this error when i try to applying migrations using python manage.py migrate. I am using sqlite3. My model has a JSONField in it. Kindly any ideas how to fix this. Below is a snippet of the whole exception. Operations to perform: Apply all migrations: account, admin, auth, blog, contenttypes, sessions, sites, small_small_hr, socialaccount Running migrations: Applying small_small_hr.0011_auto_20200124_1128...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\migrations\operations\fields.py", line 112, in database_forwards field, File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 327, in add_field self._remake_table(model, create_field=field) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 188, in _remake_table self.effective_default(create_field) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 64, in quote_value raise ValueError("Cannot quote parameter value %r of … -
How to pass variable from details method to downloader method?
I want to pass the link user entered on a form to the downloader method. from django.shortcuts import render import pytube from .forms import VideoDownloadForm # Create your views here. def details(request): if request.method == 'POST': form = VideoDownloadForm(request.POST, request.FILES) if form.is_valid(): f = form.cleaned_data['Url'] yt = pytube.YouTube(f) # videos = yt.streams.filter(progressive=True, type='video', subtype='mp4').order_by('resolution').desc().first() thumb = yt.thumbnail_url title = yt.title return render(request, 'ytdownloader/details.html', { 'title': title, 'thumbnail': thumb}) downloader(yt) else: form = VideoDownloadForm() return render(request, 'ytdownloader/front.html', {'form': form}) def downloader(request, yt): videos = yt.streams.filter(progressive=True, type='video', subtype='mp4').order_by('resolution').desc().first() videos.download('C:\\Users\\user\\Downloads') return render(request, 'ytdownloader/details.html') Error: *Exception Type :TypeError Exception Value :downloader() missing 1 required positional argument: 'yt'* -
Getting an error while integrating django-private-chat in my django project?
I am newbie to django I want a one to one chat feature in my django application so I had downloaded the django-private-chat app as pip install django-private-chat and in settings.py included 'django-private-chat' in INSTALLED APPS getting error as ModuleNotFoundError: No module named 'django-private-chat' I had included the traceback also please help me out -
Django formset: Unable to save
Trying to setup simple formset, but getting errors 'SWDataForm' object has no attribute 'save' MODEL class SWData(ValidateOnSaveMixin, models.Model): serial = models.ForeignKey(SWInfo, related_name='serial_items', on_delete=models.SET_NULL, null=True) hostname = models.CharField(max_length=20, default='', unique=True) deployed = models.BooleanField() class Meta: verbose_name_plural = "SWDATA" def __str__(self): return "{0}".format(self.hostname) FORM class SWDataForm(forms.Form): serial = forms.ModelChoiceField(queryset=SWInfo.objects.all()) hostname = forms.CharField(max_length=20) deployed = forms.BooleanField() SWDataFormset = formsets.formset_factory(SWDataForm) VIEW def display_data(request, data, **kwargs): return render(request, 'web/posted-data.html', dict(data=data, **kwargs)) def swdata(request, formset_class, template): #hostname = None if request.method == 'POST': formset = SWDataFormset(request.POST) for counter, form in enumerate(formset.forms): if formset.is_valid(): obj = form.save(commit=False) # if counter>0: # obj.hostname = hostname #obj.auditor = request.user obj.save() # if counter == 0: # hostname = obj.hostname data = form.cleaned_data return display_data(request, data) else: formset = formset_class() return render(request, template, {'formset': formset}) Unable to save or display form. Spend a lot of time figure it out, still no luck. Getting errors, when adding the obj.save() doesn't have save. -
Copying data from parent model instance when child model instance is saved
I have a parent model which contains a database of unique records, as follows (truncated - there are many more fields): models.py - parent class DBPlatform(models.Model): description = models.CharField(max_length=300, unique=True) PDS_date = models.DateField() PDS_version = models.CharField(max_length=50, blank=True) I use this model to create a child model to save me copying all of the fields. The child model saves specific user-generated instances of the parent records. They are stored separately as they may be edited by the user: models.py - child class Platform(DBPlatform): scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE, related_name="platforms") database_platform = models.ForeignKey(DBPlatform, on_delete=models.CASCADE, related_name="instances") edited = models.BooleanField() I am using Django REST Framework to create an API for the eventual app. When a child model is created, I want to update all of its inherited fields with those of the parent model. The incredibly convoluted steps I have taken so far (that do not work) are in the views.py file of the child mode. As follows: api.views.py - child class PlatformViewSet(viewsets.ModelViewSet): lookup_field = "id" serializer_class = PlatformSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): db_id = self.request.data["database_platform"] database_platform = get_object_or_404(DBPlatform, id=db_id) datadict = self.request.data.dict() datadict.update(database_platform.__dict__) query_dict = QueryDict('', mutable=True) query_dict.update(datadict) self.request.data = query_dict serializer.save() How can I achieve what I am looking to … -
How to add default value in queryset?
I have a moneybook, moneylog models and moneylog get relation with moneybook manytomany. moneybook = models.ForeignKey( moneybook_models.Moneybook, on_delete=models.CASCADE) pay_day = models.DateTimeField(default=NOW) payer = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="payer") dutch_payer = models.ManyToManyField( user_models.User, related_name="dutch_payer", blank=True) price = models.IntegerField() category = models.CharField(max_length=10) memo = models.TextField() I want payer default save in dutch_payer if user choose or not. and this is my forms.py class CreateMoneylogForm(forms.ModelForm): class Meta: model = models.Moneylog fields = ( "pay_day", "payer", "dutch_payer", "price", "category", "memo", ) widgets = { "dutch_payer": forms.CheckboxSelectMultiple } def save(self, *args, **kwargs): moneylog = super().save(commit=False) if moneylog.payer not in moneylog.dutch_payer: moneylog.dutch_payer.add(moneylog.payer) return moneylog as you see. if moneylog.payer not in moneylog.dutch_payer: moneylog.dutch_payer.add(moneylog.payer) return moneylog this not work. how can i achieve it? -
Django Admin Page Shuts down immediately
whenever i start the server at http://127.0.0.1:8000 the page loads perfectly but when i add the admin page, the server shuts instantly without any error alert on the terminal. (envr4) C:\Users\xxxx\djangoprojects\personal>python manage.py createsuperuser Username (leave blank to use 'xxxxxxxx'): Email address: xxxxxxxxxxxxx@gmail.com Password: Password (again): Superuser created successfully. (envr4) C:\Users\nelso\djangoprojects\personal>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). January 24, 2020 - 11:00:32 Django version 3.0.2, using settings 'my_portfolio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [24/Jan/2020 11:00:40] "GET / HTTP/1.1" 404 2037 Not Found: /favicon.ico [24/Jan/2020 11:00:42] "GET /favicon.ico HTTP/1.1" 404 2088 [24/Jan/2020 11:00:54] "GET /admin/ HTTP/1.1" 302 0 [24/Jan/2020 11:00:55] "GET /admin/ HTTP/1.1" 302 0 [24/Jan/2020 11:00:56] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [24/Jan/2020 11:00:57] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [24/Jan/2020 11:00:57] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [24/Jan/2020 11:00:57] "GET /static/admin/css/responsive.css HTTP/1.1" 200 18052 [24/Jan/2020 11:00:57] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [24/Jan/2020 11:00:57] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0 [24/Jan/2020 11:00:58] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0 [24/Jan/2020 11:00:58] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0 [24/Jan/2020 11:01:14] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 (envr4) C:\Users\xxxxx\djangoprojects\personal> -
How to override "save_model" method ModelAdmin for User model?
I try to change logic for saving data in Django admin. I overriding save_model but i get error "<User: test_user>" needs to have a value for field "id" before this many-to-many relationship can be used. class UserAdminForm(forms.ModelForm): middle_name = forms.CharField(label='Middle name') class Meta: labels = { 'last_name': 'Last name', 'first_name': 'First name', 'password': 'Password', } class UserAdmin(admin.ModelAdmin): form = UserAdminForm fields = ['username', 'password', 'last_name', 'first_name', 'middle_name', 'groups'] list_display = ['username', 'last_name', 'first_name', ] def save_model(self, request, obj, form, change): print(form) -
Model formset always sends None value to the view
I am using Model Formset to handle multiple instances of a form. However the data inside the forms is always None even if I fill it. This is the error I get. I am completely new to the concept of ModelFormSet, this would be really easy to do through API but I am not allowed to do so. django.db.utils.IntegrityError: null value in column "CODE_MAP_ID" violates not-null constraint DETAIL: Failing row contains (5, null, null, null, null, null). models.py class Codemap(models.Model): code_map_id = models.IntegerField(db_column='CODE_MAP_ID') # Field name made lowercase. type = models.CharField(db_column='TYPE', max_length=50, blank=True, null=True) # Field name made lowercase. input_value = models.CharField(db_column='INPUT_VALUE', max_length=100, blank=True, null=True) # Field name made lowercase. output_value = models.CharField(db_column='OUTPUT_VALUE', max_length=100, blank=True, null=True) # Field name made lowercase. display_label = models.CharField(db_column='DISPLAY_LABEL', max_length=100, blank=True, null=True) # Field name made lowercase. class Meta: db_table = 'CODEMAP' managed = False forms.py class CodeMapFinal(ModelForm): class Meta: model = Codemap fields = ('input_value', 'output_value',) views.py class CodeMapView(View): template_name = 'tabledata/code-map.html' def get(self, request): codemap = Codemap.objects.all() codemap_formset = modelformset_factory(Codemap, form=CodeMapFinal, can_delete=True) return render(request, self.template_name, context={'rows': codemap, 'formset': codemap_formset}) def post(self, request): forms = CodeMapFinal(request.POST) if forms.is_valid(): forms.save() return HttpResponse("asdfasdfasdf") template.html <div id="form-div" hidden="hidden"> <h3>Code Map</h3> <form action="" method="post"> {% csrf_token %} {{ … -
New HTML page to the existing page
I have an HTML page that contains some details. I would like to add a blog listing below. Blog listing is Paginated in the same view. View class WhoWeAreView(TemplateView): template_name = 'who_we_are.html' @csrf_exempt def get(self, request, *args, **kwargs): whoweare_data = WhoWeAre.objects.all() blog_list = Blog.objects.all() page = request.GET.get('page', 1) paginator = Paginator(blog_list, 4) try: blogs = paginator.page(page) except PageNotAnInteger: blogs = paginator.page(1) except EmptyPage: blogs = paginator.page(paginator.num_pages) context = { 'whoweare': whoweare_data, 'blog': blogs, } return render(request, self.template_name, context) Template <div class="row"> {% for whoweare in whoweare %} <div class="col s12 m6 l4"> <div class="team-member"> <div class="team-img"><img src="{{ MEDIA_URL }}{{ whoweare.logo.url }}" width="55" height="55"></div> <h3 class="team_name">{{ whoweare.tittle }} </h3> <p class="team_text">{{ whoweare.description }} </p> </div> </div> {% endfor %} </div> {% for blog in blog %} <div class="container-full"> <div class="who_mainhead">{{ blog.tittle }}</div> <div class="who_maintext">{{ blog.short_description }} </div> </div> {% endfor %} {% if blog.has_next %} <div class="who_bigbtnblock"> <a href="?page={{ blog.next_page_number }}"> <button class="btn waves-effect waves-light who_mainbtn_big" type="submit" name="action"> View More </button> </a> </div> {% endif %} The pagination works. The paginated data should be a continuation of the same page as per my requirement. But now it reloads the entire page Existing Structure whoweare_data blog_1 blog_2 blog_3 blog_4 View more (button) …