Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access other tables in the same database in Django
We're using two backends languages, JAVA and Python (Django), to handle different modules in the same project. As shown above, in the database, pl_**** tables work for the JAVA part and qa_**** tables work for my Django part. Right now, my Django part want to use the pl_user table, what should I do to access the data? Do I need add anything in the models.py? Or, do I need make some relationships between pl_user table and auth_user table? -
django call_command migrate seems to kill the process
I do this in my view.py import os import django from django.core import management def runmigrate(self, databasename): try: print('0') os.chdir(os.getcwd()) management.call_command('makemigrations') print('1') django.setup() management.call_command('migrate', app_label='client', database=databasename, interactive=False) print('2') return "success" except Exception as e: print(e.args[0]) return "failure" but when i call this method in the front end, the terminal shows that 0 No changes detected 1 Operations to perform: Apply all migrations: client Running migrations: Applying client.0001_initial... OK Performing system checks... The success label '2' never shows and No error messages are shown. it seems that the process is killed and every command after it will not be executed. -
Django edit creates new object
My update view creates a new object instead of updating the object. i pass in the primary key and also the instance but yet still creates a new object. views.py def tour_update(request, pk, template_name='tourguides/tour_form.html'): tour = Tourguide.objects.get(pk=pk) form = TourForm(request.POST or None, request.FILES or None, instance=tour) if form.is_valid(): form.save(force_update=True) return redirect('tour_list') return render(request, template_name, {'form':form}) urls.py path('tourguides/edit/<int:pk>', views.tour_update, name='tour_edit'), I have tried to add force_update true as you can see above but that also didnt fix the issue. -
Django 1.11 Access Media File 404 not found
my urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' when trying to access http://127.0.0.1:8000/media/python.pdf its result Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/python.pdf did i miss something?... -
Nginx redirect (non-www to www) not working with Certbot
I have a website running with a Python/Django/uWSGI/Nginx setup. I also use Certbot to enable https on my site. My redirects from non-www to www (e.g. "example.com" to "www.example.com") haven't been working even though I couldn't spot any deviations from the Nginx/Certbot documentation. Here is the relevant part of my sites-available Nginx code: server { listen 80; server_name example.com www.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myname/example; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/activities.sock; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; #managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; #managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot } I found a similar StackOverflow answer (Nginx: redirect non-www to www on https) but none of the solutions worked for me. I have SSL certificates for both example.com and www.example.com. I also tried creating a separate 443 ssl server block for example.com based on the comments in that answer but it didn't work either. My sites-available and sites-enabled code is the same. What am I doing wrong? -
does templates get cached in browser in django
return render(request, "my_template.html", {foo: bar}) Lets say we have a request made in django which renders my_template.html and the context of {foo: bar} now based on the user activity foo and bar change.Now lets say if a user has made his first request now django will return the template and the corresponding {foo: bar} based on user activity.lets say if the user had made a second request with different activity does my_template.html template will be sent from django server to browser or only the changed context is sent to the browser.Does the template gets cached in the browser. Case 1: If the template gets cached in browser if a code with some changes is deployed does it reflect in the clients browser.does this work in the way where md5 hash of both the templates is compared if they are not in sync then the template is downloaded from django server Case2 If The template is rendered every time for every request then does that mean the bandwidth usage is not optimistic. i read that in node and angular the javascript bundles is cached in clients browser and only data(context {foo:bar}) calls are made to server so the bandwidth usage is … -
django 2 - User and userprofile models, how to obtain all fields in a single query?
I've been looking for a solution but I'm not finding anything that sticks out. I've created a Profile model which is linked to the standard User model via one-to-one field which is working in admin. I want to pull all fields/data for both models into a single queryset. I'm trying to create a user editing form and I want to pull in all fields for User and Profile based on the current logged in user and display those fields which I will have a page to edit and save those fields. What are the best options to achieve this, simple is better. class Profile(models.Model): address = models.blablabla user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') def profile_edit(request): form = UserProfileForm(request.POST or None) instance = Profile.objects.all().filter(user__username=request.user).values # This is the place I need to create a single queryset. if request.method == "POST" and form.is_valid(): form = UserProfileForm(request.POST, instance=instance) user_form = form.save() print("POST event") else: form = UserProfileForm(instance=instance) print(form) return render(request, 'frontend/profile_edit.html', {'form': form}) I'm manually creating the forms in the template so I would like to have something like {{ form.username }} {{ form.profile.address }} or something like that. I'm likely doing things poorly, I'm new to django. -
Django forms interacting with each other
I have a django (2.0) application with a page that contains two separate forms that are not meant to interact with each other at all. However, I am getting some weird behavior. Pictured here, when I click on one of the labels on the bottom form, it triggers the checkbox for the corresponding (based on row, not name) element in the upper form (clicking "members" on the group form selected "Email" on the person form). This only goes one way--clicking anywhere on the top form never effects the bottom form. Checking the actual boxes of the bottom form do trigger the expected boxes that their labels correspond to. The html for this page is: <head> {% load static %} <title>LDAP - Search</title> <link rel="shortcut icon" href="{% static 'djangoWrapper/favicon.ico' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'ldap/style.css' %}"> </head> <body> <h1>Search</h1> <div class="search-form"> <h2>Search for Person</h2> <form action="{% url 'ldap:person_results' %}" method='post'> {% csrf_token %} <table> {{ personForm }} </table> <input type="submit" value="Search"> </form> </div> <div class="search-form"> <h2>Search for Group</h2> <form action="{% url 'ldap:group_results' %}" method='post'> {% csrf_token %} <table> {{ groupForm }} </table> <input type="submit" value="Search" /> </form> </div> <div class="url"> <a href="{% url 'ldap:index' %}">or … -
Django STATICFILES_DIR - files out of the project folder not collected
I'm trying to setup my applications so that they all use the same static folder for Bootstrap, jQuery etc.. Here are the relevant settings : STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'MyApp/static'), os.path.join(os.path.dirname(BASE_DIR), 'Tools/static/assets'), "full_path_to_assets" ] However only the first static folder (the app one) is collected when I run collectstatic. According to the official doc, static files do not need to be in the project folder, so I'm quite confused, what's wrong with this ? I'm working with Django 2.0 and Python 3.6. -
Django models access outside Django without access to the settings file
I would like to allow people that don't have access to the Django project root folder (so no access to settings.py file and no DB password) to use specific models outside of Django. I would like some users to be able to query certain tables in the database using the powerful Django structure (querysets etc...) without giving full access to all the tables. Would any of the following strategies work? Is it even possible to do that? And what are the best practices for this kind of issues? Idea 1: Setting-up django using my_project.settings. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") django.setup() The problem is that it requires access to the project root folder and give access to all the database Idea 2: Setting-up django using a different database user with restricted access from django.conf import settings settings.configure( DATABASE_ENGINE = 'django.db.backends.mysql', DATABASE_NAME = '<db_name>', DATABASE_USER = 'new_user', DATABASE_PASSWORD = '<psw>', DATABASE_HOST = '<host>', INSTALLED_APPS = ... ) I didn't manage to make this work yet but I feel like the django.setup() will fail because the DB user won't have access to all the tables. Also it still needs access to the project root folder. Idea 3: Using the database (MySQL) directly from python, no link … -
How does a website keeps itself updated for new data?
I'm currently developing a website for a chat application (everything in the serverside is Django). One of the problems I faced was how to keep the website (once a user is logged and has everything rendered) updated if the user needs to receive something new (a new message, notifications, etc). The solution I came with was to first create a URL to send a get request, and the response would be a list of unseen notifications for the user. Then, in the HTML, a JavaScript code to send request to this URL and receive the unseen notifications. This way, upon loading, the page will send a get and receive all unseen notifications and save them in a variable, after that it will keep sending the request every half a second and check if the rendered data is the most recent data, and if it's not, reload the page to refresh all the rendered data. Now, this works ok, but I'm not sure this is how it should be done, as I'm bombarding with requests my server (currently, everything in development and just a couple of users at the time nothing exploded) and the client is sending request all the time. … -
Multiline if condition in django html templates
My if statement in django template is too long. I want to break that into multiple lines. {% if ABCDEFGH == BENDHSS and asdasd == asdasdas or asasdas == asdasdd and dasdasdsa == asdasdass or ghgfgsd == efdscsdfg and sgrtvsd == acsdfer %} I want to break the above line of code into multiple lines. In python, We break it with a backward slash("\"). if ABCDEFGH == BENDHSS and asdasd == asdasdas or \ asasdas == asdasdd and dasdasdsa == asdasdass or \ ghgfgsd == efdscsdfg and sgrtvsd == acsdfer: Could anyone let me know how we do it in django? -
Putting the celery tasks outside of django application as a separate module
I am building a task based server side application using celery, rabbitmq and django. I want to manage better and version all my tasks, as such I want to move them outside of the django project (same machine). Is that possible, will my tasks still be discovered outside of the project provided if I specify the correct path in CELERY_IMPORTS. Or better does the celeryconf.py work if placed outside of the project? What possible insurmountable problems would I encounter? -
Python 2 to Python 3 futurize builtins str
I am converting a django application from Python 2 to Python using futurize. I am currently futurizing future_builtins. In the following set of code in the test: response = str(self.client.get(self.url)) I get the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 3261: ordinal not in range(128) and the test fails However, when I remove the following import: from builtins import str The tests pass. I tried to use decode() function but I get the same error. Where could I be going wrong? -
django i can't see my form
I don't understand why I can't see my form. I would like to create a form with a drop down menu with display_name of rider model as the choices. my models.py: class Rider(models.Model): first_name = models.CharField(max_length = 256,blank= True) last_name = models.CharField(max_length = 256,blank= True) display_name = models.CharField(max_length = 256,blank= True) birth = models.DateTimeField(default=timezone.now) place_of_birth = models.CharField(max_length = 256,blank= True) age = models.IntegerField(default = 0,blank= True) nationality = models.CharField(max_length = 256,blank= True) height = models.FloatField(default = 0.0 ,blank= True) weight = models.FloatField(default = 0.0 ,blank= True) team = models.CharField(max_length = 256, blank= True) team_code = models.CharField(max_length = 256, blank= True) cost = models.IntegerField(default = 0,blank= True) def __str__(self): return self.display_name my form.py: class ScoreForm(forms.ModelForm): riders =forms.ModelChoiceField(queryset=Rider.objects.all(),to_field_name="display_name") class Meta: model = Rider fields = ('display_name',) my view.py: class ScoreView(TemplateView): form = ScoreForm model=Rider template_name = 'blog/score.html' Screenshot -
Retrieve user existing in one of related models in one query
I am looking for ORM or RAW SQL here that would improve speed and efficiency. First, the design (imho) is the best it can be but am open to suggestions cos thats how the client business works. A user/employee works in a specific "spot" in the hr structure, which looks like this: Head: id,name dept: id,head_id,name division:id,name,dept_id unit:id,name,division_id Now to complicate matters what others, each of the above have "offices" inside them. That was revealed later. So, instead of creating "office" for each, I added an office model with nullable cols: office: name,head_id,dept_id,division_id,unit_id Now, an employee can work in an office, head,dept,division or unit. Users: id,first_name Positions: id,user_id,head_id,office_id,head_id,dept_id,division_id,unit_id where all except user_id are nullable. Now, I want to get list of positions of a user with a friendly output. For example, if he is working in department, i want name of the department but also the head the department is located. If he works for an Office that is located in a division,I want to get name of hte office, the division,department and head. So far, I get the information as they are (Office name returns, the rest are null). positions=Position.objects.filter(user_id=1).values('id','office__name','head__name','dept__name','division__name','unit__name') Any suggestion on how the query, raw or orm, … -
How to add a custom action button to the wagtail admin changelist pages?
I want to achieve this feature for models that registered via modeladmin module. -
Django and mariadb not working with istartswith correctly using german umlauts
the following query should only return all cities starting with "Ö" (German umlaut). letter = 'Ö' City.objects.filter(name__istartswith=letter) But it returns cities starting with O and Ö. I use django 1.11 and mariadb. I allready set COLLATE on that table to utf8_bin but this haven't changed the behavior within django. What do I need to do? -
How can I access the response object in DetailView?
I want to access the response object rendered in a DetailView so that I can manually cache it (and delete it from cache on specific uses). What's the best way to access the response object that gets created by the DetailView? -
Django - Using multiple databases, one for each client
I am building a companion web/mobile application for an existing web app. The database is implemented in MySQL. I will be writing an API using Django/Django Rest Framework (DRF). The application is used by various organizations. The interesting part about the implementation is that each organization has it's own database. In the existing web application, the user enters the database name along with the login credentials. How to go about implementing this in Django? I am going to have lots of models - and they all need to read from the correct database depending on the current user. -
Create url trough django apps
I have two application with two model. I would like to generate the following url structure: http://example.com/company/'companyslug'/worker/'workerslug' In the url above the 'companyslug' and 'workerslug' are variables. I already run over a many of posts but I didn't find any solution for it. The main problem is that, if the system generates link the value evaluated both times as an attribute of Worker model. Do you have any idea, how can I generate a link as it looks like above? Many thanks! app1/models.py class Company(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=150) slug = models.SlugField(max_length=150, unique=True) app2/models.py class Worker(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) rel_company_worker = models.ForeignKey('app1.Company', on_delete = models.CASCADE, null=True,related_name='workers') first_name = models.CharField(,max_length= 50, blank=True ) last_name = models.CharField(,max_length= 50, blank=True ) slug = models.SlugField(max_length=100, null=True) I have 3 urls file: urls.py urlpatterns = [ path("company/", include('app1.urls')), ] app1/urls.py urlpatterns = [ path('<slug:slug>/worker/',include('app2.urls')), ] app2/urls.py urlpatterns = [ path('<slug:slug>',views.WorkerDetailView.as_view(), name ='worker-detail-view'), ] app2.views.py class WorkerDetailView(generic.DetailView): model = Worker If I run the code it genearates the following link: http://example.com/company/'workerslug'/worker/'workerslug' -
Using Wagtail as an API layer
My company is evaluating Wagtail as a CMS for parts of our website. Currently we're running Python 2.7 and Django 1.5 (don't ask...). We have the ability to run Wagtail on a separate instance which can include the most current versions of Python/Django but we will not be able to run Wagtail out of the box within our main application. We're looking at using Wagtail strictly as a CMS, then proxying requests from our main website to the Wagtail instance and returning just the generated markup. Is there anyone who has done something like this, of could offer insight into the process we might take? Does Wagtail offer functionality like this out of the box? What potential pitfalls might we encounter, or things we should watch out for? -
django redirect to another view with context
I have this in my view def foo(request): context['bar'] = 'FooBar' return redirect('app:view') is there some way to include this context['bar'] when I redirect to 'app:view'? My last resort and alternative would be to do use render() however, I do not want to define all the context variables again. Is there any other approach to this? -
PHP, Python Django File Download Control
The application will send a link by SMS, the link requires OTP and after verification of OTP, a PDF document is downloaded. Now, how can we ensure the file is successfully downloaded and opened? Can we have our page download the file in the background with a progress bar UI and hand over to browser/system download API only after the file is successfully downloaded in the background. We want assurance that file is successfully received and opened. Thank you to all those extending their help. -
Wants to create choice field dynamically i.e. current time after that + 30 min
My code is below: <pre> def datetime_result(): t = datetime.datetime.now() intervalTime = 30 currenttime = t.minute checktm = int(currenttime) - int(intervalTime) if checktm < 0: addtime = abs(checktm) elif checktm > 0: addtime = intervalTime - checktm else: addtime = checktm opentime = t + datetime.timedelta(minutes=int(addtime)) closetime = datetime.time(22, 30, 0) firsttime = opentime + datetime.timedelta(minutes=60) start_time = opentime.strftime('%H:%M') end_time = closetime.strftime('%H:%M') slot_time = 30 # Start date from today to next 5 day start_date = datetime.datetime.now().date() end_date = datetime.datetime.now().date() + datetime.timedelta(days=0) days = [] Delivery_Time_CHOICES = "" date = start_date while date <= end_date: time = datetime.datetime.strptime(start_time, '%H:%M') end = datetime.datetime.strptime(end_time, '%H:%M') while time <= end: Delivery_Time_CHOICES += ('(' + "'" + time.strftime("%I.%M%p") + "'" + ', ' + "'" + time.strftime("%I.%M%p") + "'" + '),') time += datetime.timedelta(minutes=slot_time) date += datetime.timedelta(days=1) return '(' + Delivery_Time_CHOICES + ')' This code will generate time from current time + 30 minutes on wards time. when i called this method in choice filed gives me error "string index out of range" and when i put printed value of this method direct in choice field variable then its working.