Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling django query sets when user needs them
I have been going back and forward with ideas doing this and none of them has worked so I'm gonna ask for ideas. I have model called "List" that users can create for example "Sleep" Then they have input where they select one of their lists and can add value for example 8. Good sleep! After that user sees a graph based on the data that he/(she has entered. All that is already working but I cannot seem to find a way to get data organized. I'm trying to do it so list "sleep" calls all it's values to the graph and then other list lets say "money" shows all its money values. I am using chart.js to draw the graphs and I dont care if they are all at the same time on the screen or if one by one but for somereason I cannot call these querysets properly. Only way it works is if I use .all() and that wont work since I have multiple users. Models: class List(models.Model): name = models.CharField(max_length=100, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') def __str__(self): return self.name class Meta: unique_together = ['name', 'user'] class DataItem(models.Model): data = models.IntegerField(default=0) list = models.ForeignKey(List, on_delete=models.CASCADE, related_name='data_items')r … -
Ubuntu supervisor import python modules error
Im using supervisor to run the django websocket in system startup . When I start the supervisor it will raise ModuleNotFoundError: No module named 'django' in the log file . Here is supervisor conf: [fcgi-program:myProject] environment=HOME="/home/ubuntu/envFiles/myProject/bin" # TCP socket used by Nginx backend upstream socket=tcp://0.0.0.0:8000 directory=/home/ubuntu/projects/myProject command=daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers myProject.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=4 process_name=asgi%(process_num)d autostart=true autorestart=true stdout_logfile=/home/ubuntu/logs/project.log redirect_stderr=true when i try to restart the supervisor by supervisorctl restart all , it has import module error again. Error log : ModuleNotFoundError: No module named 'django' I think it uses system python path But i defined environment in config file so supervisor must use there environment . whats the problem ? How can i set my django environment files in supervisor conf ? -
How to handle multiple actions in Django-Template
I have created a web app in which page which consist of choose file input and Now I need to preprocess the data with one button and that preprocessed data should be used for next button called forecast to show the result in that page.Is it possible with Django. Does it compulsory to take any action in page with url changes in django? -
Merge Date Time in Django ORM
I was trying to combine date and time. For that i was using datetime.combine. But it is giving AttributeError module 'datetime' has no attribute 'combine' TimesheetEntry.objects.filter( timesheet_users = user_id ).order_by( '-id' ).annotate( timesheet_clock_in=datetime.combine('timesheet_clock_in_date', 'timesheet_clock_in_time') ).annotate( timesheet_clock_out=datetime.combine('timesheet_clock_out_date', 'timesheet_clock_out_time') ).values_list( 'timesheet_clock_in', 'timesheet_clock_out', 'timesheet_jobs', 'timesheet_note', 'timesheet_clock_in_by' ) -
How to connect to OracleDB from Django on GAE Standard Environment
cx_Oracle library is not available on the GAE Standard Environment (?). How to include that in my Django/Angular app so that it can access the OracleDB? Or are there any other libraries/ ways to do that? I have the connection details like name,SID,password,port, host etc. for the database. After setting up the database in my Django settings.py by giving "engine" as "django.db.backends.oracle", I get the following error; django/db/backends/oracle/base.py", line 54, in <module> raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e) ImproperlyConfigured: Error loading cx_Oracle module: No module named cx_Oracle Any help will be appreciated. -
DRF ManualSchema: how to specify headers as a location of the field?
My view requires that request has a specific header. I would like to add this information to the ManualSchema that I create to describe the endpoint in order to have endpoint description in DRF auto-generated docs (http://my-site/docs/). Unfortunately I was unable to find the example in documentation or source code of coreapi or DRF documentation. Relevant part of my schema looks like in snippet below. I don't know what to type to location parameter. import coreapi import coreschema from rest_framework.schemas import ManualSchema MY_SCHEMA = ManualSchema( fields=[ 'Custom-Header', required=True, location='headers', # How to specify that this have to be in headers?! schema=coreschema.String() ] ) -
Passing context to a Response and using it in a view
I am working on a web app and I want to use HttpResponse or HttpResponseRedirect instead of render. But I dont know hoe to pass context in response as it does not have context parameter like render. And also how to use the passed context in the url or view ? Here is my view: @login_required def view_task_description(request): if request.method == 'POST': task_description = GetTaskDescription(data=request.POST, user=request.user) if task_description.is_valid(): obj = GetTaskDescription.get_task_description(task_description) return render(request, 'todoapp/task_desc.html', context={'description': obj[0].description}) return render(request, 'todoapp/select_task_description.html', context={'view_tasks': GetTaskDescription(user=request.user)}) I want to use Redirect or ResponseRedirect with the context instead of the render that I am returning if my form is valid. Basically render still shows the response as a POST method and I want the response to be a GET. How can I do so ? Thanks. -
To define Django models. To define Django query. So how sent result of query on fron-end?
I'm a new in Django. I have to create a part of project witch will create a report from some relations tables. I think there are 3 general stages: 1) define a model; 2) create view and query set; 3) create api for results of querys. Ok, that my models.py: class Renters(models.Model): id = models.AutoField(primary_key=True) org_prav_form = models.ForeignKey(Pravform, models.DO_NOTHING, blank=True, null=True) inn = models.CharField('ИНН',max_length=100, blank=True, null=True) account_name = models.CharField(max_length=100, blank=True, null=True) #для регистрации class Meta: managed = True verbose_name = 'rent' verbose_name_plural = 'renters' class Agreement(models.Model): id = models.AutoField(primary_key=True) renters_id = models.ForeignKey(Renters, on_delete=models.DO_NOTHING, verbose_name='рентер') date = models.DateField(verbose_name='dates') organ = models.CharField(max_length=80, help_text ='name_org') class Meta: verbose_name = 'projects' verbose_name_plural = 'projects' This classes have views, serializers,api. So how to get api for result of request? from django.db import models from renter.models import Renters, Agreement areport = Renters.objects.get() return areport -
Url parameter in Template - ID - Django
path('clock/view/<user_id>', views.ClockInOutViewListView.as_view(), name='admin_timesheet_clock_in_out_view'), I am passing user_id in url and looks like this - http://localhost:8000/timesheet/clock/view/13 I want that user_id in my template to reuse that user_id Example - 13. I was trying to {{user_id}} in my template but it did not got any value How can i get that 13 value in my template which is passed in my url class ClockInOutViewListView(LoginRequiredMixin, generic.TemplateView): template_name = 'clock/clock-view.html' def get_context_data(self, user_id, **kwargs): context = super(ClockInOutViewListView, self).get_context_data(**kwargs) try: context['views'] = TimesheetEntry.objects.filter( timesheet_users = user_id, ).order_by('-id') except: pass return context -
Django: save a list of model instances in a session after Ajax request
I have a product list page in which each product has a associated button (the button name is equal to the product pk). If I click a certain button then an Ajax request is carried out window.onload = function () { $("button").click(function () { var idButton = $(this).attr('id'); if (idButton.startsWith("addaftersearch")) { var button = document.getElementById(idButton); var pk = button.name; $.ajax({ url: 'list/add/', type: 'POST', dataType: 'json', headers: { "X-CSRFToken": $("input[name=csrfmiddlewaretoken]").val(), }, data: {'pk': pk}, }); } }); } Fortunately the Ajax request works and I am able to call the corresponding view that is: def add_item_to_session(request): if request.method == 'POST': print("I CAN ENTER HERE") product = Product.objects.get(pk=request.POST['pk']) serializer = ProductSerializer(product) if 'addedProductList' in request.session: temp_var = request.session['addedProductList'] temp_var.append(serializer.data) request.session['addedProductList'] = temp_var else: request.session['addedProductList'] = serializer.data return JsonResponse({'OK': 'ok'}) In few words, in this view I am doing a query in order to get the model instance that has the corresponding pk and after serializing it I am trying to save it in a session variable Now, the issue is: How can I save model instances in the session? I want to store as many products as the user times clicks Add button, but I am getting the error AttributeError: 'dict' … -
Slack interactive message: POST response is not in json format
@csrf_exempt def slack(request): print("Testing slack") if request.method == 'POST': print('request', str(request.body)) webhook_url = 'xxxxxxxx' text = "Would you recommend it to customers?" request = unquote(unquote(request.body.decode(encoding='ascii'))) print('url', request) slack_data = { "attachments": [ { "fallback": "Would you recommend it to customers?", "title": request, "callback_id": "comic_1234_xyz", "color": "#3AA3E3", "attachment_type": "default", "actions": [ { "name": "recommend", "text": "Recommend", "type": "button", "value": "recommended" } ], } ] } test = slack_data print('slack_data', type(slack_data)) response = requests.post( webhook_url, data=json.dumps(test), headers={'Content-Type': 'application/json'} ) return HttpResponse("New comic book alert!") In this str(request.body) I am getting output like: b'payload=%7B%22type%22%3A%22 interactive message%22%2C% So I encoded it using unquote(unquote(request.body.decode(encoding='ascii'))) and I am able to get the payload in this format: payload={ "here I got all details of POST message" } How do I parse this in Json ? -
Get ForeignKey Model dynamically in Django 2
Currently I'm trying do determine the Model behind a ForeignKey dynamically. For example I have: class Calendar(models.Model): date = models.DateField() shift= models.ForeignKey(Workshift, on_delete=models.CASCADE, null=True, blank=True) class Workshift(models.Model): shift = models.CharField(max_length=20) Now I want to do something like Calendar._meta.get_foreign_key_models() (which of cause doesn't exist) and receive the Workshift Model. I already tried the model._meta.get_fields() method, but this only tells me, that shift is a ForeignKey, not which Model stands behind it. Is this possible in any way? -
Python/Djngo Parse JSON from subprocess.Popen and save to Database
im currently working on a platform that also supports crypto-payments and the client wants a cold storage to protected the coins from hackers etc. therefor i'm currently building some kind of wrapper around the famous electrum BTC wallet -> https://electrum.org/#documentation and use it only with a imported public key, that means that only coins can be received but not get send... anyways, i now want to save the return i get in JSON format to the database but i don't know how to properly parse the vaules from subprocesses.Popen call and save it to the DB field :( . all this is done in a celery job. tasks.py def check_btc_deposit(): users = User.objects.all() try: for user in users: if user.acc_btc_addr: check_addr = subprocess.Popen(['electrum' + ' ' + 'getaddressbalance' + ' ' + user.acc_btc_addr], shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() print(check_addr) else: print (str ('No BTC Address allocated by User ->') + ' ' + str(user)) except Exception as e: print(e) Thanks and kind regards -
How to use multiple fields from one model to another as foreignkey?
I am trying to use multiple fields from my Dog model as choices in MyDog model. When i create a new MyDog instance, it both shows what is in Dog.name. How can i make MyDog.breed see whats in Dog.breed? class Dog(models.Model): name = models.CharField(max_length=10) breed = models.CharField(max_length=10,unique=True) def __str__(self): return self.name class MyDog(models.Model): name=models.ForeignKey(Dog,related_name='mydogname',on_delete=models.CASCADE) breed = models.ForeignKey(Dog,related_name='mydogbreed',on_delete=models.CASCADE,to_field='breed',db_column='breed') -
redirect to different pages in django after login
When i click on the sell product link from homepage it redirects to the login page and after login done it redirects to the homepage and i have to again click on the sell product link to fill the form.I want to redirect to the sell_product page after login instead of homepage.How can i do that ?? How can i redirect to the different pages from one signin url. urls.py path('signin/user/',views.users_signin,name='users_signin'), path('sell/product/',views.sell_product,name='sell_product'), views.py def users_signin(request): if request.method == "POST": form = UserSigninForm(request.POST) username = form['username'].value() password = form['password'].value() user = authenticate(username=username,password=password) login(request,user) return redirect('shop:home') else: form = UserSigninForm() return render(request,'shop/users_signin.html',{'form':form}) def sell_product(request): if request.user.is_authenticated: if request.method == "POST": form = SellProductForm(request.POST,request.FILES) if form.is_valid(): myproduct = form.save(commit=False) myproduct.seller = request.user myproduct.save() messages.success(request,'Your Product has been posted successfully.!!') return redirect("shop:home") else: form = SellProductForm() return render(request,'shop/sell_product.html',{'form':form}) else: messages.error(request,'please login first') return redirect('shop:users_signin') sell_product.html {% extends "shop/base.html" %} {% load bootstrap4 %} <title>{% block title %}Sell a Product{% endblock %}</title> {% block content %} <div class="container"> <div class="row"> <div class="col-lg-6 offset-lg-3 col-sm-10 offset-sm-1"> <div class="card my-5"> <div class="card-header text-center"> Sell Your Product </div> <div class="card-body"> <form action="{% url 'shop:sell_product' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-success … -
javascript nested collapse and expand not working on django template
I'm fetching records from nested dictionaries on my django template. Without the js code, I can see the hierarchical representation of my data properly on the form. But when I add the js script to the template, I'm not able expand the records if my sub folder has only one record. When I add multiple records in my sub folder, expand and collapse works fine. Facing the issue only in the case of one record in each sub folder. I tried to replicate this in a fiddle. It works fine in the fiddle but not on my form. Can someone tell me what is the problem? Template code : <div align='left'> {% for key, values in years_dict.items %} <ul class="archive_0"> <li class="level_0"><b>{{key}}</b> <ul class="archive_2"> {% for x,y in values.items %} <li class="level_1 "><b>{{x}}</b> {% for each in y %} <ul class="archive_3"> {% for file in folders %} {% if file.File1.url == each %} <li class="level_2"><a href="{{ each }}" target="_blank">{{ file.Filename }}</a></li> {% endif %} {% endfor %} </ul> {% endfor %} </li> {% endfor %} </ul> </li> </ul> {% endfor %} and the js script $( '.level_0,.level_1,.level_2').click(function(e) { e.stopPropagation(); $(this).children('ul').slideToggle(); }); The fiddle in which I tried to replicate this … -
Cannot configure youtube plugin in django-ckeditor
I have done the following in my settings and model: settings.py CKEDITOR_CONFIGS = { 'special': { 'toolbar': 'Special', 'toolbar_Special': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ], 'extraPlugins': 'youtube', } } models.py class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) post = RichTextUploadingField(blank=True, null=True, config_name='special', external_plugin_resources=[( 'youtube', '/static/ckeditor/ckeditor/plugins/youtube_2.1.13/youtube/', 'plugin.js', )], ) date = models.DateTimeField(auto_now_add=True) I want to add the youtube plugin in my ckeditor. I have already downloaded it from https://ckeditor.com/cke4/addon/youtube. Can any one find out the problem in my code? Thank you -
Docker and postgresql: How to Manage Data
I am working on a Django project. I have arhclinux host used as development server with postgresql running. I have created a database in postgresql. sudo su - postgres (get into the shell session for the postgres user) [postgres]$ psql (Log into a Postgres session by typing:) psql (10.3) Type "help" for help. postgres=# postgres=# CREATE DATABASE myproject; postgres=# CREATE USER myprojectuser WITH PASSWORD 'password'; postgres=# GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser; In my django app changed settings.py for accessing postgresql DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } Then in django i do the migrations and create Super user: # do migrations cd ~/myproject python manage.py makemigrations python manage.py migrate # create super user python manage.py createsuperuser Now i want to user docker for production: What is the best way to manage my postgresql database: Option 1: (mount /var/lib/postgresql inside postgres container) Assuming i am using an aws ubuntu host server, then I install postgresql in it, create user [myproject] and database [myproject] and then restore my database from backup dump from my developement server psql dbname < dumpfile Now in the dockercompose.yml dbpostgres: image: postgres … -
ValueError - In Delete View Django
I am getting ValueError while deleting a user Error - ValueError at /employee/delete/31/ The view apps.employee.views.EmployeeDeleteView didn't return an HttpResponse object. It returned None instead. class EmployeeDeleteView(LoginRequiredMixin, generic.DeleteView): model = User template_name = 'employee/employee_confirm_delete.html' context_object_name='employees' def get(self, request, *args, **kwargs): # Tab Opts Checking if request.user.userprofile.user_company.company_tab_opts: return redirect('admin_employee') def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.userprofile.soft_delete() messages.success(request, 'Employee Deleted Successfully.') return HttpResponseRedirect(reverse('admin_employee')) This is the traceback of the error Internal Server Error: /employee/delete/31/ Traceback (most recent call last): File "/home/.virtualenvs/apollo_django-njoxc1BQ/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/.virtualenvs/apollo_django-njoxc1BQ/lib/python3.5/site-packages/django/core/handlers/base.py", line 137, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view apps.employee.views.EmployeeDeleteView didn't return an HttpResponse object. It returned None instead. -
Google login using react js and Django rest frame work and socio auth
I am using trying to integrate a google login to my website. I am using react js as my front end and django at backend. I have got the access token from google, and also i have registered a application in django admin in Django oauth tool kit. Can some one explain what should i do now after this? -
Reusing Django models with different data
I am a new programmer in Django. I am trying to create a game using Django. The game has some model parameters. I have created a model to store all the model parameters. Each time a user wants to start a game the game parameters get automatically attached to the game model. However I want to ensure that game parameters which are attached to a specific game should be editable without effecting the generic game parameters. For example there are user inputs (Price and Quantity) and i have defined a generic upper and lower limits for both the quantities for each round of the game. However when the user plays the game, i want to dynamically change the limits for the specific user without effective the generic upper and lower limits I have set. Can anyone help me on how to achieve this? -
Django: What is the smartest way connect models for two types of clients (individual and company) to the address model?
I am working on developing a CRM like application using Django and I've stumbled upon a problem. The company which will use the app has private individuals as clients but also other companies. As they have different fields I created two separate models: class PersonAccount(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100, null=False) personal_id_number = models.CharField(max_length=50, unique=True, null=False) document_series = models.CharField(max_length=50) document_number = models.CharField(max_length=50, null=False) document_emission_date = models.DateField(null=True) document_expiration_date = models.DateField(null=True) birth_date = models.DateField(null=True) sex = models.ForeignKey(Sex, on_delete=models.CASCADE, null=False) workplace = models.CharField(max_length=100) nationality = models.ForeignKey(Geography, on_delete=models.CASCADE) occupation = models.CharField(max_length=100) observations = models.CharField(max_length=500) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) def __str__(self): return "Person account: " + self.last_name + " " + self.first_name class CompanyAccount(models.Model): company_name = models.CharField(max_length=100, null=False) chamber_of_commerce_reg_number = models.CharField(max_length=50, unique=True, null=False) company_unique_id_number = models.CharField(max_length=50, unique=True, null=False) company_type = models.ForeignKey(CompanyType, on_delete=models.CASCADE) company_nationality = models.ForeignKey(Geography, on_delete=models.CASCADE) company_activity = models.CharField(max_length=100) company_representative = models.ForeignKey(PersonAccount, on_delete=models.CASCADE) observations = models.CharField(max_length=500) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) def __str__(self): return "Commpany account: " + self.last_name + " " + self.first_name I want to connect them both to an address model: class AccountAddress(models.Model): address_type = models.ForeignKey(AddressType, on_delete=models.CASCADE, null=False) street = models.CharField(max_length=100) street_number = models.CharField(max_length=100) buliding = models.CharField(max_length=100) entrance = models.CharField(max_length=100) floor = models.CharField(max_length=100) … -
Django 500 server error using nginx and gunicorn
django website is working fine on localhost but when hosted on server using nginx and gunicorn, some APIs are throwing 500 server error. This problem is with some APIs and rest of the APIs are working well. Please help me what should I do? -
I cannot log into the Django admin page with valid username and password, it returns {% csrf_token %} forbidden 404 error message
I cannot log into the django admin page with valid username and password. I created a superuser via the "python manage.py createsuperuser" command, then entered details asked, but then when I go to the django admin page and enter the details I created, it gives an error message "Forbidden 403 csrf missing or incorrect". I tried to update my settings.py file by placing "django.middleware.csrf.CsrfViewMiddleWare" on top MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] but it still doesn't work. I am running my project on a localhost server and keeps on showing me this: System check identified no issues (0 silenced). March 13, 2019 - 11:38:30 Django version 2.1.7, using settings 'aps_site.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [13/Mar/2019 11:38:51] "GET / HTTP/1.1" 200 1944 [13/Mar/2019 11:38:51] "GET / HTTP/1.1" 200 1944 [13/Mar/2019 11:38:54] "GET /login/ HTTP/1.1" 200 2470 [13/Mar/2019 11:38:54] "GET /login/ HTTP/1.1" 200 2470 Forbidden (CSRF token missing or incorrect.): /login/ [13/Mar/2019 11:38:56] "POST /login/ HTTP/1.1" 403 2513 [13/Mar/2019 11:38:56] "GET /login/ HTTP/1.1" 200 2470 I again tried placing the {% csrf_token %} inside my form but still gives an error. Please assist and thank you in advance. -
Celery RuntimeError: populate() isn't reentrant
I am able to start worker from CLI , but not from supervisor. I tried to run it under different users and it worked on some and not on the others. It always worked as root. So I thought it may be related to some environmental variables or permissions. But lol Project location is under /opt/data/project and it is set as chown apache:apache -R /opt/data/project supervisor 3.4.4 django 1.11.3 celery 4.2.1 I did pretty much standard configuration cat /opt/project/CORE/CORE/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CORE.settings') app = Celery('CORE') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) cat /opt/project/CORE/CORE/init.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) cat …