Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django restframework serializer with joining tables
I'm creating a django API for a discord bot for sounds recorded management. Here are my models (simplified) : class Member(models.Model): name = models.CharField("Discord Name", max_length=100, unique=True) discord_id = models.BigIntegerField("Discord ID", unique=True, blank=True, null=True) class Sound(models.Model): id = models.AutoField("Sound ID", primary_key=True) file = models.FileField("Sound", upload_to='sounds/') added_by = models.ForeignKey(Member, verbose_name="Author", on_delete=models.SET_NULL, blank=True, null=True) tags = TaggableManager("Tags", blank=True) class MemberinSound(models.Model): sound = models.ForeignKey(Sound, on_delete=models.CASCADE, related_name="membersinsound") personality = models.ForeignKey(Member, related_name='membersinsound', on_delete=models.CASCADE) Explanations : a sound is uploaded by any member (added_by), with multiples optional tags, and personality that appears in this sound (MemberinSound). You can imagine this 3 tables like (player, match, and playersinmatch). My view to get a specific sound is : class SpecificSound(APIView): def get(self, request, id: int, formate=None, **kwargs): sound = Sound.objects.select_related().get(id=id) membersinsound = sound.membersinsound.all() serializer = SoundSerializer(sound, many=False) return Response(serializer.data) And serializers.py : class MemberInSoundSerializer(serializers.ModelSerializer): class Meta: model = MemberinSound fields = [ 'personality' ] class SoundSerializer(serializers.ModelSerializer): personality = MemberInSoundSerializer(many=True, read_only=True) class Meta: model = Sound fields = [ 'id', 'title', 'volume', 'file', 'stream_friendly', 'is_active', 'personality', ] def to_representation(self, instance): representation = super().to_representation(instance) representation['path'] = instance.file.path return representation First problem I got is in my view where I send to my serializer only Sound model (without MemberinSound), I don't … -
Djnago Form getting Error while edit record
I am getting Issue while edit a record based on CHatquestion ID, if option is null then i need to add a record based on same chatquestion id, if chatqustion id exist in option it will work, i am trying to multiple way to solve this issue but still can't find solution. Models.py # thease are all 3 models class Problem(models.Model): Language = models.IntegerField(choices=Language_CHOICE, default=1) type = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.type class ChatQuestion(models.Model): # Eding record based on chatquestion id question = RichTextField(null=True, blank=True) problem_id = models.ForeignKey( Problem, models.CASCADE, verbose_name='Problem', ) sub_problem_id = models.ForeignKey( SubProblem, models.CASCADE, verbose_name='Sub Problem', null=True, blank=True ) def __str__(self): return self.question is_first_question = models.BooleanField(default=False) class Option(models.Model): option_type = models.CharField(max_length=250, null=True, blank=True) question_id = models.ForeignKey( ChatQuestion, models.CASCADE, verbose_name='Question', null=True, blank=True ) problem=models.ForeignKey( Problem, models.CASCADE, verbose_name='Problem', null=True, blank=True ) next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True, related_name='next_question') def __str__(self): return self.option_type forms.py class EditQuestionForm(forms.ModelForm): class Meta: model = ChatQuestion fields =('question','problem_id') class EditOptionForm(forms.ModelForm): class Meta: model = Option fields =('option_type',) views.py def question_edit(request,id=None): if id is not None: queryset = get_object_or_404(ChatQuestion,pk=id) queryset1=get_object_or_404(Option,question_id=queryset ) else: queryset = None queryset1 = None if request.method=="POST": form = EditQuestionForm(request.POST ,instance=queryset) form1=EditOptionForm(request.POST, instance=queryset1) if form.is_valid() and form1.is_valid(): question=form.cleaned_data['question'] option_type=form1.cleaned_data['option_type'] if id: … -
Out of range value issue while migrating django's default contenttypes
When I run python manage.py migrate I am getting this error - django.db.utils.DataError: (1264, "Out of range value for column 'id' at row 1") The file at which the error is being thrown is this - import django.contrib.contenttypes.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='ContentType', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ('app_label', models.CharField(max_length=100)), ('model', models.CharField(max_length=100, verbose_name='python model class name')), ], options={ 'ordering': ('name',), 'db_table': 'django_content_type', 'verbose_name': 'content type', 'verbose_name_plural': 'content types', }, bases=(models.Model,), managers=[ ('objects', django.contrib.contenttypes.models.ContentTypeManager()), ], ), migrations.AlterUniqueTogether( name='contenttype', unique_together={('app_label', 'model')}, ), ] I haven't written this file. It is being generated by Django itself. I am using MYSQL 5.7 as a database. -
Where i should add url() in django?
Installation: pip install django-bKash Add "bKash_payment" to your INSTALLED_APPS setting like this: INSTALLED_APPS = ( ... 'bKash_payment', ) Include the bKash_payment URLconf in your project urls.py like this: url(r'^bKash_payment/', include('bKash_payment.urls')), where to add this url? in url patterns?? -
Django Admin: initial data while adding related object
Hello I met a problem while trying to add new object via django admin to model who has reference to other model. Normally this problem wouldn't occur, but I'm using get_initial_for_field method. in my admin.py I have: @admin.register(UserProfile) class UserProfileAdmin(UserProfileExportMixin, admin.ModelAdmin): list_display = ('user', 'attrs', 'invited_by') form = UserProfileForm and UserProfile model has reference to django.contrib.auth.models.User. My UserProfileForm looks like: class UserProfileForm(forms.ModelForm): is_active = forms.BooleanField(required=False) class Meta: model = UserProfile exclude = ["id", ] fields = ["user", "invited_by", "avatar", "attrs", "phone_number", "is_active"] def get_initial_for_field(self, field, field_name): obj = super().save(commit=False) field_value = obj.user.is_active if field_name == "is_active": field.initial = field_value return super(UserProfileForm, self).get_initial_for_field(field, field_name) So when I attempt to see/change existing UserProfile there is no problem, because reference to user is set, but when I try to add new user profile I got RelatedObjectDoesNotExist. UserProfile has no user. I was trying to check is user exists: obj = super().save(commit=False) field_value = True if obj.user is not None: field_value = obj.user.is_active if field_name == "is_active": field.initial = field_value but it didn't work. Could somebody give me any tips how to solve this problem? -
Getting error when passing more than 1000 values in Django IN filter
I have list which contains more than 1000 entires. I have to check out of those 1000 entries how man exist in my table so I am using Django IN filter but it is giving me error Error: ('07002', u'[07002] [Microsoft][ODBC Driver 17 for SQL Server]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') and when I reduce the list of values to around 400 it works. Can anyone suggest me a better way to approach this. Thank You -
Filter list view based on foreign key of another model
I have three models, subjects, topics and study days. I want to display the study days in a list view but just show study days with different topics connected to the same subject. This is my model structure class Subject(models.Model): name = models.CharField(max_length=100, null=False) class Topic(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=False) class StudyDay(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) ... I have tried this in one the views and it filters correctly but it removes the data previously showing up associated with the study day, so it does not work correctly. def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['study'] = context['study'].filter(student=self.request.user) context['study'] = Topic.objects.filter(subject=3) # This is the line where I try to filter return context So the question is, is there any way for me to filter through the objects in the StudyDay model based on which subject the topic in the study day belongs to? -
Django form model alter the data before stored in database
I want to alter thedata in form_valid What I want to do is The model has the column action in database. form has the two field model_child_0 model_child_1 Now I want to add these two and store in action These are my source code, but in vain. Where am I wrong? class MyModelUpdateView(LoginRequiredMixin, UpdateView): model = MyModel template_name = 'mymodel_edit.html' form_class = MyModelForm def form_valid(self, form): print(form.cleaned_data['model_child_0']) print(form.cleaned_data['model_child_1']) form.cleaned_data['action'] = form.cleaned_data['model_child_0'] + form.cleaned_data['model_child_1'] return super().form_valid(form) -
Python: writing file and using buffer
I'm using django to generate personalized file, but while doing so a file is generated, and in terms of space using it is quite a poor thing to do. this is how i do it right now: with open(filename, 'wb') as f: pdf.write(f) #pdf is an object of pyPDF2 library with open(filename, 'rb') as f: return send_file(data=f, filename=filename) #send_file is a HTTPResponse parametted to download file data So in the code above a file is generated. The easy fix would be to deleted the file after downloading it, but i remember in java using stream object to handle this case. Is it possible to do so in Python? -
Submit the data from dynamically genereted form
I have simple model view class template, It makes input field for name and I can get the data after submit. <form method="post" name="uploadForm" role="form" action="{% url 'mymodel-list' object.id %}" enctype="multipart/form-data" > <div class="col-md-12"> <label>name</label> <div class="detailed-info"> {% render_field form.name class="form-control" %} {% for error in form.name.errors %} <div class="text-alert"> {{ error }} </div> {% endfor %} </div> </div> <div id="additional"></div> <button type="submit" class="btn btn-info">change</button> </form> After submit I can get the data here and store in database. class MyModelUpdateView(LoginRequiredMixin, UpdateView): model = MyModel template_name = 'mymodel_edit.html' form_class = MyModelForm def form_valid(self, form): d = form.cleaned_data['name'] return super().form_valid(form) Then, I want to add the form fields which is not in model, also dynamically added by jquery. <script> $(function(){ $("#additional").html(` <input type="text" id="name2"> <input type="text" id="name3">`); }) How can I send this data (name2,name3) together with name and how can I get this data in MyModelUpdateView? -
Get value from form in template
in Django template. Model data is passed in form And I can use {{form.my_data}} in template to get the data like <textarea name="pre_action" cols="40" rows="10" id="id_my_data">this is mydata</texstarea> However, I want to get the raw data this is mydata. Because I want to use this variable in jquery. Is it possible ? or its not good way to pass the data from django to jquery? -
Django nested transacation in two databases Errored with ProgramError
I have want to have nested transaction across different databases. (I know this does not guarantee transactional commit in two databases). One layer of nexsted transaction seems ok, however if I have outer layer transaction nested in inner layer again, sometimes I see error django.db.utils.ProgrammingError: relation "xxx" does not exist (Not 100% of time, but error occurs almost every 1 out of 2 runs). Following is the code to reproduce it: with transaction.atomic(using="db1"): with transaction.atomic(using="db2"): qs = ExampleModel.objects.all() #.select_for_update() for obj in qs: obj.type = "new_value" ExampleModel.objects.bulk_update(qs, ["type"]) with transaction.atomic(using="db1"): ExampleModel.objects.using("default").bulk_update(qs, ["type"]) What could have caused this? Is there a way to get around this? (I understand the innermost transaction is not necessary, but if there are nested function calls, I'd rather wrap each call in nested transaction rather than worry about checking upper layer caller) -
Django - how to return human readable from an enum (for multicheckbox forms)
I have this code, but it only returns the shorter variable values, 'Plan 1', 'Plan 2', not their longer human-readable forms which I have defined in the model. I generate checkboxes in a HTML template from a form.py and view.py by calling and passing in the variable (correct instance).student_loan_plan.all(), and passing that through the 'context' variable in the 'render' function MODEL # U.K. STUDENT LOAN PLAN MODEL class UK_Student_Loan_Plan(models.Model): STUDENT_LOAN_PLANS = [ ('Plan 1', 'Plan 1: English or Welsh student'), ('Plan 2', 'Plan 2: English or Welsh who started on 1 September 2012'), ('Plan 4', 'Plan 4: Scottish student who started on 1 September 1998'), ('Postgraduate', 'Postgraduate: English or Welsh student'), ] student_loan_plan_id = models.BigAutoField(verbose_name='Student Loan Plan ID', primary_key=True, serialize=False, auto_created=True) student_loan_plan = models.CharField(verbose_name='Student Loan Plan', max_length=12, choices=STUDENT_LOAN_PLANS, blank=True, unique=True, null=True) def __str__(self): return self.student_loan_plan QUESTION Q1. How do I get the full human readable form returned? I've tried this, but no success def __str__(self): return self.student_loan_plan.choice -
'modelBlog' object has no attribute 'CommentModel_set'
Im try make blog detail and comment in one page but if im try posting comment i got error like this 'modelBlog' object has no attribute 'CommentModel_set' My views def comment(request, id): blog = get_object_or_404(modelBlog, id=id) form = CommentForm(request.POST or None) heading = blog.title if request.method == 'POST': if form.is_valid(): data={ 'name':request.POST['name'], 'komentar':request.POST['komentar'], } blog.CommentModel_set.create(**data) return redirect('blog:detail', id) context = { 'title':'Detail', 'heading': heading, 'blog':blog, 'comment':comment, 'form':form } return render(request, 'blog/detail.html', context) And my model class modelBlog(models.Model): title = models.CharField(max_length=200) description = models.TextField() body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True,) def __str__(self): return ('{}.{}').format(self.id, self.title) class CommentModel(models.Model): user = models.ForeignKey('auth.User',default=1, on_delete=models.CASCADE) blog = models.ForeignKey(modelBlog, on_delete=models.CASCADE) name = models.CharField(max_length=200) komentar = models.TextField() pub_date = models.DateTimeField(auto_now_add=True,) My templates <form action="{% url 'blog:comment' blog.id %}" method="post"> {% comment %} {% endcomment %} {% csrf_token %} {% for forms in form %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">{{forms.label}}</label> <input type="{{forms.type}}" name="{{forms.name}}" class="form-control" id="exampleFormControlInput1"> </div> {% endfor %} <button type="submit" class="btn btn-primary">Kirim</button> </form> -
Hx-push-url doesn’t work on back button click
I am trying to integrate Htmx with django and achieve single page application behaviour. I am rewritting Djangoproject.com poll app with htmx. When I click on detail page link, content loads, htmx push a new url in address bar. When I press back button, it took me to index page perfectly for the first time, after that if I again go to detail page and click back button, url shows of the index, button index content doesn’t load, content remains same as detail page. Here is my code views.py def index(request): latest_question_list = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} if request.headers.get("Hx-Request") is not None: return render(request, 'main/index/index.html', context) else: return render(request, 'main/index/index-full.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) print(request.headers.get("Hx-Request")) if request.headers.get("Hx-Request") is not None: return render(request, 'main/detail/detail.html', {'question': question}) else: return render(request, 'main/detail/detail-full.html', {'question': question}) index.html <div id="index" class=""> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><div class="has-text-link" hx-get="{% url 'main:detail' question.id %}" hx-push-url="true" hx-target="#index" hx-swap="outerHTML">{{ question.question_text }}</div></li> {% endfor %} </ul> {% else %} <p> No polls are available. </p> {% endif %} </div> index-full.html {% extends 'base.html' %} {% block content %} {% include 'main/index/index.html' %} {% endblock content %} detail.html <div id="detail" … -
TypeError: 'NoneType' object is not callable django websockets
i'm trying to add a notification feature to my projet. but when i try to connect using postman i get TypeError: 'NoneType' object is not callable. i have no idea why im getiing this error. the error doesnt even indicate a line in my code. this is my consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class NotificationConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['user_id'] user = self.scope['user'] if self.room_name == user: async_to_sync(self.channel_layer.group_add)( self.room_name, self.channel_name ) self.accept() return async def disconnect(self, code): return await self.close() def receive(self, text_data=None): return def send_notifications(self, event): data = json.loads(event.get('value')) self.send(text_data=json.dumps({'payload':data})) this is my routing.py from django.urls import re_path from .consumers import NotificationConsumer websocket_urlpatterns = [ re_path(r'ws/notification/(?P<user_id>\w+)/$', NotificationConsumer.as_asgi()), ] this is my channelsmiddleware.py from django.db import close_old_connections from rest_framework_simplejwt.tokens import UntypedToken from rest_framework_simplejwt.exceptions import InvalidToken, TokenError from jwt import decode as jwt_decode from clothRentalBackend import settings from django.contrib.auth import get_user_model from urllib.parse import parse_qs class TokenAuthMiddleware: """ Custom token auth middleware """ def __init__(self, inner): # Store the ASGI application we were passed self.inner = inner def __call__(self, scope): # Close old database connections to prevent usage of timed out connections close_old_connections() # Get the token token = parse_qs(scope["query_string"].decode("utf8")).get("token")[0] try: UntypedToken(token) except (InvalidToken, TokenError) … -
django.core.exceptions.FieldDoesNotExist: User has no field named 'phone'
I'm trying to customize Django's AbstractBaseUser and make phone as a main field like username in AbstractUser model. But when I'm trying to migrate or run the server I'm getting the follow error: "django.core.exceptions.FieldDoesNotExist: User has no field named 'phone'". USERNAME_FIELD, REQUIRED_FIELDS are all set in Custom User and AUTH_USER_MODEL = 'users.User' is also available in settings.py. Here is the code: class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): USER = 1 BUSINESS_OWNER = 2 #choices for user type USER_TYPE_CHOICES = [ (USER, _('User')), (BUSINESS_OWNER, _('Business Owner')) ] first_name = models.CharField( _('first name'), max_length=200 ), user_type = models.PositiveSmallIntegerField( _('user type'), choices=USER_TYPE_CHOICES, default=USER ) phone = models.CharField( _('phone number'), max_length=13, unique=True ), sms_code = models.CharField( _('SMS code'), null=True #TODO: if verification requires change null ) last_name = models.CharField( _('last name'), max_length=200, null=True, blank=True ), is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('is active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField( _('date joined'), default=timezone.now ) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['first_name'] objects = users_managers.UserManager() class Meta: verbose_name = _('User') verbose_name_plural = _('Users') db_table = 'users' Code of UserManager: … -
generate presigned url sse-c s3
How to generate a presigned url to get an URL to an object using when SSE-C is used in python? When I upload the file, this is what my code looks like secret = '?D(G+KbPeSgVkYp3s6v9y$B&E)H@McQf' # just pasting here. In general, it's usually derived from .env file return client.put_object( Bucket=os.environ.get('S3_DOCS_BUCKET'), Key='koushik.jpg', # giving a random name for .jpg image file Body=file, ContentType=fileobject.content_type, SSECustomerAlgorithm='AES256', SSECustomerKey=secret, ) Now, this uploads fine. But the problem is that I can't generate pre signed URL like this url = client.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': os.environ.get('S3_DOCS_BUCKET'), 'Key': 'koushik.jpg', 'SSECustomerAlgorithm': 'AES256', 'SSECustomerKey': '?D(G+KbPeSgVkYp3s6v9y$B&E)H@McQf', # just pasting here }, ExpiresIn=3600, ) The key that it generates says that the signature doesn't match. Now I've searched, at some places, it says that I've to provide the SSECustomerKeyMD5 params as well. I've tried doing that and still doesn't work. url = client.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': os.environ.get('S3_DOCS_BUCKET'), 'Key': 'koushik.jpg', 'SSECustomerAlgorithm': 'AES256', 'SSECustomerKey': '?D(G+KbPeSgVkYp3s6v9y$B&E)H@McQf', # just pasting here, 'SSECustomerKeyMD5': hashlib.md5('?D(G+KbPeSgVkYp3s6v9y$B&E)H@McQf'.encode('utf-8')).hexdigest() }, ExpiresIn=3600, ) I've spent days but still can't get a working solution. If anyone can, please show an working example of file upload(a.k.a put_object) by providing SSECustomerKeyMD5. I think that would help me a lot. Thank you in advance. -
Migrating content type is throwing an error
When I run this command python manage.py migrate contenttypes I am seeing an error as django.db.utils.DataError: (1264, "Out of range value for column 'id' at row 1"). I have no tables in my database it is all empty. I have deleted all the migration folders and then I tried to migrate the contenttypes. My Django versions is django~=3.2.12 Here is the complete traceback of the error - Operations to perform: Apply all migrations: contenttypes Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/usr/local/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.DataError: (1264, "Out of range value for column 'id' at row 1") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", … -
Popup not showing after adding my frontend with react inside a Django project
I am using Reactjs to create a Popup that should appear when I click on a button. Tha same code is running when the project is alone, but once I insert it in django, Everything is working except the popup of the form. When I click on it i get a blank page. Ps: When I set the useState(true), nothing appears from the start.(white page again) (Even my confirmation dialog is working) (I am using some components from material ui) This is the main page where I have the button, and where the popup should appear: export default function Documents() { const [openPopup, setOpenPopup] = useState(false); return ( <div className={classes.newButton}> <Buttons text="My Button" color="warning" startIcon={<AddCircleOutlineOutlinedIcon />} onClick={() => { setOpenPopup(true); }} /> </div> <Popup title="Title of my Popup" openPopup={openPopup} setOpenPopup={setOpenPopup}> <DocumentForm /> </Popup> ) This is the Popup component: import { Dialog, DialogContent, DialogTitle, Typography } from "@mui/material"; import React from "react"; import ActionButton from "./Controls/ActionButton"; import CancelIcon from "@mui/icons-material/Cancel"; export default function Popup(props) { const { title, children, openPopup, setOpenPopup } = props; return ( <Dialog open={openPopup} maxWidth="md"> <DialogTitle> <div style={{ display: "flex" }}> <Typography variant="h6" component="div" style={{ flexGrow: 1 }}> {title} </Typography> <ActionButton onClick={() => { setOpenPopup(false); }}> … -
How to get or create on Django Rest Framework and return it
I would like to send post request with json data as shown below. { "checkin_date": "2022-02-15", "checkout_date": "2022-02-18", "guest_number": 1, "user": { "first_name": "Huesped", "last_name": "1", "email": "huesped_1@mail.com", "phone": "+34 12345678" } } How can I override some ModelSerializer method to get the user if the email exists, or create it and return its id for reservation related? Can it be done in a single query with nested objects or should I do 2 queries? Here are my python files. models.py: class Reservation(models.Model): user = models.ForeignKey(get_user_model(), verbose_name="User", related_name='user_reservations', on_delete=models.CASCADE) serializers.py: class ReservationPostSerializer(serializers.ModelSerializer): user = UserPostSerializer() Thanks in advance. -
Increment the order attribute in model according to the data in spreadsheet
I have spreadsheet column which has two types of choices A and B when i extract the data from the excel sheet it will check the choice type and increment the field order how can i achieve this the data can be like only Data. Order A 1 A 2 A 3 A 4 A 5 B 6 B 7 B 8 Mymodel.objects.create(order='',) How can i increment the order according to the retreived data -
Best practice put nginx + django in AWS subnet private?public?
I want to put the fargate container which contains django + nginx However what subnet should be used for? At first I put this in public subnet, of course it works well. However, is it possible to put this in private subnet with NAT gateway? A few users(admin) need to access to this django, it doesn't need to get access from other users. -
The input field could not show the expected result that I filled in Django
customer/update_order.html <table class="table table-striped table-bordered"> <form method="POST" action="."> {% csrf_token %} <tr> <th style="width:160px;text-align:center;background-color: blue;color:red;">食物</th> <th style="width:100px;text-align:center;background-color: blue;color:red;">單價</th> <th style="width:100px;text-align:center;background-color: blue;color:red;">數量</th> <th style="width:100px;text-align:center;background-color: blue;color:red;">總價</th> <th style="width:100px;text-align:center;background-color: blue;color:red;"></th> </tr> {% for item in food %} <tr> <td style="text-align:center;vertical-align:middle;"> {{ item.product.name }} </td> <td style="text-align:center;vertical-align:middle;">$ {{ item.unit_price }}</td> <td style="text-align:center;vertical-align:middle;"> <input name="qty{{ item.id }}" type="text" value="{{ item.quantity }}"> </td> <td style="text-align:center;vertical-align:middle;"> <a href="{% url 'update_item_qty' item.id %}" class="btn btn-warning">更新</a> </td> <td style="text-align:center;vertical-align:middle;">$ {{ item.total_price }}</td> </tr> {% endfor %} <tr> <td colspan="4" align="left" class="upline"><strong>總計</strong></td> <td align="center" class="upline">$ {{ order.total_price }} (包括$100運費)</td> </tr> <tr> <td colspan="4" align="left" class="upline"><strong>換領積分</strong></td> <td align="center" class="upline">{{ order.points_earned }}</td> </tr> </form> </table> views.py def update_order(request,order_id): global cartlist_update order = Order.objects.get(id=order_id) food = OrderDetail.objects.filter(order=order) cartlist_update = [] for item in food: cart = [] menu_food = Menu.objects.get(name=item.product.name) food_name = OrderDetail.objects.get(product=menu_food) cart.append(food_name.product.name) cart.append(food_name.unit_price) cart.append(food_name.quantity) cart.append(food_name.total_price) print(cart) cartlist_update.append(item) print(cartlist_update) context = {'order':order,'food':food} return render(request,'customer/update_order.html',context) def update_item_qty(request,item_id): global cartlist_update menu = OrderDetail.objects.get(id=item_id) print(menu.id) qty_id = 'qty'+str(menu.id) print(qty_id) new_quantity = request.POST.get(qty_id,'') print(new_quantity) order_id = menu.order.id ## original_food = menu.product.name price = menu.unit_price return redirect('update_order',order_id=order_id) models.py class Order(models.Model): PAYMENT_OPTIONS = ( ('VISA','VISA'), ('Master','Master'), ('Octopus','Octopus'), ('Cash','Cash'), ) STATUS = ( ('Pending','Pending'), ('Approved','Approved'), ('On the way','On the way'), ('Delivered','Delivered'), ('Completed','Completed'), ) METHODS = ( ('外賣自取','外賣自取'), ('送遞','送遞'), ) … -
File transfer link V.ht
Please let me know how we can shorten the large link into the short link (Example v.ht) As we know if we upload a file through WETransfer and then short their share link we use v.ht please let me know the basic working of this?