Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert Django ImageField to binary data
I have an image that is stored on Amazon S3. It is connected to a model through an ImageField. I would like to get the binary data of that file. Should I use the requests module to fetch the image? Or is there a more elegant way through Django to achieve this? Thanks -
How Do I Recreate An AWS EB Django App From Config Files?
I want to make sure I have saved enough info/config data to be able to completely delete my AWS EB App and then at a later time recreate it using the saved configs/code etc. I am just getting started with AWS and EB. I created a very basic Django app that uses a Postgres DB provided by AWS RDBMS service. Here is what I have so far (all the below is in a a git repo): website code .elasticbeanstalk/config.yml (generated automatically at env creation) a file that contains the output of the command eb config I am assuming this is the same file(s) that are stored automatically on S3. I assume this is not generated locally .ebextentions files I DONT Have: localsettings.py stored in S3 Any Database info including dumps or config Last time I deleted the database I could not recreate it with the same identifier. Is this by design or did I just do it wrong? -
Django - No column found for custom field?
I'm having an issue creating a custom field for a user in Django currently. Ideally, I would want to create a custom field for a "CustomProgressBar" class that updates depending on the parameter "donations" passed into it and should be different for each user. Whenever I try to access an account on the server it returns "django.db.utils.OperationalError: table donorportal_profile has no column named progress". I have tried multiple times to makemigrations, migrate, and syncdb. I think there is an issue where I am not converting it to/from the database a certain way. I'm also unsure what to put in the parameters when I create the field in the model class. Any code relevant to my issue is attached below. I'm new to Django, so thank you for any help you can provide me! class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=40, default='') state = models.CharField(max_length=2, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) progress = user_assets.ProgressField() class CustomProgressBar: def __init__(self, donations): self.money = donations if 0 <= donations < 25: self.tier = 0 self.percent = donations / 25 elif 25 <= donations < 250: self.tier = 1 self.percent = donations / 250 elif 250 <= donations < 2500: self.tier = … -
Django foreign key for FileField and only show uploaded files associated with new request
When the user loads file(s), the selected files are immediately uploaded to the server into one pool of files that don't have any relation to the service request. If the user were to begin another new request, it would show all of the files uploaded to that point. How do I go about setting the relationship between the RequestAttachment model to the ServiceRequest model? I understand it is a one to many relationship, but this is my first time jumping into foreignkeys and I'm lost. When a new service request is initiated, it should not show any files uploaded. When uploading files as part of the request, what is the best way to go about? Immediately save to the server then set up relationship to respective request? Somehow hold the file until the request is submitted then commit all data (service request and the request attachment file) to the server? I'm almost positive this is too much for one question, and I'm not necessarily looking for a firm solution. A bump in the right direction is appreciated as much as the final solution. models.py class ServiceRequest(models.Model): CATEGORY_CHOICES = ( (None, ''), ('aircraft_repair', 'Aircraft Repair'), ('backshop', 'Backshop'), ('documentation', 'Documentation'), ('other', 'Other') … -
Retrieve Django media files from render.com disk
I'm deploying my Django application via render.com and I'm using a disk to serve the media files uploaded by the user. I can tell that the media files are being uploaded to the right place by using the render.com shell: Image files appear in the media folder However, when I try retrieving the image files in my website template, they don't appear. Images aren't appearing on the website My MEDIA_ROOT is "/var/www/[mysite].onrender.com/media/" ([mysite] replaced with the application name) and my MEDIA_URL is '/media/'. On render, the mount path of my disk is '/opt/render/project/src/media/'. -
Can't start test server with python django
I'm new to the Django framework and just trying to create a basic website, but when I try to open the server with the python manage.py runserver I get this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 601, in run_with_reloader exit_code = restart_with_reloader() File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 230, in restart_with_reloader p = subprocess.run(args, env=new_environ, close_fds=False) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\run\__init__.py", line 145, in __new__ process = cls.create_process(command, stdin, cwd=cwd, env=env, shell=shell) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\site-packages\run\__init__.py", line 121, in create_process shlex.split(command), File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\shlex.py", line 310, in split return list(lex) File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\shlex.py", line 299, in __next__ token = self.get_token() File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\shlex.py", line 109, in get_token raw = self.read_token() File "C:\Users\siuba\AppData\Local\Programs\Python\Python37\lib\shlex.py", line 140, in read_token nextchar = self.instream.read(1) AttributeError: 'list' object has no attribute 'read' Does anyone know the answer? If so please help! Thanks -
Adding profile picture to registration page
In Django Administration I can add profile pictures to the custom made user model. Here is the models.py file. class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user non superuser admin = models.BooleanField(default=False) # superuser timestamp = models.DateTimeField(auto_now_add=True) profilepicture = models.ImageField(upload_to=upload_image_path, null=True, blank=True) # confirm = models.BooleanField(default=False) # confirmed_date = models.DateTimeField(default=False) USERNAME_FIELD = 'email' #username # USERNAME_FIELD and password are required by default REQUIRED_FIELDS = [] #['full_name'] #python manage.py createsuperuser Here is forms.py. User = get_user_model() class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name', 'email', 'profilepicture') #'full_name',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user Here is register.html. {% extends "base.html" %} {% block content %} <div class="container"> <div class='row'> <div class='col-5'> <form method='POST'> {% csrf_token %} … -
Django annotate queryset with list from related model
This is my first time using Django querysets in such detail so I am a little confused. I have two models: Asset: id = models.BigIntegerField(primary_key=True, db_index=True, editable=False) asset = models.CharField( max_length=255, null=False ) ip = models.CharField( max_length=255, null=True, ) entity = models.ForeignKey( Entity, on_delete=models.CASCADE, related_name="owned_assets", db_constraint=False, ) Software (Django model, table not managed by Django though): id = models.BigIntegerField(primary_key=True, db_index=True, editable=False, null=False) entity = models.ForeignKey( Entity, db_constraint=False, null=False, ) asset = models.ForeignKey( Asset, db_constraint=False, null=False ) software = models.CharField( max_length=64, null=False ) version = models.CharField( max_length=64, null=False ) When a user GETs all assets, I want to decorate the Asset queryset with the related Software. A software entry is not unique across asset and entity though, a single asset can have multiple software entries associated with it. What would be the best way to go about annotating the base Asset queryset with these software entries? How do I add a list of software and version to a single Asset in the queryset? Is it possible to do this in the DB and not in memory? Thank you -
Problems sending emails in post save signal in Django
I'm trying to send a email after save some model in a post_save signal but when I save the model by first time the email is not sent, if I save the model a second time the email is sent. Notes The model has a ManyToMany field so I can't use pre_save signal because it throws a error: <mymodel: mymodel_name object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. What I have Model class Message(TimeStampedModel, models.Model): """Representation of a Message.""" recipients = models.ManyToManyField( to=settings.AUTH_USER_MODEL, verbose_name=_("Recipients") ) subject = models.CharField( verbose_name=_("Subject"), help_text=_( "150 numbers / letters or fewer. Only letters and numbers are allowed." ), max_length=150, validators=[alphabets_accents_and_numbers], ) content = models.TextField(verbose_name=_("Message")) Signal @receiver(signal=post_save, sender=Message) def send_message(sender, instance, **kwargs): """Send a email or Whatsapp if a new message is created.""" recipient_emails = [recipient.email for recipient in instance.recipients.all()] attachments = [] if instance.messagefile_set: for message_file in instance.messagefile_set.all(): attachments.append((message_file.file.name, message_file.file.read())) send_mails( subject=instance.subject, message=instance.content, recipient_list=recipient_emails, attachments=attachments, ) Send mail wrapper to send emails This is the function used in the signal to send emails. def send_mails( subject: str, message: str, recipient_list: List[str], from_email: Optional[str] = None, **kwargs, ) -> int: """Wrapper around Django's EmailMessage done in send_mail(). … -
django subracting datetime fields
I am using an model which has fields named start_time and finish_time, both are DateTimeField, I'm trying to calculate the response time by subtracting finish_time with start_time. In shell: >>> obj = Quizgame.objects.get(user=harry) >>> start = obj.start_time >>> end = obj.finish_time >>> result = end - start >>> result datetime.timedelta(seconds=31, microseconds=912224) But In django Views, when I perform this I'll get an error of unsupported operand type(s) for -: 'method' and 'datetime.datetime' views.py def final_part(request): obj = Quizgame.objects.get(user=request.user) start = obj.start_time end = obj.end_time result = end - start return HttpResponse(result) -
Problem in handling User and forms.py in django
I am building a blogging website where users can register and log in and start posting their blogs. Now in the form where they are asked to write their article and stuff. I want a field in the form where their usernames need to be displayed. I used Django Forms for the purpose. Now instead of displaying their username, a dropdown menu shows up displaying the username of all the users. My code is: models.py: class Writer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) email = models.EmailField(unique=True) profile_pic = models.ImageField(upload_to = 'Bloggers') bio = models.TextField() def __str__(self): return self.user.username class Post(models.Model): title = models.CharField(max_length=25) cover = models.ImageField(upload_to='Blog Image') content = models.TextField() username = models.ForeignKey(Writer, on_delete=models.CASCADE) def __str__(self): return self.title forms.py: class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class WriterForm(ModelForm): class Meta: model = Writer fields = '__all__' exclude = ['user'] class PostForm(ModelForm): class Meta: model = Post fields = '__all__' views.py: def writewithus(request): form = PostForm(initial={'username': request.user.username}) # form.fields["username"].initial = request.user.username print(form) if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): print("Hello") # form.cleaned_data.get('title') = 'Hahaha' form.save() if form.save(): print("HEY") return redirect('/') else: print (form.errors.as_data()) context = {'form':form} return render(request, 'Blog/writewithus.html', context) -
Can I create a field in django-model depending of an other?
I created a class Lesson, I want to give the ability to an admin to add 1, 2, 3 or more textfields and other fields. For now I do like that : class Lesson(models.Model): title = models.CharField(max_length=50) text1 = models.TextField(default="") text2 = models.TextField(default="", blank=True, null=True) text3 = models.TextField(default="", blank=True, null=True) ... But in admin side it's not really nice Does it exist a way to define a first field : models.IntegerChoices where the admin choose 10 for example and it automatically generates 10 textfields and so generate 10 columns in database ? Thank's for reading -
Django Rest Framework: Why does PrimaryKeyRelatedField document as a string in the schema when read_only?
I have a serializer with a PrimaryKeyRelatedField: field_name = serializers.PrimaryKeyRelatedField(queryset=ModelClass.objects.all(), read_only=False) With this setup, the Schema properly identifies the parameter as an integer (the PK). But, when I change to: field_name = serializers.PrimaryKeyRelatedField(read_only=True) (it will not let you specify queryset and read_only at the same time) then the parameter is identified as a string in the Schema. Why would this be? Is this correct/expected behavior or perhaps a bug? -
Django Python Version 3.6.10 to 3.6.11 Heroku
I have a Django application deployed on Heroku, it has been deployed for months with no issue. Deployments today are suddenly failing saying Heroku doesn't support Python 3.6.10, only 3.6.11 (closest one to 3.6.10) I havent specified a version anywhere in my app so I can only assume Django defaults to 3.6.10 or Heroku previously did, but they have abruptly stopped supporting it now. Are there any risks in setting 3.6.11 in my runtime file so my builds work? Is there any reason it defaults to 3.6.10? The app is in use heavily and Heroku support is awful unless you pay 1000 a month so I can't afford it to fail, and if it does, I can't revert to 3.6.10! Thanks so much for any help -
Updateddates are absent in RSS feed
Django 3.0.8 feeds.py class RssFeed(Feed): title = "Pcask.ru: все о компьютерах, гаджетах и программировании." link = get_site_address() description = "Новости, статьи, фотографии, видео о компьютерах и программировании." def items(self): # All evergreen posts and fresh news (just exclude old news). # Django taggit doesn't support excluding, only filtering. (https://django-taggit.readthedocs.io/en/latest/api.html#filtering) # Therefore we have to exclude items via an id list. excluded_items = Post.published.filter(tags__slug__in=[SPECIAL_TAGS.NEWS.value], updated__lte=timezone.now()-timedelta(days=NEWS_LIFESPAN)) return Post.published.exclude(id__in=get_id_list(excluded_items))[:NUMBER_OF_ITEMS] def item_title(self, item): return item.title def item_description(self, item): return item.description def item_categories(self, item): return (item.category.title,) feed_copyright = 'Все права защищены (c) {}, {}'.format(timezone.now().year, get_site_address()) def item_enclosure_url(self, item): featured_image = item.get_featured_image() img_field = getattr(featured_image, ENCLOSURE_WIDTH) enclosure_url = img_field.url return enclosure_url def item_enclosure_mime_type(self, item): featured_image = item.get_featured_image() img_field = getattr(featured_image, ENCLOSURE_WIDTH) _, ext = img_field.name.split(".") mime_type = get_mime_type(ext) return mime_type def item_enclosure_length(self, item): featured_image = item.get_featured_image() img_field = getattr(featured_image, ENCLOSURE_WIDTH) return img_field.size def item_pubdate(self, item): return item.created def item_updateddate(self, item): return item.updated Generated feed (with test data) <?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>Pcask.ru: все о компьютерах, гаджетах и программировании.</title> <link>http://localhost:8000</link> <description>Новости, статьи, фотографии, видео о компьютерах и программировании.</description> <atom:link href="http://localhost:8000/rss/" rel="self"></atom:link> <language>ru-RU</language> <copyright>Все права защищены (c) 2020, </copyright> <lastBuildDate>Mon, 13 Jul 2020 00:00:00 +0000</lastBuildDate> <item> <title>6ffd0cc4-c4cb-11ea-b89d-5404a66bf801</title> <link>http://localhost:8000/linux/6ffd0cc4-c4cb-11ea-b89d-5404a66bf801/</link> <description>1</description> <pubDate>Sun, 12 Jul 2020 00:00:00 +0000</pubDate> … -
Cannot access forms in template
I tried to access to the comment form in my templates but it doesn't work. I can do it with the posts but I cannot do it with the comments. I want to access to the form on the bottom of my template. My code is also working but I cannot create the comments via the template. Thank you very much view.py class PostDetail(generic.DetailView): template_name = 'post_detail.html' form=CommentForm model = PostModel fields=['comment'] success_url="/post_detail" def form_valid(self, form): form.instance.author=self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context ['commentmodel_list'] = CommentModel.objects.order_by('-created_on') return context post_detail.html {% extends 'base.html' %} {% block content %} {% load crispy_forms_tags %} <div class="container"> <div class="row"> <div class="col-md-8 mt-3 left mx-auto"> <div class="card mb-4 block"> <div class="card-body"> <h1 class="card-title">{% block title %} {{ postmodel.post }} {% endblock title %}</h1> <p class=" text-muted"><a style="text-decoration:none" href="#">@{{ postmodel.author }} </a>| {{ postmodel.created_on }}</p> <p class="card-text ">{{ object.content | safe }}</p> </div> </div> </div> <div class="col-md-8 mt-3 left mx-auto"> {% for comments in commentmodel_list %} <div class="card mb-4 block"> <a class="overlay" href="{% url 'comment_detail' postmodel.slug comments.pk %}"style="text-decoration:none"> </a> <div class="card-body inner"> <p style="text-align:right;float:right;margin-top:10px;" class="card-text text-muted h6"><a style="text-decoration:none" href="https://google.com">@{{ comments.author }}</a> </p> <h2 class="card-title">{{ comments.comment }}</h2> </div> </div> {% endfor %} </div> </div> … -
Get the the related field of a related field in Django admin
I do have a model with two foreignkeys to get a target_site and a target_page but the problem is I would need to access to the target_pages related to the selected targeted_site only. What would be the best way to do so? class Link(models.Model): source_page = models.CharField(max_length=300) target_site = models.ForeignKey( 'network.Site', on_delete=models.CASCADE, related_name='site') target_page = models.ForeignKey( 'network.Page', on_delete=models.CASCADE, related_name='page') anchor = models.CharField(max_length=300) time_added = models.DateTimeField(null=True, blank=True) def __str__(self): return self.source_page @property def target_path(self): full_path_target = "https://" + \ str(self.target_site) + str(self.target_page) return full_path_target -
Abstract model with relations and inline modeladmin
I have a UserProfile abstract class with common data for Patient and Doctor models. I want to keep the Address model in a separate database, but the Address is also a common data, so I made the UserProfile <--o2o--> Address relationship. Because UserProfile is an abstract class I need to write the relation in that class and not in the Address one. The problem arises when I want to add an inline ModelAdmin to be able to edit the Address from the Patient and Doctor models in the Django admin because there is a conflict in how to get the inline model admin working and the abstract class relation working. In the first one, I need to create the relation in the inline class (Address) and in the other one I need to create the relation in the abstract class (UserProfile). Do you know any workaround or refactor of the database models to be able to do this? I'd appreciate your help. Here is the code: models.py class UserProfile(User): class Meta: abstract = True # Relational user = models.OneToOneField(User, on_delete=models.CASCADE, parent_link=True) # address = models.OneToOneField('Address', on_delete=models.CASCADE, related_name='profile') # Own second_last_name = models.CharField(max_length=50, blank=True) gender = models.CharField(max_length=10, blank=True) class Address(models.Model): """Esquema … -
why cant i use similar reated_name for 2 Foreign key calls?
in my code i used 2 Foreign key import in the same class starter=models.ForeignKey(User,related_name="Topics"); board=models.ForeignKey(board,related_name="Topics"); my question is why cant i use same related_name for 2 different attributes. -
How can I customize views in django?
Hi I am learning django from youtube channel.What are these(? mark),is this queryset or varaible.I am totally confused.From where I can find documentation or online resources about this.Please help me.Sorry for my bad English. [![views.py][1]][1] [1]: https://i.stack.imgur.com/YNNLz.png -
How to resolve this UNIQUE constraint failed: auth_user.username
I need to register a user and use it's email as Username. I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register on the page. I AM NEW TO DJANGO AND PYTHON My Code is forms.py File from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from phonenumber_field.formfields import PhoneNumberField from django.db import transaction from .models import User class UserRegistrationForm(UserCreationForm): name = forms.CharField(max_length=60) # Username = forms.CharField(max_length=15) email = forms.EmailField() class Meta(UserCreationForm.Meta): models = User fields = ['name','email','password1','password2'] views.py file from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from .forms import UserRegistrationForm from django.contrib.auth import get_user_model def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): User = form.save() else: form = UserRegistrationForm() return render(request, 'users/signup.html', {'form': form}) models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import AbstractUser class User(AbstractUser): """docstring for User""" email = models.EmailField(verbose_name='Email Address', unique=True) name = models.CharField(max_length=50) USERNAME_FIELD = 'email' user_permissions = None groups = None REQUIRED_FIELDS = [] def __str__(): return self.name -
QuerySet with GenericRelation return 'NoneType' object has no attribute 'startswith'
I have a model Console. It has a GenericForeignKey: configuration. I have serveral model as: configuration_A configuration_B On each of these models I have: console = GenericRelation( 'device.Console', related_query_name='A', object_id_field='configuration') Obviously with different related_query_name. I want to query my console model and filter it by configuration, here is what I am doing: my_queryset = Console.objects.filter(A__id=random_id) I know for sure that 'random_id' exists. When I want to print the result the query or 'my_queryset.query' I got: 'NoneType' object has no attribute 'startswith' Do you have any idea of how to fix it or even debug it ? Thank you :) -
Dictionary inside array loop
Given a json file with the following data: [ { "activityId": "Task_5.1.1", "activityInstanceId": "Task_5.1.1:8c42f564-cdbe-11ea-8be8-00155d891509", "errorMessage": null, "errorDetails": null, "executionId": "8c42ce53-cdbe-11ea-8be8-00155d891509", "id": "8c431c75-cdbe-11ea-8be8-00155d891509", "lockExpirationTime": null, "processDefinitionId": "Process_5.1.1:1:d1c02af8-cdb8-11ea-8be8-00155d891509", "processDefinitionKey": "Process_5.1.1", "processInstanceId": "8c42802b-cdbe-11ea-8be8-00155d891509", "retries": null, "suspended": false, "workerId": null, "topicName": "AppointIM", "tenantId": null, "priority": 0, "businessKey": "57a4c7e9-fd9f-4d71-a39d-7bd8e112a39a" }, { "activityId": "Task_5.1.1", "activityInstanceId": "Task_5.1.1:fcad6582-cdb8-11ea-8be8-00155d891509", "errorMessage": null, "errorDetails": null, "executionId": "fcad6581-cdb8-11ea-8be8-00155d891509", "id": "fcad6583-cdb8-11ea-8be8-00155d891509", "lockExpirationTime": null, "processDefinitionId": "Process_5.1.1:1:d1c02af8-cdb8-11ea-8be8-00155d891509", "processDefinitionKey": "Process_5.1.1", "processInstanceId": "fcacf049-cdb8-11ea-8be8-00155d891509", "retries": null, "suspended": false, "workerId": null, "topicName": "AppointIM", "tenantId": null, "priority": 0, "businessKey": "f254eb9e-93a5-48e0-8a8e-a95c9fd17ab3" } ] I am trying to only save the dictionaries where businessKey is equal to some value. This will then be display in a template. i can access each item using: items_display = list_task['tasks'][0] but there can sometimes be as many as 1000 sets or as few as 0. I need a method of first searching for all dicts that have the required value: and either discard the remainder or secondly save the found items to a new dict that can be accessed in the template. I have been failing for over 4 hours trying different methods etc: I can get the key : values etc by using the index as above but need a method to iterate through all … -
The dangers of filtering formfield querysets in Django admin
Summary If we filter the queryset for a choice field on a Django admin form, it seems we have to be very careful not to exclude existing values for that field (on the model instance associated with the form). If we do exclude them, the existing values will be considered invalid, which can lead to nasty surprises later on. Is there a generic way to prevent this from happening? More detail can be found below. Background The desire to restrict the available choices for (the representation of) a ForeignKey or ManyToManyField on a Django admin form appears to be fairly common: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey How do I filter ForeignKey choices in a Django ModelForm? filter foreignkey field in django admin Django ModelForm instance with custom queryset for a specific field how to limit the foreignkey dropdown with constraints? Django Limit ManytoMany queryset based on selected FK Judging from the discussions above, there are several different ways to restrict these choices, but most of them boil down to filtering the queryset for a ModelChoiceField (or ModelMultipleChoiceField) on the admin form. General problem Here is what the docs have to say about the ModelChoiceField.queryset: A QuerySet of model objects from which the choices for … -
I am working on a website that requires users to register and login but Having problem in adding an additional field to auth_user using django
I have this form in html of my site <form class="row contact_form" action="." method="post" novalidate="novalidate"> {% csrf_token %} <div class="col-md-12 form-group p_star"> <input type="text" class="form-control" id="firstname" name="first_name" value="" placeholder="First Name" required> </div> <div class="col-md-12 form-group p_star"> <input type="text" class="form-control" id="lastname" name="last_name" value="" placeholder="Last Name" required> </div> <div class="col-md-12 form-group p_star"> <input type="text" class="form-control" id="mobile" name="mobile" value="" placeholder="Mobile Number" required> </div> <div class="col-md-12 form-group p_star"> <input type="text" class="form-control" id="email" name="email" value="" placeholder="Email" required> </div> <div class="col-md-12 form-group p_star"> <input type="password" class="form-control" id="password" name="password" value="" placeholder="Password" required> </div> <div class="col-md-12 form-group p_star"> <input type="password" class="form-control" id="cpassword" name="cpassword" value="" placeholder="Confirm Password" required> </div> <div class="col-md-12 form-group"> <button type="submit" value="submit" class="btn_3"> SignUp </button> </div> </form> Now the problem I am facing is: 1)When I try to post data it shows me an error that username is required which i dont want(create_user() missing 1 required positional argument: 'username'). 2)There is no mobile number section in auth_user which i want. I have tried reading the django docs but couldnt understand(OnetoOne thing and custom usermodel thing I couldnt understand both) Here is my views.py def signup(request): if request.method == "POST": first_name=request.POST['first_name'] last_name=request.POST['last_name'] email=request.POST['email'] mobile=request.POST['mobile'] password=request.POST['password'] cpassword=request.POST['cpassword'] username=request.POST['username'] user=User.objects.create_user(first_name=first_name,last_name=last_name,email=email,password=password,mobile=mobile) user.save(); return redirect('/') else: return render(request,"signup.html") (The indentations are …