Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - How to set the current_user when POST
I have just followed a small tutorial using DRF, but I can't figure how to like my model to his user when POSTing a new object this is my model : # Create your models here. class Project(models.Model): # project title title = models.CharField(max_length=255, null=False) # subtitle subtitle = models.CharField(max_length=255, null=False) ####### user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) and so my serializer class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ("id", "title", "subtitle", "user_id") so, now in the view I have access to the current_user with this : request.user class ListProjectsView(generics.ListCreateAPIView): authentication_classes = [authentication.TokenAuthentication] queryset = Project.objects.all() serializer_class = ProjectSerializer def list(self, request): queryset = Project.objects.filter(user_id=request.user.id) serializer = ProjectSerializer(queryset, many=True) return Response(serializer.data) [...] def create(self, request, pk = None): return super(ListProjectsView, self).create(request, pk = None) I suppose there is a way to passe the request.user is the create in order to allow my Project.user_id to be filled ? Whatever I'm doing, I can't manage to set the user, and i get the django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint error Any idea? Thanks! -
how to save this form?
I tried how to save this code. it shows the form in the template but when the form filled and submit the data isn't saving to the database here is my views.py def create_tables(request): restaurant = Restaurant.objects.get(user=request.user) print(restaurant) form = TablesForm(request.POST or None, instance=request.user) if form.is_valid(): user = form.save(commit=False) user.refresh_from_db() user.restaurant = restaurant user.name = form.cleaned_data.get('name') user.time = form.cleaned_data.get('time') user.save() return redirect('/') args = { 'table': restaurant, 'form': form } return render(request, 'main/tt.html', args) and also here is my forms.py class TablesForm(forms.ModelForm): name = forms.CharField(max_length=250, label="Table Name") time = forms.ModelChoiceField(queryset=Time.objects.all()) class Meta: model = Table fields = [ 'name', 'time', ] so help me please. -
What to write in application root when deploying django app in cpanel
Am deploying my first django app in cpanel, when filling details am stack in the category called application root, which is the physical address of where I will deploy. I have tried to write many words as I have seen by searching through google like django,app, and others nothing has worked. Also I went through my file structure in cpanel account to look which location am going to deploy my site, tried several of them but none of them has worked. Below are the links for more details file structure in my cpanel account and place to input application root -
Django request into forms.py
In a view, I define the user database from request.user: def delete(request, pk): electricity_supply = get_object_or_404( ElectricitySupply.objects.using( request.user.accounts_database_id.database_name ), pk=pk, ) electricity_supply.delete() How to use request in forms.py? class ClientGroupForm(forms.ModelForm): group_name = forms.ModelChoiceField( queryset=ClientGroup.objects.all() ) subgroup_name = forms.ModelChoiceField( queryset=ClientSubGroup.objects.all() ) class Meta: model = ClientSubGroup fields = ["group_name", "subgroup_name"] -
How to write equivalent filter in django for the below query
Below is a query which i am using for a search screen. Mobile1, sponsor1 and status1 are the field inputs from the user. If these fields will not be entered then all the values should be returned as output. Query ----- Select * from customer where mobile = nvl(mobile1,mobile) and sponsor = nvl(sponsor1,sponsor) and status = nvl(status1,status); Models.py --------- class customer(models.Model): company = models.CharField(max_length=3) mobile = models.CharField(max_length=10) name = models.CharField(max_length=100) sponsor = models.CharField(max_length=10) address1 = models.CharField(max_length=200) country = models.CharField(max_length=101) state = models.CharField(max_length=100) city = models.CharField(max_length=100) zip = models.CharField(max_length=6) email = models.EmailField(max_length=100) status = models.CharField(max_length=1) creator = models.CharField(max_length=20) cretime = models.DateTimeField(default=datetime.now) updator = models.CharField(max_length=20) updtime = models.DateTimeField(default=datetime.now, blank = True ) -
Django - Problem with Implementing Models and Views in My PhoneReview Application
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models for: Brand – details on brand, such as, name, origin, manufacturing since, etc Model – details on model, such as, model name, launch date, platform, etc Review – review article on the mobile phone and date published, etc Many-to-many relationship between Review and Model. Now, I have to create views for the following: a. An index page that display all Brands available for mobile phone in the database b. A phone model page that display model when a brand is selected. c. A detail page when a model is selected that contain reviews and newslink I have managed to create view for "a. An index page that display all Brands available for mobile phone in the database." However, I am stuck with "b. A phone model page that display model when a brand is selected." I have managed to display the phone model page. However, the name of the phone model is not being displayed. So, I feel that … -
how to add another table in django-admin site?
I have this table inside of students enrollment record(adminsite) how do i add this table under the table students enrollment record when the admin filter/or click the monthly? this is my code in model.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) this is my code in admin.py admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): #inlines = [InLineSubject] list_display = ('lrn', 'Student_Users', 'School_Year', 'Courses', 'Section', 'Payment_Type', 'Education_Levels') #list_select_related = ('Student_Users') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') def lrn(self, obj): return obj.Student_Users.lrn @admin.register(ScheduleOfPayment) class ScheduleOfPayment(admin.ModelAdmin): list_display = ('Education_Levels','Payment_Type','Display_Sequence','Date','Amount','Remark','Status') ordering = ('Education_Levels','Payment_Type','Display_Sequence') list_filter = ('Education_Levels','Payment_Type') -
Docker compyling python file in Dockerfile
I would to create a docker image from my django app but i don't whant pull my .py file. For doint this i need a way to compile my python file in docker then remove all *.py and left only *.pyc file. If i simply in .dokerignore file whrite **/*.py i get the error ImportError: bad magic number in 'ajaxfuncs': b'\x03\xf3\r\n' because my original *.py file was compiled with a different python version (local python3.6.0 docker python3.6 for alpine) So as workaround i would build my python file in dockerfile and then remove all py first in my .dockerignorefile i put: **/*.pyc then in my Dockerfile think to use python -m py_compile for generate my new *.pyc files: FROM python:3.6-alpine EXPOSE 8000 RUN apk update RUN apk add --no-cache make linux-headers libffi-dev jpeg-dev zlib-dev RUN apk add postgresql-dev gcc python3-dev musl-dev RUN mkdir /Code WORKDIR /Code COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . /Code/ RUN python -m py_compile /Code/ajaxfuncs/ajax.py /Code/ajaxfuncs/asktempl.py /Code/ajaxfuncs/group.py /Code/ajaxfuncs/history.py /Code/ajaxfuncs/template_import.py RUN rm -rf /Code/ajaxfuncs/*.py ENTRYPOINT python /Code/core/manage.py runserver 0.0.0.0:8000 but when i run my application seem that compiler does not compile my files, because no pyc … -
setting a gallery in a amp lightbox with django
thanks for your time. i've been working on a project with django on the back end and amp on the frontend although im having some troubles to link both tags like the lightbox one. i'd like to get a list of first images on my product page(i've done it) and by clicking on a image it displays me the other images of that object on a lightbox without going to the detail template. the whole project its just updated on github at: https://github.com/lucasrf27/dealership thats the amp code that i'm trying to. i'm trying this one on test.amp.html besides put on my category (product template) <div> {% for v in veiculos %} <amp-img src="{{ v.first_image.imagem.url }}" on="tap:cars" width="200" height="100"></amp-img> <amp-carousel id="cars" lightbox="{{v.modelo}}" width="1600" height="900" layout="responsive" type="slides"> {% for i in veiculos.images.all %} <amp-img lightbox src="{{ i.imagem.url }}" width="30" height="30" alt="apples"></amp-img> {% endfor %} </amp-carousel> {% endfor %} </div>´ i'm not shure if i'm passing the variables wrong on my views.py i'd like to get a list of first images as i did and by clicking in one of them open a lightbox with the other images of that product -
My contact page displays an error "No module named "'django"" on heroku but it works fine on my local machine
I can send a message from my local computer to my email just fine but when i deploy my app on heroku i get an error message 'No module named "'django"'. What might be the problem? Views.py @login_required(login_url='/accounts/login/') def s_contact(request): c_form = ContactForm if request.method == 'POST': c_form = ContactForm(data=request.POST) if c_form.is_valid(): email = c_form.cleaned_data['email'] subject = c_form.cleaned_data['subject'] message = c_form.cleaned_data['message'] send_email(email, subject,message, ['myemail@gmail.com']) messages.success(request, f'Your message has been sent!') return redirect(seller_home) else: email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') context = { 'c_form': c_form } return render(request, 'seller/contact.html', context) Forms.py class ContactForm(forms.Form): email = forms.EmailField(label='Your Email') subject = forms.CharField(required=True, max_length=150) message = forms.CharField(widget=forms.Textarea, required=True) Kindly assist guys. -
Django: Get a table into Django view
How do I get a table in Django View? I have tried both post and get within below, but object returns None <form method="post" action="{% url 'product-send2' %}"> {% csrf_token %} <div class="table-wrapper"> <table class="form-control table display responsive" id='datatable' style="width:100%;"> <thead> <tr> <th>Send</th> <th>Name</th> <th>Status</th> </tr> </thead> <tbody> {% for object in object_list %} <tr> <td></td> <td>{{ object.name }}</td> <td>{{ object.status }}</td> <tr> {% endfor %} </tbody> <tfoot> </tfoot> </table> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> In the Urls path('product/send/', send_product2, name='product-send2') and in the views def send_product2(request): recipients = request.POST.get('datatable') print(recipients) return HttpResponseRedirect('/product/list') I have tried variants such as recipients = request.GET.get('datatable') and recipients = request.POST.get('datatable', False) I cannot get hold of the "object" and don't really know how to debug it. In the end, I am trying to have checkboxes in the table and the selection should work as a multiselect for the form (that will be sent by email). I hope I can help with some hints how to progress. Thanks! When i print(request.dict) it looks like below : <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x7f907ab5f680>>, '_messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7f907ab82b10>, '_body': b'csrfmiddlewaretoken=xxx_length=10', '_post': <QueryDict: {'csrfmiddlewaretoken': ['xxxxx'], 'datatable_length': ['10']}>, '_files': <MultiValueDict: {}>, 'csrf_processing_done': True} -
Django URL related models for UpdateView
I have two model related with ForeignKey and everything works excepted but when i try to update PatientData related to Patient with different IDs i have problem. For example if Patient with ID 1 have PatientData with ID 1 it works. But if I have Patient with ID 5 and want to update PatientData with ID 20, the URL not working. Now what i have is working in the Admin Pannel. When i go to PatientData and press the "VIEW ON SITE" it works. But in the template the rendering part is not working. patient_update_form.html Details button guide to PatientData "html". <a href='{{ patientdataupdate.get_absolute_url }}'><button type="button" class="btn btn-info">Details</button></a> Model1 class Patient(models.Model): female_name = models.CharField(max_length=120) female_surename = models.CharField(max_length=120) male_name = models.CharField(max_length=120) male_surename = models.CharField(max_length=120) day_insert_patient = models.DateTimeField(default=datetime.now, blank=True) def get_absolute_url(self): print(self) return reverse('patients:patientupdate', [self.pk], kwargs={'pk': self.pk}) Model2 class PatientData(models.Model): patientfk = models.ForeignKey(Patient, default=None, on_delete=models.CASCADE, related_name='patientfk') female_age_model = models.DateField() female_age = models.IntegerField(db_column='Age',blank=True) male_age_model = models.DateField() male_age = models.IntegerField(db_column='MaleAge',blank=True) This is the View.py class PatientUpdate(LoginRequiredMixin, UpdateView): login_url='/login/' model = Patient form_class = PatientForm template_name_suffix = '_update_form' success_url = '/' class PatientDataUpdate(LoginRequiredMixin, UpdateView): login_url='/login/' model = PatientData form_class = PatientDataForm template_name_suffix = '_update_form' success_url = '/' And url.py path('patient/<int:pk>/', views.PatientUpdate.as_view(), name='patientupdate'), path('patient/<int:pk>/patientdetails/<int:patientfk>/', views.PatientDataUpdate.as_view(), name='patientdataupdate'), … -
Input prompt not working in Pycharm's Django `Run manage.py Task...` console?
When I use Pycharm's Run manage.py Task... console, everything works well, until the command expects some user input. For example makemigrations and migrate commands work just fine, because they don't require any additional user input: But commands which require some intermediate input, like createsuperuser and collectstatic don't work at all. The input prompts don't show up, and typing in the console does nothing: I've tried googling this issue, but since it doesn't seem to appear to affect any other users, I don't think it's an actual bug in this version of Pycharm (macOS 2019.2.1 Professional Edition). -
How to add another table in Select students enrollment record to change
how do i add this table under the table students enrollment record when the admin filter/or click the monthly? this is my code in model.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) this is my code in admin.py admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): #inlines = [InLineSubject] list_display = ('lrn', 'Student_Users', 'School_Year', 'Courses', 'Section', 'Payment_Type', 'Education_Levels') #list_select_related = ('Student_Users') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') def lrn(self, obj): return obj.Student_Users.lrn @admin.register(ScheduleOfPayment) class ScheduleOfPayment(admin.ModelAdmin): list_display = ('Education_Levels','Payment_Type','Display_Sequence','Date','Amount','Remark','Status') ordering = ('Education_Levels','Payment_Type','Display_Sequence') list_filter = ('Education_Levels','Payment_Type') -
How to calculate 2x + 4 = 10 using sympy. Is it possible that?
How to calculate 2x + 4 = 10 using sympy. Is it possible that? This not run on sympy gamma but it is run on wolframalpha and cymath. Is it any logic or some bulit in library that we are used this type of equation. please help me. -
Store four decimal places but show two in Django admin form
Is it possible to store in my models decimal fields with four decimal places but to show only two in Django admin forms. class MyModel(models.Model): purchase_price_gross = models.DecimalField( _('Purchase price (gross)'), validators=[MinValueValidator(0.0)], max_digits=19, decimal_places=4) Now in the Admin form the field is showing with 4 decimal places. But how can I restrict the forms to show only two places? -
How to automatically populate fields in a specific form
I'm developing a django app to keep track of orders and products in my laboratory. I have an Order model that I create instances from with a form that fills some of its fields (but not all) and creates an object. I've also created an UpdateForm to update the blank fields once the order arrives to the lab. This update form has just one field (storage location), but I want this form to automatically set the status of the order to "received" and populate the "received_by" field with the logged user and "received_date" with the dateTime when the form is sent.. While writing this I just thought I could create a different model for Receive and relate it to the Order model via OnetoOne, would that be a proper solution? -
For loop in Django template while changing the HTML each iteration
So I have this piece of HTML: <div class="core-features-single"> <div class="row"> <div class="col-sm-6"> <div class="core-feature-img"> <img src="assets/images/watch-4.png" class="img-responsive" alt="Image"> </div> </div> <div class="col-sm-6"> <div class="core-feature-content arrow-left"> <i class="icofont icofont-brand-android-robot"></i> <h4>Android and iOS Apps Install</h4> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat.</p> </div> </div> </div> </div> <div class="core-features-single"> <div class="row"> <div class="col-sm-6"> <div class="core-feature-content arrow-right"> <i class="icofont icofont-ui-text-chat"></i> <h4>Live Chat With Friends</h4> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat.</p> </div> </div> <div class="col-sm-6"> <div class="core-feature-img"> <img src="assets/images/watch-5.png" class="img-responsive" alt="Image"> </div> </div> </div> </div> Which generates this kind output in the webpage: But how do I iterate an HTML element like this? Because the text and image block order are changing each iteration. What I came up with: {% for entry in page.product_features_showcase.all %} {% image entry.image height-1000 as img %} <div class="core-features-single"> <div class="row"> <div class="col-sm-6"> <div class="core-feature-content arrow-{% cycle 'left' 'right' 'left' 'right' 'left' 'right' 'left' 'right' %}"> <i class="icofont icofont-phone"></i> <h4>{{ page.product_features_showcase_title }}</h4> <p>{{ page.product_features_showcase_description }}</p> </div> </div> <div class="col-sm-6"> <div class="core-feature-img"> <img src="{{ img.url }}" class="img-responsive" alt="Image"> </div> </div> </div> </div> {% endfor %} I know I can use cycle to make different CSS classes each iteration. But … -
Push online troubles
I'm trying to push my Django project to Heroku, but I'm having troubles: Enumerating objects: 20, done. Counting objects: 100% (20/20), done. Delta compression using up to 4 threads Compressing objects: 100% (18/18), done. Writing objects: 100% (20/20), 4.89 KiB | 358.00 KiB/s, done. Total 20 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to teacher-rating. remote: To https://git.heroku.com/teacher-rating.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/teacher-rating.git' I'm doing a project to help teachers realize their qualities and I'm having trouble pushing my code online. I need help because it would be amazing if teachers would treat us as we deserve. -
Is there a way to make select columns editable from df.to_html in Django?
I'm new to using Django and I'm currently taking data I have stored in a CSV and am trying to display on my website as a table. I'm importing the csv as a dataframe in pandas and then using df.to_html() to convert it to a table and passing into render within views.py. The code is shown below and a screenshot of what it renders is shown. However, I would like to make the last 3 columns editable so the user can change the values there. The commented out line is an attempt I've made, but it doesn't achieve the desired result. Does anyone know how I might go about making these editable? def optimizer(request): df = Optimizer.get_daily_roster('E:\website\optimizer\Predictions.csv') df = df.drop(columns=['Name + ID', 'Game Info', 'Unnamed: 0', 'Unnamed: 0.1', 'name']) df = df.rename(columns={'TeamAbbrev': 'Team', 'AvgPointsPerGame': 'Predicted FP'}) # df['Predicted FP'] = df['Predicted FP'].apply(lambda x: '<div contenteditable="true">' + str(x) + '</div>') df['Min Exposure'] = 0 df['Max Exposure'] = 1 html_table = df.to_html(index=False, justify='left', classes=[ 'table table-bordered table-striped table-hover table-responsive table-sm, container-fluid']) return render(request, 'optimizer/optimizer.html', {'player_table': html_table}) I am trying to make it so users can edit the last 3 columns: Predicted FP, Min Exposure, and Max Exposure. -
Null value violates not-null constraint, but model has blank=True null=True
I have a form class EmployeeHistoryForm(forms.ModelForm): department = forms.ModelChoiceField( label="Подразделение", queryset=Department.objects.all() ) post = forms.ModelChoiceField( label="Должность", queryset=Post.objects.all() ) rank = forms.IntegerField( label="Разряд", validators=[ MaxValueValidator(MAX_RANK), MinValueValidator(1) ]) start_date = forms.DateField( label="Дата начала работы", initial=datetime.now().date() ) class Meta: model = EmployeeHistory exclude = ['employee', 'end_date'] to model class EmployeeHistory(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) rank = models.IntegerField( validators=[ MaxValueValidator(MAX_RANK), MinValueValidator(1) ] ) start_date = models.DateField() end_date = models.DateField(blank=True, null=True) employee field is filled from another form and I want to keep end_date None-typed for a while. This is view: def add_employee_action(request): if request.method == "POST": ... history_form = EmployeeHistoryForm(request.POST) if personal_form.is_valid() and history_form.is_valid(): ... employee.save() history=EmployeeHistory( employee=employee, department=Department.objects.filter( pk=request.POST['department'] )[0], post=Post.objects.filter( pk=request.POST['post'] )[0], rank=request.POST['rank'], start_date=datetime.now().date(), end_date=None ) history.save() else: ... history_form = EmployeeHistoryForm() return render( request, 'add_employee.html', context={ ... 'history_form': history_form, } ) But when I submit the form have a django.db.utils.IntegrityError: null value in column "end_date" violates not-null constraint DETAIL: Failing row contains (7, 12, 2019-10-26, null, 1, 10, 1). I'm using PostgreSQL. Note: I've added blank=True, null=True after first migration, then migrate again. May be this will importaint. -
How to query more than two tables in Django?
I want to make a big query with multiple tables. My model will be written below, in which there are 5 ForeignKeys, that is, I will touch on 5 tables. class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, related_name='deal', on_delete=models.CASCADE) service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) context = models.TextField(blank=True, null=True) Also, PayerPaymentSource contains ForeignKey.And need will from it another request like select_related() How to implement such a query? -
How to show spacific restaurant tables?
I'm working on Restaurant Reservation app, I wanna show every restaurant's tables after that when the person click on it, it will redirect to booking form page, in that page I wanna show the list of available tables of that restaurant. this is my models.py class Restaurant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=250) class Table(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) time = models.ForeignKey(Time, on_delete=models.CASCADE, null=True, blank=False) booked_by = models.OneToOneField(User, null=True, on_delete=models.SET_NULL, related_name='table_booked', blank=True) name = models.CharField(max_length=100, help_text="Table name or number.", blank=False) so here is my forms.py, now it will show all the available tables of all restaurants. class BookingFormm(forms.ModelForm): table_booked = ModelChoiceField(queryset=Table.objects.filter(booked_by__isnull=True)) class Meta: model = Table fields = ['table_booked'] And here is my views.py @login_required def booking(request): form = BookingForm(request.POST or None, instance=request.user) if form.is_valid(): user = form.save(commit=False) tbl = form.cleaned_data['table_booked'] tbl.booked_by = request.user tbl.save() user.save() print(request.user.table_booked.id, request.user.table_booked.is_booked) return redirect('/') return render(request, 'booking/booking.html', {'form': form}) If you have any idea please help me. Thanks. -
How to solved that equation using sympy
I want to calculate 2x+2=10 and print the output is 6. Is that possible using sympy? i am not use pythion shell. i am done my code in pycharm and run on localhost. so can uh pleasen help me? how to run that? -
Unable to connect to PostgreSQL with SSL on Django
My database configuration in Django's settings.py: 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("DB_NAME"), 'USER': os.environ.get("DB_USER"), 'PASSWORD': os.environ.get("DB_PASS"), 'HOST': os.environ.get("DB_HOST"), 'PORT': '5432', 'OPTIONS': { 'sslmode': 'verify-full', 'sslrootcert': '/home/{user}/.postgresql/default_root.crt', 'sslcert': '/home/{user}/.postgresql/default.crt', 'sslkey': '/home/{user}/.postgresql/default.key', }, } Running python manage.py dbshell --database default throws the following errors: psql: FATAL: connection requires a valid client certificate FATAL: no pg_hba.conf entry for host "{DB_HOST}", user "{DB_USER}", database "{DB_NAME}", SSL off The full error traceback: Traceback (most recent call last): File "manage.py", line 20, in <module> main() File "manage.py", line 16, in main execute_from_command_line(sys.argv) File "/home/{user}/.virtualenvs/{project_name}/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/{user}/.virtualenvs/{project_name}/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/{user}/.virtualenvs/{project_name}/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/{user}/.virtualenvs/{project_name}/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/{user}/.virtualenvs/{project_name}/lib/python3.6/site-packages/django/core/management/commands/dbshell.py", line 22, in handle connection.client.runshell() File "/home/{user}/.virtualenvs/{project_name}/lib/python3.6/site-packages/django/db/backends/postgresql/client.py", line 71, in runshell DatabaseClient.runshell_db(self.connection.get_connection_params()) File "/home/{user}/.virtualenvs/{project_name}/lib/python3.6/site-packages/django/db/backends/postgresql/client.py", line 61, in runshell_db subprocess.check_call(args) File "/usr/lib/python3.6/subprocess.py", line 311, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['psql', '-U', '{DB_USER}', '-h', '{DB_HOST}', '-p', '5432', '{DB_NAME}']' returned non-zero exit status 2. However, when I run psycopg2.connect("host={DB_HOST} dbname={DB_NAME} user={DB_USER} password={DB_PASS} sslmode=verify-full sslcert=/home/{user}/.postgresql/default.crt sslkey=/home/{user}/.postgresql/default.key sslrootcert=/home/{user}/.postgresql/default_root.crt") in the Django python shell, connection can be established. Also, openssl verify -CAfile default_root.crt default.crt shows default.crt: OK. Any help will be greatly appreciated. Thanks …