Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I use foreign key to import users login from google by Django-allauth
I am using 2 login methods, one is Django inbuilt authentication and another by using "allauth" of google. I want to make a separate model with only the entries from google logged-in people by using a "foreign key" and few more attributes. In Django admin page there is a table "Social accounts", which has only google logged in users, so how can I include that model? -
I am unable to create a new custom user in Django
I tried creating a new user but it didn't work, I have tried debugging it but don't get a way about this, kingly help. I have a User Model but want to try and create different user types like students, teachers something like that which would all be in the user user model as well as their various user models. View.py def AddCustomerManager(request): if request.method == "POST": email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.create_user(email=email, username=username, password=password, user_type=2) user.save() messages.success(request, "Customer Manager Added Successfully") except: messages.error(request, "Failed to Add Customer Manager") return render(request, "pusheat_admin/addcm.html") models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) user_type_choice = ((1, "SuperUser"), (2, "CustomerManager")) user_type = models.CharField(default=1, choices=user_type_choice, max_length=10) objects = UserManager() class CustomerManager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=50, blank=False) email = models.EmailField() password = models.CharField(max_length=32) addcm.html <form role="form" method="POST"> {% csrf_token %} <div class="card-header"><h4>Add Customer Manager</h4></div> <div class="card-body"> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label>Username</label> <input type="text" class="form-control" name="username" placeholder="Username"> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" name="password" placeholder="Password"> </div> </div> <div class="card-footer"> <button type="submit" class="btn btn-primary">Add Customer Manager</button> </div> </form> -
Django button not toggling
I have a button on a page that I want to toggle back and forth between "Follow (+)" and "Following". For some reason it is not toggling at all and I'm really struggling to understand why. The button is doing what I want it to do in terms of adding/removing the user to/from the profile followers so I know the button is working but the text of the button is not changing. views.py def profile_page(request, user_username): currentUser = request.user profile = get_object_or_404(User, username=user_username) if profile.followers.filter(user=currentUser).exists() == True: a_follower = True else: a_follower = False return render(request, "network/profilePage.html", { "profile": profile, "currentUser": currentUser, "a_follower": a_follower }) profilePage.html {% if currentUser != profile %} <form action="{% url 'follow' profile.username %}" method="POST"> {% csrf_token %} <input type='hidden' name='profile_id' value="{{ profile.id }}"> {% if currentUser is a_follower %} <input type="submit" value="Following"> {% else %} <input type="submit" value="Follow (+)"> {% endif %} </form> {% endif %} Can anyone see what the problem is? Please let me know if I need to include more details. -
How can i create stream follow date in logger Django?
Currently, i'm using watchtower and boto3 to create and handle logs from Django to Cloudwatch AWS, but i want to auto create stream_name follow date, how can i do it? This is my code: def check_log(request): logger_boto3_session = boto3.Session( aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'], region_name=AWS_DEFAULT_REGION) logging.basicConfig(level=logging.DEBUG) cw_handler = watchtower.CloudWatchLogHandler(log_group="log-app-atbb", stream_name=datetime.now().strftime('%Y-%m-%d'), boto3_session=logger_boto3_session) logger = logging.getLogger('watchtower') logger.info("Hello World") In my code, it only create one time is current date, tomorrow, it can't create new log stream with tomorrow date on Cloudwatch Expect: Today: 11/03/2020 -> create log stream is 2020-11-03 Tomorrow: 12/03/2020 -> will auto create log stream is 2020-12-03 -
File Upload Only Works Sometimes in Django
I am trying to upload text files which get converted into csvs and then into my database. However, the file upload only works when I have created the text file in my project directory. For example, when I have a text file that I create here it works - I can drag this file into my template with the upload files button and it makes the rows in the database. When I create the test.txt file on my desktop and try to import the file in my template, nothing happens and it returns an empty csv file. Views.py @login_required(login_url='login') def upload(request, *args, **kwargs): if request.method == "GET": return render(request, 'users/upload.html') if request.method == "POST": # Create subject object in database cram_set = CramSet.objects.create( subject='Other', name='', ) raw_file = request.FILES['file'] contents = raw_file.read().decode('UTF-8') question_pattern = re.findall( r'^\d+\)\s*((?:(?:(?!^\d+\))[\s\S])*?\n(([A-Z])\)(?:(?!^\d+\))[\s\S])*?)$)?(?:(?!^\d+\))[\s\S])*?)\nAnswer:\s*(\3|FALSE|TRUE)\nExplanation:\s*(.*)', contents, re.M) df = pd.DataFrame(question_pattern, columns=["Question", "Answer", "1","2","Explanation"]) clean_df = df.drop(columns=["1", "2"]) data_set = clean_df.to_csv(index=False) io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar='"',quoting=csv.QUOTE_MINIMAL): _, created = Question.objects.update_or_create( question=column[0], answer=column[1], explanation=column[2], cram_set_id=cram_set.pk, ) return redirect('/users/' + request.user.username + '/') return render(request, 'users/upload.html') Do I need to save these files in a Media file in my project so that I can work with them … -
Converting from Raw Sql to Django Queryset API
I am currently doing a sample profile information with total counts of friends. It is actually working fine with raw sql, and I read a lot that it is highly recommended to use Django ORM than using raw sql. I tried several ways such as implementing with aggregate() or annotate() but none of those ways seem to work base on my expected result. Any help would mean very much to me. Thanks in advance! Here are my models: Profile class Profile(models.Model): user = models.ForeignKey(User, related_name="profile", on_delete=models.CASCADE, null=False) mobile_no = models.CharField(max_length=20, null=False, unique=True) first_name = models.CharField(max_length=30, null=False) last_name = models.CharField(max_length=30, null=False) gender = models.CharField(max_length=20, null=False) objects = ProfileManager() class Meta: db_table = 'profile' Friends class Friend(models.Model): to_user = models.ForeignKey(AUTH_USER_MODEL, models.CASCADE, related_name="friends") from_user = models.ForeignKey( AUTH_USER_MODEL, models.CASCADE, related_name="_unused_friend_relation" ) created = models.DateTimeField(default=timezone.now) objects = FriendshipManager() class Meta: db_table = 'friends' Here is my raw query written in ProfileManager() and ProfileQuerySet() class ProfileQuerySet(models.QuerySet): def get_complete_user_profile(self, user_id): user_profile_query = self.raw("""select profile.*, (select count(*) from friend where friend.from_user_id = profile.user_id) as friends from profile where user_id = %(id)s""", params={'id': user_id}) return user_profile_query class ProfileManager(models.Manager): def get_queryset(self): return ProfileQuerySet(self.model, using=self._db) def user_profile(self, user_id): return self.get_queryset().get_complete_user_profile(user_id=user_id) -
Django Permission classe gets called twice
i'm facing an odd problem in my project. I have created a simple custom permission class to understand how the system works. class CustomPermission(permissions.BasePermission): def has_permission(self, request, view): print("something") return True When I try add this permission to an APIVIew in the terminal "something" prints twice. Is it normal for a view to check permission two times for the same request? -
Django annotate sort by
i need your help. i have two models candidate/models.py class Candidate(models.Model): skill = models.TextField(blank=True) and employer/models.py class Job(models.Model): skill = models.TextField(blank=True) and i need to sort based on this two, in another views interview/views so i need a query set to sort this. Interview models have a job and candidate as their foreign key class Application(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE) can anyone help me out? i've been stuck with this for days. Application.objects.annotate(percentage=(Count('candidate__skill', filter=Q(candidate__skill__in=job__skill)) / Count('job__skill') * 100 )).order_by() this code above, have an error in candidate__skill__in=job__skill Thank you! -
get_absolute reverse URL multi Slug Many To Many Field Django Model
I use Slugs to address the URL. It all works but when I want to show product details. I don't know how can I get two slugs from another model and put it beside the details slug. (the category is in the main URL) (show me all products Samsung mobile) Works: site.com/category/mobile/samsung/ (I want when I want to click one of them, show me the details, but it doesn't work) Doesn't Work: site.com/category/mobile/samsung/s10 Model: from Django.db import models from Django.shortcuts import reverse class Category(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) child_category = models.ForeignKey('self', max_length=150, null=True, blank=True, on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def get_absolute_url(self): return reverse('shop:brands', args=[self.slug]) def get_absolute_url_product(self): return reverse('shop:products', args=[self.child_category.slug, self.slug]) class Product(models.Model): category = models.ManyToManyField(to=Category, related_name='products') name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) description = models.TextField() # Here I did what I knew, but It didn't work. =============================================== def get_absolute_url_details(self): return reverse('shop:product_details', self.category.model.slug, self.category.model.child_category.slug, self.slug) When I use this reverse way, it gives me this Error: 'ForwardManyToOneDescriptor' object has no attribute 'slug' URL: from Django.urls import path from Shop import views app_name = 'shop' urlpatterns = [ path('<slug:brands_slug>/', views.brands, name='brands'), path('<slug:brands_slug>/<slug:product_slug>/', views.products, name='products'), path('<slug:brands_slug>/<slug:product_slug>/<slug:product_details>/', views.details_products, name='product_details'), ] View: def products(request, brands_slug, product_slug): product = Product.objects.filter(category__slug=product_slug, category__child_category__slug=brands_slug) context = … -
How to filter a serializer manytomany field in djangorestframework
I want to filter the manytomany field based on the current instance selected field['customer']. I want the cart_items manytomany field to only contain the cart_items of the selected customer in cart API. models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_id = ShortUUIDField(unique=True, editable=False) name = models.CharField(max_length=100) # price = MoneyField(max_digits=14, decimal_places=2) price = models.DecimalField(max_digits=14, decimal_places=2) class Customer(models.Model): customer_id = ShortUUIDField() user = models.ForeignKey(User, on_delete=models.DO_NOTHING) name = models.CharField(max_length=255, blank=False) email = models.EmailField(unique=True) class CartItems(models.Model): cart_items_id = ShortUUIDField() user = models.ForeignKey(User, on_delete=models.DO_NOTHING) customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) products = models.ForeignKey(Product, on_delete=models.DO_NOTHING) quantity = models.IntegerField(default=1) class Meta: unique_together = ( ("customer", "user", "products"), ) class Cart(models.Model): cart_id = ShortUUIDField() user = models.ForeignKey(User, on_delete=models.DO_NOTHING) customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) cart_items = models.ManyToManyField(CartItems) serializers.py class CartSerializer(serializers.ModelSerializer): class Meta: model = models.Cart fields = '__all__' read_only_fields = ['user'] I have tried to use all of the things below. Any help would be appreciated. Requirement: The cart_items must contain items of the selected customer only. class CartSerializer(serializers.ModelSerializer): """serializer for Product objects.""" # authors = serializers.PrimaryKeyRelatedField(queryset=Author.objects.all(), many=True) # cart_items = serializers.PrimaryKeyRelatedField(queryset=models.CartItems.objects.filter(customer=self.context['request'].user), many=True) # cart_items = serializers.PrimaryKeyRelatedField(queryset=models.CartItems.objects.filter(user=2), many=True) # cart_items = CustomerFilteredPrimaryKeyRelatedField(many=True, source='user.Customer') # cart_items = serializers.PrimaryKeyRelatedField('get_cart') # # def get_cart(self, product): # qs = models.CartItems.objects.filter(user=2) # serializer = CartItemSerializer(instance=qs, many=True) … -
django console.log in script tag not working
Only a script a tag in html, not log in console index.html <script> console.log(123) </script> urls.py path('', TemplateView.as_view(template_name='index.html')) -
How do I run my django server from pycharm?
im wondering how I run django server from pycharm? I dont know where I should run it. Does someone know? Beginning programmer -
Python join not giving back comma separated string [duplicate]
I have a Django query that returns me an array of strings. I am trying to convert them into a comma separated string. array_string = "['xyz2005.test.com', 'xyz2006.test.com']" (Pdb) joined_string = ",".join(array_string) (Pdb) joined_string "[,',x,y,z,2,0,0,5,.,t,e,s,t,.,c,o,m,',,, ,',x,y,z,2,0,0,6,.,t,e,s,t,.,c,o,m,',]" I was expecting: xyz2005.test.com, xyz2006.test.com What am I doing wrong? -
How do I add a context in django class based view
I want to add context to a class based view in django. How do I do that? from django.views.generic import ListView from .models import Post class PostDetails(ListView): model = Post context_object_name = "post" # How do I add another context? -
Django collectstatic command fails in AWS Elastic Beanstalk Amazon Linux 2 Python 3 platform
I've been struggling for several days now to deploy my Django application to Elastic Beanstalk using the Amazon Linux 2 Python 3.7 platform. After managing to deploy the app I can't run the command python3 manage.py collectstatic --noinput in order for nginx to be able to serve the static files and thus have all the necessary CSS styles for the Django Admin page. Right now I have a file named "static.config" in the .ebextensions directory that has the following YAML code: container_commands: collectstatic: command: | source $PYTHONPATH/activate python3 manage.py collectstatic --noinput I added the line source $PYTHONPATH/activate after the first failed attempt following this answer. I also have a file named "01_python.config" with the following code: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "backend_project.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: backend_project.wsgi:application NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:proxy:staticfiles": "/static/": "static/" This is the stacktrace I'm seeing in the cfn-init.log: 2020-11-04 14:06:29,217 [ERROR] Command collectstatic (source $PYTHONPATH/activate python3 manage.py collectstatic --noinput ) failed 2020-11-04 14:06:29,218 [ERROR] Error encountered during build of postbuild_1_eduvaluer_api: Command collectstatic failed Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 542, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 260, in build changes['commands'] = CommandTool().apply(self._config.commands) File "/usr/lib/python2.7/site-packages/cfnbootstrap/command_tool.py", line 117, in apply raise ToolError(u"Command %s failed" % name) … -
UnicodeDecodeError when using django serializers
I have a custom django user model and a "Photo" model with Foreign Key as "CustomUser" model: class CustomUser(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' objects = CustomUserManager() email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=10) bio = models.CharField(max_length=240, blank=True) city = models.CharField(max_length=30, blank=True) profile_pic = models.ImageField(null=True, blank=True) date_of_birth = models.DateField(blank=True, null=True) def __str__(self): return self.email and class Photo(models.Model): image = models.ImageField(blank=False, null=False, upload_to="images") author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) title = models.CharField(max_length=200) def __str__(self): return self.title I am trying to get the 'profile_pic' field (defined in CustomUser) from Photo Serializer but i get an utf-8 error. error image Photo Serializer: class PhotoSerializer(ModelSerializer): email = serializers.SerializerMethodField('get_user_email') username = serializers.SerializerMethodField('get_username') profile_pic = serializers.SerializerMethodField('get_profile_pic') class Meta: model = Photo fields = ['id', 'author','image', 'title','email', 'username', 'profile_pic'] def get_user_email(self, photo): email = photo.author.email return email def get_username(self, photo): username = photo.author.username return username def get_profile_pic(self, photo): photo_url = photo.author.profile_pic return photo_url If I replace get_profile_pic with the following code below, it gives the correct image url. But is there any other way to do it? Also I would like to know the reason for the error. def get_profile_pic(self, photo): request = self.context.get('request') photo_url = photo.author.profile_pic photo_url = 'media/' + str(photo_url) return request.build_absolute_uri(photo_url) -
Broadcasting with self.channelr_layer.group_send does not send to all users
I am trying to make a chat application between two users using a WebsocketConsumer. When connecting, both users pass on the same "room_name". Everything is working except broadcasting a new message to all channel_layers in the group. When I try to broadcast the new message to all users in the group, only the last connected user gets the broadcast, but twice. The connect method in consumer.py def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print(self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() Broadcasting method in consumer.py def send_chat_message(self, message): print("This should broadcast to everyone connected.", message) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) Method to pass message to websocket def chat_message(self, event): message = event['message'] self.send(text_data=json.dumps({ 'message': message })) -
Nginx Reverse Proxy with Gunicorn Treats Site Names Differently
We have a Django project that is served in production using Nginx and Gunicorn reverse-proxy setup. Everything seems to work except for one small detail. Somehow, the browser "sees" the following addresses as different sessions. Suppose I log into the site using the example.com address. Then, if I visit www.example.com, the browser does not see that the user has logged in. My suspicion is that this has something to do with the way Nginx or Gunicorn are setup. Any help on how to resolve this discrepancy is appreciated. Nginx config: server { root /home/example/mysite; # Add index.php to the list if you are using PHP index index.html index.htm; server_name example.com www.example.come; client_max_body_size 512M; location /static/ { alias /home/example/mysite/static/; expires 30d; add_header Vary Accept-Encoding; access_log off; } location /media { alias /home/example/mysite/media/; expires 30d; add_header Vary Accept-Encoding; access_log off; } location / { # try_files $uri $uri/ =404;# proxy_pass http://127.0.0.1:8080; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol $scheme; proxy_connect_timeout 6000; proxy_send_timeout 6000; proxy_read_timeout 6000; send_timeout 6000; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /home/ubuntu/ssl/example_com_chain.crt; ssl_certificate_key /home/ubuntu/ssl/server.key; #include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot #ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by … -
Unknown format code 'g' for object of type 'str'
I am trying to implement a simple function of float numbers and I got this error: Unknown format code 'g' for object of type 'str. What is the cause of this and how do I resolve this. from django import template register = template.Library() @register.filter def human_format(num): num = float('{:.3g}'.format(num)) magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude]) -
How do you join multiple model on a foreign key field using django ORM?
Want to join three tables and get data. Where model_c and model_b have a foreign key to model_a. But all model does not have a foreign key class Model_A(models.Model): name = models.CharField() class Model_B(models.Model): model_a = models.ForeignKey(Model_A) name = models.CharField() class Model_C(models.Model): model_a = models.ForeignKey(Model_A) name = models.CharField() Want query as below. SELECT * FROM model_c JOIN model_a ON model_a.id = model_c.model_a JOIN model_b ON model_a ON model_a.id = model_b.model_a; -
Saving records in related models using Django views and Ajax
I have been trying to update related model objects in Django app using Ajax. In order to update a model I have used the following view and the records save without problem. However, on similar lines, if I try to save data in related models (i.e. to save Django inline formset data) nothing seems to be working (unable to find solution to my predicament on the web including SO). The following is the set up for saving records in one model: My views.py class CreateViewFactorA(CreateView): template_name = ... model = ModelFactorA form_class = FormCreateFactorA # AJAX FUNCTION ******************* def postFactorA(self, *args, **kwargs): if self.request.is_ajax and self.request.method == "POST": form = self.form_class(self.request.POST) if form.is_valid(): instance = form.save() ser_instance = serializers.serialize('json', [ instance, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": ""}, status=400) My template $('#PostFactorA').submit(function(e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ url: "{% url 'factora_create' %}", type: 'POST', dataType: 'json', data: serializedData, success: function(response) { console.log('Data Saved'); }, error: function (response) { alert(response.responseText); } }); }); I am trying to use the Ajax post in order to avoid page reload. What changes are needed in the view (as above) so that the formset data may be … -
Make message disappear after several seconds
I'm displaying error messages on the screen and i want these messages to disappear after X seconds. I'm using a simple script that works if one message is displayed on the screen. If two messages are displayed, see example below, only the first message is disappeared, the second one remains on the screen. How can i remove both messages? I'm using this script: setTimeout(function() { $('#message').fadeOut('slow'); }, 15000); Script that produces the messages. {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div id="message"> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button> {{ error|escape }} </div> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button> {{ error|escape }} </div> {% endfor %} {% endif %} Thank you for help. -
Why django-admin is throwing error in cmd?
I am trying to install django in my newly installed windows 10. When i run pip install django it says requirements already satisfied, but when i run django-admin then it throws some error in comand prompt. Here is the message i'm getting when i run django-admin django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException here is the screenshot of what i'm talking about -
Broadcast a message to everyone periodically using Django channels
I'm new to Django channels. I created a WebSocket and I want to send some info to every user periodically. Each user connects to my WebSocket when goes to my website and see the info on top of each page. I have no idea whether it is necessary to create a group or not. But how can I send info to every visitor periodically? May be something like this: class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) await self.channel_layer.group_send( { "text": 'Hello user!' } ) # OR await self.send({ "type": "websocket.send", "text": 'Hello user!' }) Thanks in advance... -
Passing variables to a container on startup
I want to setup my Django app in kubernetes environment in such a way that while creating the app container, environment variables are passed such that those environment variables are used to initiate the containers. For example on starting the app container I want to issue management commands such as python manage.py createuser --lastname lname --firstname --fname --number --num " and so on. How to pass these variable values such as lname and fname above inside the container in a generic way such that every time new values can be passed depending on the user credentials and they do not need to be hard coded everytime?