Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Cannot start nginx due to false configuration
I am deploying my django project called "converter" on my ubuntu machine and I am following this tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html I have created a configuration file, which is called converter_nginx.conf and I have put it on the folder /etc/nginx/sites-available. This is the content of my configuration file: # converter_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///home/andrea/File-format-converter/converter/converter.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 1myIPaddress.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/andrea/File-format-converter/converter/uwsgi_params; # the uwsgi_params file you installed } } and symlinked this file as indicated on the tutorial with this command sudo ln -s ~/home/andrea/File-format-converter/converter/converter_nginx.conf /etc/nginx/sites-enabled/. Despite that when I start nginx I get this error: [....] Starting nginx (via systemctl): nginx.serviceJob for nginx.service failed because the control process exited with error code. See "systemctl … -
Django Admin Site two model combine into 1 model using foreignkey
I have this table StudentProfile and table StudentEnrollmentRecord, I just want to add an column before the Student User just like the picture below, this is my code in model.py class StudentProfile(models.Model): LRN = models.CharField(max_length=500,null=True) Firstname = models.CharField(max_length=500,null=True,blank=True) Middle_Initial = models.CharField(max_length=500,null=True,blank=True) Lastname = models.CharField(max_length=500,null=True,blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', 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) and this is my code in admin.py class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): list_display = ('Student_Users', 'School_Year', 'Courses', 'Section', 'Payment_Type', 'Education_Levels') ordering = ('Education_Levels',) list_filter = ('Education_Levels','Section','Student_Users') -
Javascript show more in table
I need to show another tbody of table on Click. I have following table which is in foreach so there will be multiple buttons.: <table class="table" id="call-table"> <tr> <th>Show more buttons</th> </tr> <tbody> {% for global in globals %} <tr> <td class="show-more-button">Show more</td> <tr> <tbody class="show-more"> <tr> <th scope="col">Data</th> <th scope="col">Value</th> </tr> {% for data in dataset %} <tr> <td>Some data....</td> <td>A value..</td> </tr> {% endfor %} </tbody> {% endfor %} </tbody> I'm using python with DjangoFramework. And that's the script i came up with. But it only works for changing the 's text but doesn't show the tbody. <script> $(document).on("click", ".show-more-button", function() { if ($(this).text() == "Show more") { $(this).text("Show less"); $(this).parent().children(".show-more").style.display = "block"; } else { $(this).text("Show more"); $(this).parent().children(".show-more").style.display = "block"; } }); </script> and in CSS: .show-more { display: none; } What error do i have in my script? -
Python Blog Django Vs WordPress
Are there any developers that are running Django and using it as a blog over WordPress? I would like to ask if you have found it to be more resistant compared to the normal attacks they direct at WordPress? I am already building my backend with Django and I wonder if I did integrate the blog part to the backend, including front-end would I at least get less attacks? What are your thoughts? -
AttributeError when running a flask app in flask shell
I have finished a flask app. When I run it by python run.py, the app can work perfectly. But when I want to open flask shell by flask shell or even just flask, it tell me: Traceback (most recent call last): File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 556, in list_commands rv.update(info.load_app().cli.list_commands(ctx)) File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 388, in load_app app = locate_app(self, import_name, name) File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 257, in locate_app return find_best_app(script_info, module) File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 83, in find_best_app app = call_factory(script_info, app_factory) File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 117, in call_factory return app_factory(script_info) File "C:\Users\zkhp\Desktop\flask-bigger-master\backend\startup.py", line 41, in create_app app.config['SECRET_KEY'] = config.get('secret', '!secret!') AttributeError: 'ScriptInfo' object has no attribute 'get' The last sentence is here: def create_app(config): app = Flask( __name__, template_folder=template_folder, static_folder=static_folder ) app.config['SECRET_KEY'] = config.get('secret', '!secret!') The config is a dictionary, which is given by: def start_server(run_cfg=None, is_deploy=False): config = { 'use_cdn': False, 'debug': run_cfg.get('debug', False), 'secret': md5('!secret!'), 'url_prefix': None, 'debugtoolbar': True } app = create_app(config) I am confused with how the dictionary config is transformed to be a ScriptInfo? And what should I do to solve the problem? Thanks for your patient reading! -
How to calculate row value when base on previous row and current (django and postgres)?
I am looking to create row balance where: balance = (balance from previous date) + inflows - outflows There are some answers in SQL (LAG() function most likely) but have a problem how to implement it in Django ORM... Kindly ask for help... Best of luck Artur ''' class Account (models.Model): date = models.DateField(primary_key=True) inflows = models.FileField(null = True, max_length=100) outflows = models.FileField(null = True, max_length=100)''' -
In django, Is there a way to restrict user access to a url and all its children urls?
I am writing a simple Django application. I have an index page and accounts section, the account section can only be seen if the user is logged in. The problem is, that account section have many 'child' urls, like /accounts, /accounts/create, /accounts/update, /accounts/home etc etc. Currently, i am using login_required decorator and some other tests, but the code looks messy when i write the mixins and decorators on every view. Is there a simple way to block a url and all its children for a user? urlpatterns = [ path('',views.index_view,name="index"), url(r'^login/$', auth_views.LoginView.as_view(template_name='login.html' ,form_class=forms.AuthenticationForm), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), path('accounts/',views.SellerRegister.as_view(),name="register_seller"), path('accounts/address_create/',views.address_create,name="address_create"), path('accounts/register_buyer/',views.register_buyer,name="register_buyer"), ] -
sessionid missing and session_key=None
For my view, how come I am seeing session_key = None ? @csrf_exempt @api_view(['GET']) def shuffle(request): if request.method == 'GET': request.session['selected'] = [] request.session['words'] = [] response = Response(data={'dice': 2}, status=status.HTTP_200_OK) else: response = Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) return response I thought django would take care of generating everything sessions related as soon as I start modifying the sessions dictionary. In my settings.py I have SESSION_SAVE_EVERY_REQUEST = True as well. Going to check the developer tools, I also don't see the sessionid in my cookies -
Django: How to store in the database a list of dates and the songs someone listen that day?
Imagine I have 2 models Song and Person: class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Song(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name And I want to create a field inside the Person model to store a list of the dates this person listens to music and what songs they listen to. 2019-10-2 -> (Song 3, Song 25, Song 50) 2019-10-3 -> (Song 4, Song 5, Song 12) 2019-10-7 -> (Song 77, Song 22, Song 11) The ManyToMany field seems to work for linking to one or multiple instances of another model but doesn't seem to be useful for this case. Is there any type of field could I use? Or is there any other way to store all that information? The only other way I can think of is creating a model like this and have a table with all the songs that everyone has listened to and link them to each user: class Song(models.Model): person = models.OneToOneField(Person) date = models.DateField() songs = models.ManyToManyField(Song) I'm pretty new to databases and django so im not really sure which is the proper way of storing this kind of information. Under the person's profile or in a different table? … -
Python 3.7 AttributeError: 'str' object has no attribute 'has'
When i m trying to use this below code-> if not isinstance(math, basestring): math = latex(math) return '{}'.format(math) i want to check object is str or not -> i m using python 3.7.3 , pip 19.3.1 , django 2.2 -> So that i used 'str' instead of 'basestring' ,, then script will generating : str' object has no attribute 'get' error Now i m using this code def format_math_display(self, math): try: if not isinstance(math, basestring): math = latex(math) return '{} '.format(math) except Exception: pass AttributeError at / 'str' object has no attribute 'has' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 2.2.6 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'has' Python Executable: C:\Users\Vasundhara\Envs\calculate\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\wamp64\www\Python3Django2\Calculate', 'C:\Users\Vasundhara\Envs\calculate\Scripts\python37.zip', 'C:\Users\Vasundhara\Envs\calculate\DLLs', 'C:\Users\Vasundhara\Envs\calculate\lib', 'C:\Users\Vasundhara\Envs\calculate\Scripts', 'c:\users\vasundhara\appdata\local\programs\python\python37\Lib', 'c:\users\vasundhara\appdata\local\programs\python\python37\DLLs', 'C:\Users\Vasundhara\Envs\calculate', 'C:\Users\Vasundhara\Envs\calculate\lib\site-packages'] Server time: Sat, 26 Oct 2019 04:08:58 +0000