Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add one model objects to another model’s ModelForm template with many to one relationship in Django?
I am trying to create a Hospital Management System in which have Two ModelForms, one ModelForm creates Patient Object, And another form of model two is used to admit that Patient which means it uses Patient Objects in New Form Template with new fields and creates new ID Which have model one id(patient ID) and model two id(IPD ID )as well and model two is linked with model one with Patient Id,one patient can have multiple Ipd id -
How to implement a shared variable for the entire django project?
I am writing a django server for a card game. The game begins when 2 players press the play button. To do this, in views.py I have the variable "turn", in which the id of the player who wants to play is recorded. As soon as 2 players appear in the "turn", an instance of the class with the game is created for them and is written into the dictionary, for example: games_now = {"id1": , "id2": }. Thus, 2 players use one class and manipulate common variables in it. So far, I run django as "manage.py runserver 0.0.0.0:80" on the server 1 core and do not notice any problems. But in production I have to use apache or nginx. What happens if I run a django-project on nginx on a multi-core VPS? Will all players then have access to the "turn" and "games_now" variables? How can I implement the functionality of the game on a multi-core processor to avoid conflicts? The game is implemented in the bot on vk.com I receive requests from vk.com in the form {"from_id": from_id (int), "objects": {"message": message (text)}} and within 3 seconds I should return the answer 'ok' to the server. Therefore, everything … -
Django Models, on delete set pk
This is my models: class Customer(models.Model): nome = models.CharField(max_length=40) indirizzo = models.CharField(max_length=40) class Appo(models.Model): appo = models.CharField(max_length=40) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, default=1,related_name='appocli') now, if I delete a Customer I need SQL set in Appo models a specific PK for customer Foreign Key. For example 1. Something like: on delete set 1 Please help -
I forget on which virtual environment i was working on?
I have several virtual environment in my computer and i have forget the name of the virtual environment i was working on and i don't know how can i know the name of the environment. Can someone help me please -
How to create a seperate table for the user when they registered on site
I have to create a site where every user store's there data and each user get the isolated storage for which i have to allot a particular table to each user, as the size of data stored by user is big enough too and I doesn't now how to do it in django. Please suggest me the same. -
How to upload a file from django view using filepath
I have to upload a file from django views using the file path from the local system. I'm using models.create method to save the filepath. But the image is not getting uploaded into the media directory. I have tried the Content and File from django core.utils but it deos not work def createevent(request): file_path = os.path.join(settings.FILES_DIR) # Getting the directory with files f = [] for (dirpath, dirnames, filenames) in walk(file_path): f.extend(filenames) break f.remove(".DS_Store") img = random.choice(f) # Select a random file pa = os.path.abspath(img) # absolute file path # pa = (img,File(pa)) response = File(pa) print(pa) loc = "School Ground" if request.method == 'POST': get_dateof = request.POST.get('dateof') get_nameof = request.POST.get('nameof') get_descof = request.POST.get('descof') new_report = Event.objects.create( name=get_nameof, description=get_descof, location=loc, timeoftheevent=get_dateof, user=request.user, image= pa ) #creating a db record return HttpResponse('') -
scope in django_channels searches for an argument on all pages from URLRouter
I need to support multiple-page socket connection, URLRouter is like this: URLRouter([ path('device/<device_name>',IndicatorConsumer), path('add',IndicatorConsumer), path('', IndicatorConsumer) ]) consumers.py is async def websocket_connect(self,event): print('connection succefull ', event) await self.send({ 'type': 'websocket.accept' }) self.device_id = self.get_device_id(self.scope['url_route']['kwargs']['device_name']) I need to get device_name via scope to send it to another function. But for some reason the scope searches for this on all the pages that are in the URLRouter, and so, for example, in the /add socket immediately closes because it can not find there device_name Everything works fine on the device pages, others get an error: Exception inside application: 'device_name' -
Insert multiple values with unique record in database in Django
I have a form in which user selects value from downtown and insert one value from text box. I have made a text-box such that user can enter multiple values by adding it. like in pic But when I submit form it saves only one record in database with value of last text box. Can anyone tell me how to save each value in database with unique record. my view:- class PerticularCreatView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model=Perticular success_message = " Perticulars Added successfully!" reverse_lazy('add-perticular') template_name = 'add-perticular' form_class = PerticularCreateForm # fields =[] def get_context_data(self, **kwargs): kwargs['perticulars'] = Perticular.objects.filter(is_del=0).order_by('-perticular_crt_date') return super(PerticularCreatView, self).get_context_data(**kwargs) def form_valid(self,form): form.instance.perticular_crt_by = self.request.user return super(PerticularCreatView, self).form_valid(form) -
Django website deploying to heroku. Application error
I'm trying to deploy my django website to heroku but I get an Application Error shown on the webpage. Looking at my logs using heroku logs --tail (what it tells me to do on webpage), I recieve an error 2019-07-27T06:14:34.046386+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=prremia.herokuapp.com request_id=20cd473d-50c2-43b6-892e-ce8f8981229d fwd="49.36.8.33" dyno= connect= service= status=503 bytes= protocol=https 2019-07-27T06:14:34.878053+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=prremia.herokuapp.com request_id=53c5e449-ba17-4e93-86f9-7b70eeb7e074 fwd="49.36.8.33" dyno= connect= service= status=503 bytes= protocol=https I followed the instructions from Django's docs. Django 2.2.3 Python 3.7.3 Heroku-18 My webpage: -
Django safe and striptags don't work properly
if don't have seo description,post.conten|trunnchars:160 show it. However, i have uniode and charset problem Turkish characters like " ş Ş İ I ö Ö ü Ü ç Ç " doesn't work properly the result is for Ö= &#214; ı= &#305; i added <meta charset="utf-8"> {% block description %}{% if post.seo_description %}{{post.seo_description|truncchar:160}}{% else %}{{ post.content|truncatechars:160 |safe|striptags}}{% endif %}{% endblock %} -
MultiValueDictKeyError when upload an Image using Django Test
Hi I am trying to make a test case to test my upload image API. But I think I am not returning something when I pass the files for request.FILES #models.py class Image(models.Model): name = models.CharField(max_length=200) imagefile = models.ImageField( null=True, blank=True, max_length=500, upload_to='temp/images/') def __str__(self): return self.name #views.py class ImagesView(APIView): def post(self, request): print("DATA!!!", request.data) print("FILE!!!", request.FILES) params = Image( imagefile=request.FILES['image']) params.save() print(params) return Response({"status": "ok"}) #test.py class CanalImagesApiTests(TestCase): fixtures = [] def test_post_image(self): c = Client() response = c.post('/admin/login/', {'username': 'admin', 'password': 'passwrd'}) filename = 'data/sample_image.jpg' name = 'sample_image.jpg' data = {"data": "passthis"} print(to_upload) with open(filename, 'rb') as f: c.post('/images/', data=data, files={"name": name, "image": f}, format='multipart') response = c.get('/images/') results = response.json() My request.FILES is empty: <MultiValueDict: {}> and my test gets an error: django.utils.datastructures.MultiValueDictKeyError: 'image' -
Getting unreachable error when making migration in django
I have Django conde all is running fine.But when i run py manage.py it is raising erron which i am not understanding. Operations to perform: Apply all migrations: admin, api, auth, contenttypes, sessions, social_django Running migrations: Applying api.0004_auto_20190726_1113...Traceback (most recent call last): File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near ")": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\migrations\operations\fields.py", line 150, in database_forwards schema_editor.remove_field(from_model, from_model._meta.get_field(self.name)) File "C:\Users\santhoshe.e\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 327, in remove_field self._remake_table(model, delete_field=field) File … -
User specific storage backends in Django
Use case: I want to develop a Django app that supports a collaborative workflow of multiple users. Users shall be invited to review files in an order defined by the uploading user. For this the file is uploaded to the app and users are invited. Multiple users belong to one organization. There are several organization. Files uploaded by an organization user to the app shall be stored in a space owned/controlled by the organization (“bring your own storage”), e.g an existing GoogleDrive or Dropbox. The storage target is configured by the first user of a new organization (target url, oauth token). Question: is it possible to switch the storage backend of Django based on information related to the user uploading a new file, e.g. the users organization? -
How to apply zoom effect on mouseover for all the images passed in a single Image tag using jquery?
I am trying to zoom images on mouseover but zoom is applied only on first image . I am using given code in my django templates to zoom images . {% for image in images_obj %} <img class="drift-demo-trigger" data-zoom="{% static '/images/catalog/products/thumbnail/' %}{{image}}" src="{% static '/images/catalog/products/thumbnail/' %}{{image}}" alt="IMG-PRODUCT" style="width:99%;border:1px solid #ccc;"> <div class="detail"> <section> </section> </div> {% endfor %} new Drift(document.querySelector('.drift-demo-trigger'), { paneContainer: document.querySelector('.detail'), inlinePane: 900, inlineOffsetY: -85, containInline: true, hoverBoundingBox: true }); All images which are coming in loop should be zoomed but currently only the first image is able to zoom . -
Django migrate --fake-initial reports relation already exist
I am trying to import an existing database into my Django project, so I run python manage.py migrate --fake-initial, but I get this error: operations to perform: Apply all migrations: ExcursionsManagerApp, GeneralApp, InvoicesManagerApp, OperationsManagerApp, PaymentsManagerApp, RatesMan agerApp, ReportsManagerApp, ReservationsManagerApp, UsersManagerApp, admin, auth, authtoken, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... FAKED Applying auth.0001_initial... FAKED Applying contenttypes.0002_remove_content_type_name... OK Applying GeneralApp.0001_initial...Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/IntellibookWebProject/IntellibookWebVenv/lib/python3.6/site-packages/django/db/back ends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.ProgrammingError: relation "GeneralApp_airport" already exists Of course all the tables already exist in the database, that is the reason why I use --fake-initial, that is supposed to fake the creation of database objects. Why is migrate attempting to create the table GeneralApp__airport instead of faking it? -
Unable to import module 'handler': No module named 'werkzeug'
I suddenly started getting this error on a Django + AWS lambda setup with zappa. I'm using ubuntu 18.04 image on bitbucket pipelines to trigger the deployment. Unable to import module 'handler': No module named 'werkzeug' It was working fine for python3.6 on zappa==0.42.2 until the last deployment in 25-July-2019. I thought it was due to some code changes on the app that's causing it (even though the code changes are not related to pip modules - just some updates on the application's codebase) but even reverting to previous deployments are throwing this error now. My zappa config has a slim_handler: true { "staging": { "project_name": "myapp", "slim_handler": true, "runtime": "python3.6", "log_level": "WARNING", "timeout_seconds": 300 } } I have tried some suggested solutions in Zappa's GitHub issues but without success. https://github.com/Miserlou/Zappa/issues/64 https://github.com/Miserlou/Zappa/issues/1549 I've also tried some SO solutions from questions related to import issues in zappa and haven't been successful. I would highly appreciate any pointers for debugging or workarounds for this zappa issue in AWS lambda with python3.6. -
Why Supervisor can cause mysql sock problem?
I'm deploying my Django project on Debian system ,when I want to use supervisor to manage processes , I met some strange problem. Django:2.1 Python:3.5 Supervisor:3.3.1 Error message: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) The history is: At first I ran the Django by Gunicorn alone, it works , I can visit my website from outside. Then I use apt-get install supervisor to install it in order to manage the processes. Configuration Please see bottom. What I've tried : 1:cancel the celery and redis program in supervisor configuration No use 2:cancel the redis program and keep Django and celery inside , then run redis manually No use 3:Only run Django under superviosr Ok Why I'm so confused is Why it can caused mysql sock problem....? I searched out google for 3 days already... PS: if this error occurred , I can't use mysql anymore , like mysql -u root -p [program:NBAsite] directory = /home/allen/NBAsite/NBAsite command = /home/allen/NBAsite/env/bin/gunicorn NBAsite.wsgi:application -b 0.0.0.0:8000 autostart = true startsecs = 5 autorestart = true startretries = 3 user = allen redirect_stderr = true stdout_logfile_maxbytes = 20MB stdout_logfile_backups = 20 stdout_logfile = /home/allen/NBAsite/supervisor_log/allenbigbear.log [program:celery] directory = /home/allen/NBAsite/NBAsite command = /home/allen/NBAsite/env/bin/celery -A NBAsite … -
When do you have to add an app to Django's INSTALLED_APPS setting?
I'm getting back to Django now after just dabbling in it before, and I'm working my way through the Polls tutorial again. I'm confused as to how include('polls.urls') in the main URL configuration file knows about the Polls app, particularly where to find it, when we haven't defined it in the INSTALLED_APPS setting in settings.py. Does it just know to look one directory up from the settings file, for example? For the sake of argument, what if I decide I want to put it in a different place (not that I have any good reason to)? And taking this one step further, if it knows to look in that main project folder, why do we have to define any installed apps in the INSTALLED_APPS setting? I'm sure there's a good answer to all of this--just don't quite understand at the moment. Many thanks in advance for any guidance! -
How to do post-mortem debugging within Django's runserver?
I am currently debugging a Django project which results in an exception. I would like to enter the ipdb post-mortem debugger. I've tried invoking ipdb as a script (cf. https://docs.python.org/3/library/pdb.html), but this just enters me to the first line of code: > python -m ipdb manage.py runserver > /Users/kurtpeek/myproject/manage.py(2)<module>() 1 #!/usr/bin/env python ----> 2 import os 3 import sys ipdb> If I press c to continue, I just run into the error, with no possibility to drop into the debugger post-mortem. Presumably I could press n (next) until I get the error, but that would be quite cumbersome. Is there a way to run python manage.py runserver with post-mortem debugging? -
Login Page not coming up on clicking the link
I want the user icon on the right to go to login page. (icon shown in right side of the screenprint) Once I click it, url gets changed to /accounts/login/ but the page does not change. Urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url,include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), url(r'',include('blog.urls')), url(r'accounts/login/$',views.LoginView.as_view(template_name="registration/login.html"),name='login'), url(r'accounts/logout/$',views.LogoutView.as_view(),name='logout',kwargs={'next_page':'/'}), Base.html <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a href="{% url 'post_new' %}" >New Post</a></li> <li> <a href="{% url 'post_draft_list' %}" >Drafts</a></li> <li> <a href="{% url 'logout' %}" >Logout</a></li> <li> <a href="#">Welcome: {{user.username}}</a> </li> {% else %} <li> <a href="{% url 'login' %}" class="nav navbar-right"> <span class="glyphicon glyphicon-user"></span> </a> </li> {% endif %} </ul> Login.htm {% extends 'blog/base.html' %} {% block contents %} <div class="jumbotron"> <h2>Please Login:</h2> <h3>Check with site admin incase you're not a SuperUser </h3> {% if form.errors %} <p>Invalid Credentials. Please try again.</p> {% endif %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary" value="Login"> <input type="hidden" name="next" value="{{next}}"> </form> </div> {% endblock %} I'm using Django 2.1, Where am I missing? -
Django: "settings.DATABASES is improperly configured" upon migrate, but can access database through ORM
I'm having trouble migrating my database and creating authentication tables to my application's database for superusers, staff, etc. which has to be done by performing python manage.py migrate. I believe my problems are occuring because I'm using legacy databases hosted on a Microsoft SQL Server instance, but I'm not sure and I might just have some things set up wrong. I expect to connect to the database and add an admin/authentication table to an existing database ('authentication_database'), however I receive the following error message: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. It should be noted that I can access the client_database's ORM via interactive shell/custom management commands. I simply can not migrate the database. Here is my DATABASES setting in settings.py: DATABASES = { 'default': {}, 'auth_db': { 'NAME': 'authentication_database', 'HOST': 'host.ip.address.yo', 'PORT': '', 'ENGINE': 'sql_server.pyodbc', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', }, }, 'client_database': { 'NAME': 'client_database', 'HOST': 'host.ip.address.yo', 'PORT': '', 'ENGINE': 'sql_server.pyodbc', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', }, }, } # Database routers DATABASE_ROUTERS = ['app_name.dbrouter.ClientRouter', 'project_name.authrouter.AuthRouter'] DATABASE_CONNECTION_POOLING = False I can provide my auth routing code if that could help. -
How to make Django ORM query for summary results with multiple conditions and group by
I am trying to make one Django query for a summary result from single model with multiple conditions. I created this two queries I want one single query to get single group by result. Can any one help me. I am little new to Python/Django alertall = alert_master.objects.filter(orgcode_id='RMS01').values('alertbatchid','alertrmname').annotate(alertgen=Count('alertid')).order_by('alertbatchid','alertrmname') alertclose = alert_master.objects.filter(orgcode_id='RMS01',alertstatus='CLOSED').values('alertbatchid', 'alertrmname'). annotate(alertclose=Count('alertid')).order_by('alertbatchid','alertrmname') -
Images that fit the regexp `.?-ad[0-9].png` can not be loaded in any browser?
I had this weird problem of identical PNG images with different file names not being loaded. Problem persists both in Django development server and nginx serving the image files so I don't think it is specific to Django or nginx. I experimented with different file names and some work and some don't: 0-ad0.png # Doesn't work a-ad0.png # Doesn't work aaaaaa-ad0.png # Doesn't work 0-ae0.png # Works 0-bd0.png # Works 0-ada.png # Works a-ad.png # Works a-ad00.png # Works As far as I can tell, if the file name fits this regular expression, it is not loaded: .*-ad[0-9].png Did anyone encounter such a thing? What could be the reason for this? -
Where should I make a python-twitter API call in my Django/React webapp
I'm creating a full stack web app using react, react-redux, and Django-rest, and I need to make an API call using the python-twitter api, then display the data from this request in my react frontend. The flow of control will be a user enters their twitter username in the frontend, which needs to trigger an API call using this username in the Django backend. Then the data from this call needs to be fed back into the React frontend using redux. Where should I be making this API call in the Django backend? -
Upload and Display Image in Django Rest Framework via FileField or ImageField
I want to upload an image to my Django Rest API and click the link I get and then see the actual image (like any other image on the internet), this is so I can then display the image in my mobile app. This is my code: class Assignment(models.Model): name = models.CharField(max_length=100) file = models.FileField(blank=False, null=False) class Meta: verbose_name_plural = 'Assignments' def __str__(self): return "{name}".format(name=self.name) class AssignmentSerializer(serializers.ModelSerializer): class Meta: model = Assignment fields = ('id', 'name', 'image') class AssignmentView(viewsets.ModelViewSet): queryset = Assignment.objects.all() serializer_class = AssignmentSerializer router = routers.DefaultRouter() router.register('assignments', views.AssignmentView), urlpatterns = [ path('', include(router.urls)), ] urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('example.urls')), ] //Settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") When I click an image in the Rest API I get en error!