Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: PNG not downloading, but opening in browser
I have one API response in which I have one URL, when I am clicking on the URL it is opening in the browser and not getting downloaded. I want to make it downloadable through the backend only. { "count": 1, "next": null, "previous": null, "results": [ { "id": 132, "certificate_url": "https://temp.com/images/export/61ca22ef07dd8b000980b7a9/image-1640637167913.png" } ] } -
django: html form submit without jumping into new page or refreshing/reloading
I am new to django and html. below is my first test web page of a simple online calculator. I found a problem that when clicking the "submit" button, it tends to jump to a new web page or a new web tab. this is not what I want. Once the user input the data and click "submit" button, I want the "result" field on the page directly show the result (i.e. partially update only this field) without refresh/jump to the new page. Also I want the user input data kept in the same page after clicking "submit". I saw there might be several different ways to do this work, iframe/AJAX. Since I am new, what is the really simplest way to achieve this goal? BTW, I dont write javascripts. html: <form method="POST"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="1" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="2" placeholder="Enter value" /> </div> <br /> <div>{{ result }}</div> <button type="submit">Submit</button> </form> view.py def post_list(request): result = 0 if request.method == "POST": num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1) + int(num2) print(request.POST) print(result) context = { 'result': result } return render(request, 'blog/post_list.html', context) -
Django Template :: How to Use POP() in django template
In Below code, am iterating through 2 list. users and roles, where I want to print first element from the roles list for the first element from the user. user = ['abc','cde'] roles = [[1,2,3] , [4,5,6]] for user 'abc' roles should be printed as 1,2,3 only. but am getting all roles for 'abc' user. <table> {% for u in users %} <tr> {% for r in roles.0 %} <th><b>{{ u }}</b></th> <td><b>{{ r }}</b></td> {% endfor %} {{ roles.pop.0 }} </tr> {% endfor %} </table> Can someone help me understanding that why the {{ roles.pop.0 }} is not deleting first element in the roles list? -
How to change the field of username to user_name in to django custom user model?
I have created custom user model. now I want to use user_name as username field instead of username. like shown in below code snippet. class CustomUser(AbstractBaseUser): username_validator = UnicodeUsernameValidator() user_name = models.CharField( _('username'), max_length=100, unique=True, help_text=_('Required. 100 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) USERNAME_FIELD = 'user_name' i'm unable to do that. i'm getting below error: SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.CustomUser'. <class 'accounts.admin.CustomUserAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'CustomUserAdmin', or an attribute or method on 'accounts.CustomUser' the reason of using this, is because all the project's database tables convention is like this. It would be more better if i could define field name is database just as we do for tables in Meta class like below. where i'm calling my customuser model as user model in db. class Meta: db_table = "user" is there anyway to call table field like this way ? class Meta: db_table_user_name = "username" if it possible then we dont need to change … -
How to include Bearer Token in Header using Django Rest Framework?
I'm using rest_framework_simplejwt package for JWT authentication in Django. I created some APIs for login, reg, token_verify, referesh_token and student_data. I restricted to view student details which are fetched from Database. So, user can't see it without authentication. Here is the image for better understanding. As you brothers can see that I pass a Bearer token in postman and then student api work. how i can do this same thing when i have to show the data on frontend? How i'm able to pass bearer token when user is generated the access token by logedin to student route for auth? If I open the link in browser. when i go on student then this happens How I can pass the access_token so i'm authenticated and see the students data? I am trying to this thing for last 10Hours here is the code. View.py ACCESS_TOKEN_GLOBAL=None class Register(APIView): RegisterSerializer_Class=RegisterSerializer def get(self,request): return render(request, 'register.html') def post(self,request,format=None): serializer=self.RegisterSerializer_Class(data=request.data) if serializer.is_valid(): serializer.save() msg={ 'msg':"Registered Successfully" } return render(request, 'login.html',msg) else: return Response({"Message":serializer.errors,"status":status.HTTP_400_BAD_REQUEST}) class Login(APIView): def get(self,request): if 'logged_in' in request.COOKIES and 'Access_Token' in request.COOKIES: context = { 'Access_Token': request.COOKIES['Access_Token'], 'logged_in': request.COOKIES.get('logged_in'), } return render(request, 'abc.html', context) else: return render(request, 'login.html') def post(self,request,format=None): email = … -
Rabbitmq not showing messages in django
I'm reading Django 3 by example book and in Chapter 7 of the book we use rabbitmq,celery and flower. I configed rabbitmq,celery and flower but there is a few problems my task is a email that it sends after a order is created and the task is executed in celery terminal and in flower flower panel but i cant see the email. and in rabbitmq panel the messages are unacked and the other problem is that broker tab in flower is empty and it does'nt show rabbitmq. Here is the screenshots and my code. rabbitmq server is runnig rabbitmq admin panel flower panel celery logs Here is my tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def order_created(order_id): """Task to send an e-mail notification when order is successfully created.""" order = Order.objects.get(id=order_id) subject = f'Order nr. {order.id}' message = f'Dear {order.first_name},\n\n' \ f' You have successfully placed an order.' \ f'Your order ID is {order.id}' mail_sent = send_mail(subject, message, 'admin@onlineshop.com', [order.email]) return mail_sent celery config file, celery.py: import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Onlineshop.settings') broker = "amqp://test:test@localhost:5672/" … -
Django view return data
I have a view that returns an HTML response using render. The data returned is specific to a template. If I want to consume that data on another page, should I write another view with the same logic, or is there a way to pass the data from view 1 to view 2 view return render(request, 'pages/project_details.html', {"project": project, urls path('show_project_details/<project_id>', view=show_project_details, name="show_project_details"), I know that a view is just a function, which takes a request and does something with it, but I don't get how I make a request to a view within a template and consume the response within an existing page. Example here: ## filename: views.py from django.shortcuts import render from .models import Team def index(request): list_teams = Team.objects.filter(team_level__exact="U09") context = {'youngest_teams': list_teams} return render(request, '/best/index.html', context) I want to return the data within this context to home.html and index.html. Hope this makes sense? -
Connecting Django to PostgreSQL database (GeoDjango)
I am having issues connecting to my Postgresql database with my Django website. My database is set up at Port 5434 as there is already an existing database in the default 5432 port. This is the error I am getting Traceback (most recent call last): File "c:\users\anouphong\appdata\local\programs\python\python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\anouphong\appdata\local\programs\python\python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run self.check_migrations() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\core\management\base.py", line 505, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\loader.py", line 223, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 270, in cursor return self._cursor() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 246, in _cursor self.ensure_connection() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 230, in ensure_connection self.connect() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 230, in ensure_connection self.connect() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 211, in connect self.connection … -
Angular.js @angular/core bug
Welcome everyone... how can i fix this im working on it 2 days but nothing change. Can you help me ?See my all codes in app.module.ts That's my nodejs screen import { AngularFireModule} from '@angular/fire/compat'; //it should be '@angular/fire' import { AngularFireDatabaseModule } from '@angular/fire/compat/database'; //it should be '@angular/fire/database' imports: [ AngularFireModule.initializeApp(environment.firebaseConfig), AngularFireDatabaseModule ]; Thank you, -
DRF: validate_empty_values() is called when not empty
I created a subclass of ChoiceField in order to add custom code to supply the default value. At this point, I've copied the validate_empty_values() method over to my new class without modifying it at all - I just want to understand how it works. Here's that method (copied straight from the Field class in /rest_framework/fields.py): def validate_empty_values(self, data): """ Validate empty values, and either: * Raise `ValidationError`, indicating invalid data. * Raise `SkipField`, indicating that the field should be ignored. * Return (True, data), indicating an empty value that should be returned without any further validation being applied. * Return (False, data), indicating a non-empty value, that should have validation applied as normal. """ if self.read_only: return (True, self.get_default()) if data is empty: if getattr(self.root, 'partial', False): raise SkipField() if self.required: self.fail('required') return (True, self.get_default()) if data is None: if not self.allow_null: self.fail('null') # Nullable `source='*'` fields should not be skipped when its named # field is given a null value. This is because `source='*'` means # the field is passed the entire object, which is not null. elif self.source == '*': return (False, None) return (True, None) return (False, data) I have done a PATCH (we use PATCH for … -
Django lists of objects in a template max out
Not an expert on django and I have a problem that I have tried to find documentation about. Hopefully someone can help me out. Sometimes my templates do not return the intended page html, but instead returns a text based html list of the objects .I suspect this is related to number of rows in the queryset. Where can I find the documentation about this? Is it a django setting or the CSS class for the list that determines this? -
How to set on delete and on update cascade in django?
Look at these modules: class Customer2(models.Model): Customer_Name=models.CharField(max_length=30) Customer_Address=models.CharField(max_length=100) Customer_Phone=models.IntegerField() Customer_Email=models.EmailField(max_length=50) class Meta: db_table="Customer_Table" class Product(models.Model): Product_Name=models.CharField(max_length=100) Quantity=models.FloatField(max_length=100) Comming_Date=models.DateField(max_length=15) Expire_Date=models.DateField(max_length=15) Comming_Price=models.FloatField(max_length=50) Picture=models.ImageField(upload_to='Images',blank=True, null=True) class Sale(models.Model): Customer=models.ForeignKey(Customer2, default=1, on_delete=models.CASCADE) Product=models.ForeignKey(Product, default=1, on_delete=models.CASCADE) Quantity=models.FloatField() Price=models.FloatField() Date=models.DateTimeField() Customer_Name1=models.CharField(max_length=20,default=0) Product_Name1=models.CharField(max_length=20,default=0) class Meta: db_table="Sale_Table" In the above modules,when I am trying to to delete (customer) from customer it gives me(Do you really want to execute "DELETE FROM customer_table WHERE customer_table.id = 2"?)message, while I already used on delete cascade in customer table,What should I do? I want to set on update and on delete cascade in customer table. -
unable to send post request using HTMX + Django
I'm trying to create a CRUD page using django + HTMX and unable to send POST request. hx-post sends a GET request instead of POST request. my Role Models is as follows: class Role(models.Model): name = models.CharField(max_length=200) I'm creating the form using Cripsy Forms as follows class RoleForm(forms.ModelForm): class Meta: model = Role fields = ('name', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['name'].label = "Role" self.helper.add_input(Submit('add_new_Role', 'Add', css_class='role_button')) self.helper.layout = Layout( Row( Column('name'), ) ) I'm using the form in my template like this : {% extends 'main.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="card col-md-6 ml-auto mr-auto"> <div class="card-body"> {% crispy role_form %} </div> </div> </div> <div id="role_list"> {% include 'role_list.html' %} </div> {% endblock %} {% block javascript %} <script type="text/javascript"> $(document).ready(function(){ $("form").removeAttr("method"); $('.role_button').attr("hx-post", '{% url "role_add" %}'); $('.role_button').attr('hx-target', '#role_list'); }); </script> {% endblock %} The CDN link is added in the main.html file. My understanding is that clicking the ADD button should trigger a POST request. However GET request is initiated, which makes me feel like the HTMX part did not work at all -
Get object URL from boto3, AWS S3, Django
I have a view in Django like this : f=request.FILES['image'] filename=str(f).split('.')[0] cloudFilename = 'blog/' + filename s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY) bucket = s3.Bucket('django-pnp-talk') bucket.put_object(Key=cloudFilename, Body=f) how can I get the URL from the recently object that I put into the bucket? -
Even though its a class why is AttributeError: 'function' object has no attribute 'as_view'
even though its a calss based func why is this attribute error popping up when i use login_required error Message path('active/<int:pk>', UpdateActiveStatus.as_view(), name="activeStatus"), AttributeError: 'function' object has no attribute 'as_view' views.py @login_required(login_url='/admin/') class UpdateActiveStatus(UpdateView): model = FutsalTimeline form_class = UpdateActiveStatus template_name = 'timeline.html' success_url = reverse_lazy('timeline') -
Django, How to filter context output from HTML template?
I have a ListView that sends context as news in the HTML template. The below code is supposed to slice the context array from the 4th element to until its end {% for post in news[4:0] %} ............ {% endfor %} But following error occurs Could not parse the remainder: '[4:]' from 'news[4:]' -
Annotation of Similar Article Tags In Django Admin
I want to display similar tags count in the Django admin Tag section like this: name | posts ------------------------------- business | 3 Currently in my Tag table I have something this. This different posts that have similar tags to them. name | post_id ------------------------------- business | 1 business | 2 business | 3 My models class Posts(models.Model): title = models.CharField(max_length=500, verbose_name='Post Title') class Tags(models.Model): name = models.CharField(max_length=500) date_created = models.DateField(auto_now_add=True, verbose_name='Date Created') last_modified = models.DateField(auto_now=True, verbose_name='Last Modified') post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts') I have this in the admin.py class TagAdmin(admin.ModelAdmin): list_display = ('name', 'post_count', 'date_created', 'last_modified') search_fields = ['name'] ordering = ['id'] readonly_fields=('date_created', 'last_modified') def post_count(self, obj): return obj.post_count def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(post_count=Sum("post")) return queryset admin.site.register(Tags, TagAdmin) This is how it looks in the admin panel name | post_count ------------------------------- business | 3 business | 3 business | 3 How do I achieve only displaying one instance of a tag name with all the posts that have that tag instead of the repetition above and instead the desired outcome below? name | posts ------------------------------- business | 3 -
Drf: authenticating without the USERNAME_FIELD
` extended from: Drf how to: simple-jwt authenticating without the USERNAME_FIELD I was tryna figure out how to authenticate a user with a field that is not set as the USERNAME_FIELD and faced some issues, it lets me input in the correct data fields, but it never authenticates I'm using this snippet from the previous questions answer: class MyTokenStudentSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['student_id'] = serializers.CharField(required=False) # self.fields['password'] = serializers.CharField(write_only=True, required=True) self.fields['password'] = PasswordField(trim_whitespace=False) username_field = 'student_id' auth_fields = ['student_id'] produces { "detail": "No active account found with the given credentials" } any modifications would be greatly appreciated. -
Annotate on Generic Relation
apologies, I'm fairly sure there's a way to do this with Q filters/F expressions but I can't quite get it right. I have a Generic Versioning Model, and several versionable models: class Version(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to=VERSIONED_OBJECTS_LIMIT ) object_id = models.PositiveIntegerField() source = GenericForeignKey("content_type", "object_id") object_uri = models.TextField(max_length=1024, null=True) version_number = models.IntegerField(default=1) is_latest = models.BooleanField(default=1) class Dataset(models.Model): versions = GenericRelation(Version) class DataModel(models.Model): versions = GenericRelation(version) I figured this approach would be wise as we version quite a few models. However, I'm struggling to create the annotation/query that would retrieve for me all model instances annotated by the latest version. For a given instance it is of course trivial, but I can't figure it out for the model writ large. latest_datasets = Dataset.objects.annotate(uri = version.uri).filter(versions__islatest=True) Obviously returns all datasets, since by design each dataset has at least one "is_latest" Version. Apologies -- maybe this is just bad db design, but I do think making "Version" a Generic abstraction made sense for our use case. So, if theres a way to get all instances of Model_x with the appended uri WHERE version.is_latest = True, I would love to know how. Thanks in advance, sorry for my ignorance. -
How to get user with POST Ajax call in django?
I'm trying to realize comments for products on site with AJAX, but faced the problem that I can not receive an author of comment in this case of code: new_comment.author = request.user I got this error in this case: "Exception Value: Object of type User is not JSON serializable" But without user I got parameters from back-end and have result 200, like this author "" content "dasda" created_at "2021-12-31T07:34:12.766Z" product 4 So the question how to be "author = request.user" can be serialized? Or it is can be realised only with Django Rest Framework? (I don't have experience in DRF, but know some things in theory) Can somebody advice please? def ajax_receiver(request): product = Product.objects.get(id=4) is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if request.method == 'POST' and is_ajax and request.user.is_authenticated: form = UserCommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) #new_comment.author = request.user new_comment.product = product new_comment.save() comment_info = { "author": new_comment.author, "content": new_comment.content, "created_at": new_comment.created_at, "product": product.id, } return JsonResponse({"comment_info": comment_info}, status=200) else: return JsonResponse({"success": False}, status=400) -
Django Python - .get function returns DoesNotExist matching query does not exist
I've been really stumped on the following issue.. I am trying to retrieve an order number after taking a stripe payment. Stripe returns a payment is completed and everything is working, on the success page I call the function below to retrieve the order number from the session table. The wierd thing is, even though it gives me a DoesNotExist error, it does find the right order number and returns the order number and all data is actually served. Function def get_order_number(session_id): order = session_order_table.objects.get(session_id=session_id) order_number = order.order_number return order_number success page function def success_page(request): summary_orders = None session_id = request.session["USER_SESSION_ID"] order_number = get_order_number(session_id) print('###############SESSION_ID######################') print(session_id) print(order_number) online_order = My_Cart_History_Model.objects.filter(order_number=order_number) .... error 1820bd97c5"\n },\n "type": "payment_intent.succeeded"\n}' 1x 777 test (Quality:VVS, Size: L, Color: yellow-gold) C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py:1416: RuntimeWarning: DateTimeField My_Cart_History_Model.transaction_date received a naive datetime (2021-12-31 07:21:41) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" Internal Server Error: /cart/my_webhook_view/ Traceback (most recent call last): File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\pwl-server\django\t7\cart\views.py", line 533, in my_webhook_view fulfil_order(request=request ,payload=payload,session=session) File "D:\pwl-server\django\t7\cart\views.py", line 594, in fulfil_order return … -
changing primary key from username to uuid on POSTGREQL gives: django.db.utils.ProgrammingError: column "username" is in a primary key
I have a postgresql database and I am making a migration to switch my pk from username to uuid. I already made a data migration file where I add a uuid to every row in my model it worked fine on sqlite but when I was testing it on postgresql I got an error. The error was "django.db.utils.ProgrammingError: column "username" is in a primary key" I am not sure where to begin to debug this thing. Here is the model, data migration, migration, and stack trace of the error: # models.py class UserInformation(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) username = models.CharField(max_length=100, unique=True, blank=True, null=True) # data migration 42 import uuid from django.db import migrations def set_uuid_for_all_user_information(apps, schema_editor): UserInformation = apps.get_model('accounts', 'UserInformation') for userInformation_user in UserInformation.objects.all(): userInformation_user.uuid = uuid.uuid4().hex userInformation_user.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0041_auto_20211227_2113'), ] operations = [ migrations.RunPython(set_uuid_for_all_user_information), ] # migration 43 (this is where the postgresqsl error occurs) trying to change pk from username to uuid from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('accounts', '0042_auto_20211229_2319'), ] operations = [ migrations.AlterField( model_name='userinformation', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='auth.user'), ), migrations.AlterField( model_name='userinformation', name='username', field=models.CharField(blank=True, … -
How to apply multiple field options to one field in Django
I'm using Django, is there a way to apply foreign key and ChartField to one field at the same time? Sometimes I want to allow the user to enter a value that is not in the foreign key. I've googled for a long time and found various ways, but I can't find a solution. Please help. [models.py] class Supporting(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=False, null=True) -
How to insert field in table from database using python script and print it in html page or print python result in html directly using pycharm django
so i'm new to django and python, i'm having a mini project to make a decision support system. so i already build a website, already connect it to the database and have the python code, now i'm having difficulties to push the result/target in python to existing field in table dataresponden from database and print it to html. the flow is like this: an user input a data (nama, umur, gejala, komorbid) and stored it in table dataresponden(nama, umur, gejala, komorbid, hasil_rekomendasi) in database. user didn't input hasil_rekomendasi because hasil_rekomendasi is the result from the decision support system. in python, i read query dataresponden as dataset, i set hasil_rekomendasi as a target and calculate the remaining column. so i get the result i want named hasil_prediksi, now the problem is i want to push hasil_prediksi to column hasil_rekomendasi in table dataresponden because when user input the data they don't input hasil_rekomendasi. after that i want print it in my html page. i tried this Execute a python script on button click but didn't work, i tried to use update table but it didn't work too, this is the code in hasil.html : <div class="modal-body text-center pb-5" id="hasilrekomendasi"> <div class="container"> <div … -
Github actions deploy django application to elastic beanstalk
I'm simply trying to deploy my django application to elastic beanstalk using github actions but keep getting these error: Warning: Environment update finished, but health is Red and health status is Degraded. Giving it 30 seconds to recover... Warning: Environment still has health: Red and health status Degraded. Waiting 19 more seconds before failing... Warning: Environment still has health: Red and health status Degraded. Waiting 8 more seconds before failing... Error: Deployment failed: Error: Environment still has health Red 30 seconds after update finished! This it the code I'm using below: name: AWS Deploy on: push: branches: - test-main-branch jobs: build: runs-on: ubuntu-latest steps: - name: Checkout source code uses: actions/checkout@v2 - name: Generate deployment package run: zip -r deploy.zip . -x '*.git*' - name: Get timestamp uses: gerred/actions/current-time@master id: current-time - name: Run string replace uses: frabert/replace-string-action@master id: format-time with: pattern: '[:\.]+' string: "${{ steps.current-time.outputs.time }}" replace-with: "-" flags: "g" - name: Deploy to EB uses: einaregilsson/beanstalk-deploy@v20 with: aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }} aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} application_name: project-pit environment_name: project-pit-cloud version_label: 12345 region: ap-southeast-2 deployment_package: deploy.zip - name: Deployed! run: echo App deployed The application is showing up in my s3 bucket but I still get a Degraded health …