Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to expose a docker container to access host database?
I'm currently trying to figure out how to configure my docker-compose.yml to allow a web-server (django) to communicate with a PostgreSQL database running on the host machine. The app is perfectly working outside of a container. And now I want to create a container for better management and deployment capabilities. I've tried this, docker-compose.yml : version: '3' services: web: image: myimage volumes: - .:/appdir environment: - DB_NAME=test - DB_USER=test - DB_PASSWORD=test - DB_HOST=localhost command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" networks: - mynet networks: mynet: Dockerfile : FROM python:3 ENV PYTHONUNBUFFERED=1 \ DJANGO_SETTINGS_MODULE=app.settings \ DEBUG=True \ SECRET_KEY=akey WORKDIR /appdir COPY . /appdir EXPOSE 8000 RUN pip install -r requirements.txt But when I do so, I get the following error : web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? Thanks -
JQuery .append() to multiple places in single forloop Python Django
I have a chat application and messages either are classified as outgoing or incoming. Client-side, these messages are shown on either side of the chat, depending on whether they are sent or received. I am trying to use the Jquery .append(msgText) to echo the message when it is sent or received (like the above image shows) but cannot get it to echo in the right place with the correct formatting (it only shows up after a page refresh but I want it to echo in real time). I've tried targeting var sentMsg = $('#sent_msg') with #sent_msg as id within the forloop, but it obviously just appends the sent text to every single sent message. If I put it outside of the forloop (ex) var chatHolder = $('#chat-items'), then the problem is that there is no formatting on the left and right-hand sides...all messages (sent and received) just come through on the left side in an unordered list. Is there a way to append to each new iteration of the forloop and also apply the proper formatting/styles? I'm learning the ropes here so would appreciate any input. thread.html <ul id="chat-items"> {% for chat in object.chatmessage_set.all %} {% if chat.user == user … -
How to show recursive data in template?
I have a model with ForeignKey = 'self', and I want to reflect all data from database via lists and sub lists: here is my model: class Place(models.Model) name = models.CharField(max_length=128, verbose_name='Place name', ) slug = models.SlugField(max_length=128, blank=True, null=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) role = models.CharField(max_length=20, choices=ROLE_CHOICES, null=True, blank=True) -
How i can set value by another field model to model
I have models class Event(models.Model): some_field = models.CharField() class Ticket(models.Model): event = models.ForeignKey(Event) How i can set model ticket field event, event with some_field field? Example: ticket = Ticket() ticket.event__some_field = 'value' ticket.save() how can you achieve this? ps. i can't use ticket.event_id in my situation -
Implement angular and django on the same apache webserver locally on a Centos 7
I have created an angular front end web app and a django REST backend. I am able to implement the django REST backend on apache on Centos 7. I could not find a proper solution to implement both angular and django on apache on Centos 7. It would be very much helpful if you can guide me to some tutorial that actually do this. My requirement is : both angular and django must run on the same apache server. -
How to deploy a Django + Whitenoise application using gunicorn?
I am using Whitenoise to serve static files in my Django app. I am NOT using Nginx. I plan to use Whitenoise behind a CDN like Cloudfront in the future. See Whitenoise FAQs. I have been looking for deployment instructions, which handle these questions: Since I am not using nginx, I plan to bind gunicorn directly to port 80. This results in an error - Permission Denied. I can run gunicorn as root, but that seems like a bad approach. How to handle SSL certificate stuff? Typically this is handled by servers like Nginx. EDIT: I am deploying my application on a Ubuntu 18.04 VM on Google Cloud Compute Engine. P.S.: Mine is not going to be a very high traffic website. Others have used this configuration to serve websites with a high traffic. See this Squeezing every drop of performance out of a Django app on Heroku. -
passing filter variables through the url and retaining them through a redirect
I have 2 issues: I have a redirect which returns to the same template, there is a filter applied which passes parameters like so: http://localhost:99/depot/container/11/?area_easting=99&area_northing=&context_number=123&sample_number=&sample_type=organic. When I redirect to the same template the parameters are lost (as expected) how do I redirect and retain this parameters? I also expect I will need a 'refresh query button. In the template I can pass operation, and the sample_id, but not the container_id. This comes from a m2m samples = models.ManyToManyField('Sample', through='ContainerSamples'), how do I pass this value in the url - related to point 1. My code <a href="{ url 'depot:change_container' operation='add' pk=sample.container.container_id fk=sample.sample_id }" class="badge badge-primary" role="button"> << </a> # urls.py path('container/<int:container_id>/', views.detailcontainer, name='detailcontainer'), # views.py def detailcontainer(request, container_id): container = get_object_or_404(Container, pk=container_id) samples = container.samples.all() container_contents = container.samples.all() unassigned_samples = Sample.objects.all()[:10] unassigned_samples2 = Sample.objects.all() qs = Sample.objects.all() easting_query = request.GET.get('area_easting') northing_query = request.GET.get('area_northing') context_query = request.GET.get('context_number') sample_number_query = request.GET.get('sample_number') sample_type_query = request.GET.get('sample_type') if easting_query != '' and easting_query is not None: qs = qs.filter(area_easting__icontains=easting_query) if northing_query != '' and northing_query is not None: qs = qs.filter(area_northing__icontains=northing_query) if context_query != '' and context_query is not None: qs = qs.filter(context_number__icontains=context_query) if sample_number_query != '' and sample_number_query is not None: qs = qs.filter(sample_number__icontains=sample_number_query) … -
Two tests works individually but not together
I have two tests in separate classes which test similar behaviors : Adding product in bookmark with Client(). Adding product in bookmark with ORM. Individually, it's working : ./manage.py test compare.test.CompareBookmarkTests or ./manage.py test compare.test.CompareAccountTests They fail when they are launched together : ./manage.py test I tried to : use setUp and tearDown methods change order of classes and methods use --reverse in my attempts to diagnose the issue launch lines of code in interactive django shell with a test database (and it's working) make some print debugging, my objects are correctly called from test database. merge those two classes in one I haven't found relevant answers on stackoverflow, for now. Neither in django documentation. from django.contrib.auth.models import User from django.test import TestCase from .models import Bookmark, Categorie, Product class CompareBookmarkTests(TestCase): def setUp(self): Categorie.objects.create(id_categorie='someid', name='somename') p = Categorie.objects.get(pk='someid') p.product_set.create(id_product='1', product_name='orange', categorie='someid') User.objects.create_user('john@sign.in', 'john@sign.in', 'smith') def tearDown(self): User.objects.all().delete() Categorie.objects.all().delete() Bookmark.objects.all().delete() def test_redirect_logged(self): self.client.login(username='john@sign.in', password='smith') # Adding product with id 1 in bookmark response = self.client.get('/compare/1/bookmark/') # Get added product form bookmark bookmark = Bookmark.objects.get(pk=1) self.assertEqual(str(bookmark), 'Bookmark object (1)') self.assertEqual(response.status_code, 302) class CompareAccountTests(TestCase): def setUp/tearDown: [same as previous class] def test_get_product(self): self.client.login(username='john@sign.in', password='smith') user = User.objects.get(pk=1) product = Product.objects.get(pk='1') # Adding product … -
Database view for Mobile Specification in django
I want to create a database for mobile specification in Django. But I'm a little confused on how to create models/table for it. I have a bunch of columns like: [['Brand', 'Aliases'], ['Release date', 'State'], ['Predecessor', 'Successors'], ['Size', 'Aspect Ratio', 'Weight', 'Usable surface', 'Materials', 'Colors', 'Origami'], ['Diagonal', 'Type', 'Resolution', 'Density', 'Others'], [''], [''], ['Model', 'CPU', 'Type', 'Frequency', '64 Bits'], ['GPU'], ['RAM', 'Type'], ['Score'], ['Capacity', 'More or less equivalent to', 'SD Slot'], ['Fingerprint'], ['Fingerprint', 'Accelerometer', 'Geomagnetic', 'Gravity', 'Gyroscope', 'Light sensor', 'Proximity'], ['Notifications LED', 'Cooling system'], ['Resolution', 'Sensor', 'Type', 'Aperture', 'Pixel size'], ['Resolution', 'Aperture'], ['Flash', 'Optical Stabilisation', 'Slow Motion Video', 'Features'], ['Resolution', 'Aperture'], ['Extra'], ['4G LTE', '3G', '2G'], ['Type'], ['Standards', 'Others'], ['Version', 'Profiles'], ['Supports'], ['Charging', 'Mass Storage', 'USB On-The-Go (OTG)', 'USB Type C'], ['--', ''], ['NFC', 'Audio Jack', 'Radio FM', 'Computer sync', 'OTA sync', 'Tethering.', 'VoLTE'], ['Capacity', 'Type', 'Others'], ['Operating System']] -
I used the Material Forms module, yesterday after trying to launch the project, I get an ImportError error: "No module named material"
I used the Material Forms module, yesterday after attempting to launch the project, I get an ImportError error: "No module named material" What happened? -
django-filter: how to force use of dropdown?
I'm using django-filter to generate filter options. For some fields that have a foreign key to model with a limited set of options it generates a drop-down menu, but for others it just generates a blank search field. Is there a way to force it to use drop-down menus for all or specific fields? Here is my code: import django_filters from app.models import Cars class CarsFilter(django_filters.FilterSet): class Meta: model = Recommendation fields = ["area", "car_type", "week_num", "released"] -
Django view redirect NoReverseMatch error
In Django project I have error NoReverseMatch after form save, redirecting to "parent view" views.py def personnel_detail(request, pk): person = get_object_or_404(Personnel, ID_Personnel=pk) try: document = IdentityDocument.objects.filter(ID_Personnel=pk).order_by('ID_IdType', '-DateExpiration').distinct( 'ID_IdType') except IdentityDocument.DoesNotExist: document = None return render(request, 'personnel/personnel_detail.html', {'person': person, 'document': document}) def identitydocument_edit(request, pk): doc = get_object_or_404(IdentityDocument, ID_IdentityDocument=pk) if request.method == 'POST': form = IdentityDocumentForm(request.POST, instance=doc) if form.is_valid(): doc = form.save(commit=False) doc.save() return redirect('personnel_detail', pk=doc.ID_Personnel) else: form = IdentityDocumentForm(instance=doc) return render(request, 'personnel/identitydocument_edit.html', {'form': form}) urls.py from django.urls import path from . import views urlpatterns = [ path('personnel/<uuid:pk>/', views.personnel_detail, name='personnel_detail'), name='personnel_edit'), path('personnel/identitydoc/<uuid:fkey>/', views.identitydocument_edit, name='identitydocument_edit'), ] Form creates new documents and saveing it fine, but after editing it brings NoReverseMatch error. -
How many concurrent connections can django-channels handle?
I am using Django channels for chat application. This application might scale to 100k concurrent users in some amount of time. I am wondering how many concurrent connections can Django Channels handle. Basically, what I am comparing it with is XMPP server, that whether XMPP is a better choice for scalability or I should continue with Django channels? Also, I am using a redis layer as the channel layer. I was wondering if redis layer can be a bottle neck at some point of time? Thanks -
How to make Ajax requests that will be save data?
I am working on project,which includes test.Questions from test has to come out randomly and must display one by one.There is button Next which you pressed when finish to answer to question.Then there must show other question. I do it like below $('btnEnd').click(function() { var rates = document.getElementsByClassName('button_radio') $("input:radio").each(function(){ var name = $(this).attr("name") if($("input:radio[name="+name+"]:checked")){ var radioValue = $("input[name="+name+"]:checked").val() $.ajax({ url: "{% url 'test' id %}", data: { 'radioValue': radioValue }, success: function (data) { } }); } def Test_view(request,id): install = User_table.objects.get(id=id) install.checking=True install.save() random_number =randint(45, 50) list_answered={} radioValue = request.GET.get('radioValue', None) list_answered['random']=radioValue; finance=Test.objects.filter(sections=1,data=date.today(),number=random_number); return render(request,'finance.html',{'finance':finance,'id':id}) Here url is for function Test_view But it doesn't work,and i am not sure does it save answer or not ? -
Form data validation (equivalent of form.is_valid) in a Django consumer (Django Channels)
I'm moving from an http-based setup (Django forms, views etc) to a websocket setup using Django Channels (reasons unavoidable). In my http-based setup, I was entering some data using a form (3 fields - name, number, city) in my template: <form id="EntryForm" method="POST"> {% csrf_token %} <div class="form-group "> {{ form }} </div> <button type="submit">Submit</button> </form> Since this data was being submitted as a Django form previously (which was mapped to my Django model using "class Meta:"), I was easily able to validate it in my views.py using the form.is_valid() method. Each field in the form data has certain conditions like CharField (max_length) etc which was getting verified by the is_valid() method in my views.py: if request.method == 'POST': form = EntryForm(request.POST, instance=Entry(user=request.user)) if form.is_valid(): form.save() messages.success(request, f'Submission accepted.') ... As you can see above, the form belongs to a form class "EntryForm" in my forms.py, which maps to a model called Entry in my models.py (which contains fields like name, number and city). But in Django Channels, in order to submit form data, since I'm having to use a script to .preventDefault() and then send the data as a separate dictionary to my consumers.py, it doesn't get there as … -
How to loop a <span> using template tag in django? condition for the loop comes from database and its of type integer
Getting an error when try to loop in django template, {% for i in obj.rating %}, where obj.rating is integer value. i tried to add range() {% for i in range(obj.rating) %}, but its not working. {% for i in obj.rating %} <span class="fa fa-star blue-star" id="star1"></span> {% endif %} -
How to make "default" in model field pick-up data of the other model's field when entry is created?
I have a following model: class BoatImage(models.Model): boat_photo = models.ImageField(upload_to=get_timestamp_path, blank=True, verbose_name='Boat photo', ) boat = models.ForeignKey("BoatModel", on_delete=models.SET_NULL, verbose_name="Boat ForeignKey", null=True) memory = models.PositiveSmallIntegerField(blank=True, null=True, default = ???) goal is to when entry is made, default in “memory” field should pick up “boat’ field ID or PK and save it the memory “field”, that is, id in both fields should coincide. I am trying to use default with method like: def funk(self): return self.boat.id # or self.boat.pk or self.boat_id – no difference But it says – funk should return int, not foreignkey(error) Question is how to store foreignkey id of the “boat” field in “memory” field when entry is created??? It is possible to do it in save() method but it is quite non-elegant solution in my opinion. Thanks... -
Why isn't my field validation function working?
I'm trying to run a field validation so that users can't submit duplicate URLs. views.py from django.shortcuts import render, redirect from .models import items, comparelist from .forms import AdditemForm # Create your views here. def HomeView(request): if request.user.is_authenticated: user = request.user list = comparelist.objects.filter(user=user) else: list = None allitems = items.objects.all() if request.method == 'POST': form = AdditemForm(request.POST) if form.is_valid(): url = form.cleaned_data.get("url") print('this is from views.py') return redirect('home') else: form = AdditemForm() template = 'compareapp/home.html' context = { "form": form, "list": list, "items": allitems, } return render(request, template, context) forms.py from django import forms from .models import items class AdditemForm(forms.Form): url = forms.URLField( label='URL input here', widget=forms.URLInput( attrs={ "class": "form-control", })) def clean_item(self): url = self.cleaned_data.get('url') print('running clean_item') qs = items.objects.all() for i in qs: if url in i.link: print('url in database') forms.ValidationError('This URL already exists') else: print('new url') return url So when I submit any URL, the def clean_item doesn't run. All I get is the print from views.py Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [01/May/2019 16:17:38] "GET / HTTP/1.1" 200 5938 this is from views.py [01/May/2019 16:17:45] "POST / HTTP/1.1" 302 0 [01/May/2019 16:17:45] "GET / HTTP/1.1" 200 5938 What am I missing? -
Problem with fetching data from local address [Kotlin & Django]
I'm beginner in Android development. I've created a simple api with django to get users information in format Json and displaying them in ListView, but I can't fetch it by AsyncTask. Kotlin code is happy with other addresses. class MainActivity : AppCompatActivity() { private val TAG = "MainActivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val userInformationUrl = "http://127.0.0.1:8000/users/ val downloadUserData = downloadUserData() downloadUserData.execute(userInformationUrl) } } class downloadUserData : AsyncTask<String, Void, String>() { private val TAG = "downloadUserData" override fun doInBackground(vararg params: String?): String { Log.d(TAG, "doInBackground called. parameter: ${params[0]}") val userJsonInformation = downloadJSON(params[0]) if(userJsonInformation.isEmpty()) { Log.d(TAG, "doInBackground called, Something went wrong here") } Log.d(TAG, "doInBackground called, data is: $userJsonInformation") return "" } private fun downloadJSON(urlPath: String?): String { return URL(urlPath).readText() } override fun onPostExecute(result: String?) { super.onPostExecute(result) Log.d(TAG, "onPostExecute called. data: $result") } } Logcat: -
Understanding django annotate
My models: class Ward(models.Model): id = models.AutoField(primary_key=True, unique=True) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) name = models.CharField(max_length=500, default='', blank=True) description = models.CharField(max_length=2000, default='', blank=True) bedcapacity = models.IntegerField(default=1) class Bed(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=200, default='', blank=True, unique=True) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) ward = models.ForeignKey(Ward, on_delete=models.CASCADE) occupied = models.BooleanField(default=False) I'm writing to convert the following pseudocode to django: from django.db.models import F, Q, When clinic = Clinic.objects.get(pk=10) wards = Ward.objects.filter(clinic=clinic) ward_set = [] for ward in wards: occupied = len(Bed.objects.filter(clinic = clinic, ward = ward, occupied = True)) total = len(Bed.objects.filter(clinic = clinic, ward = ward)) ward['occupied'] = occupied # The next two lines are pseudocode ward['total']=total ward_set.append(ward) return render(request, 'file.html', { 'wards': ward_set }) I believe I should be using annotate, but I'm finding it difficult to understand annotate from the docs. -
how to show pdf from server in a Django view?
I am trying to show/read pdfs from server , but getting erros. Below I have attached my view.py . Please help me to solve it views.py from django.shortcuts import render from django.http import HttpResponse from .models import PDF def pdf_view(request): a = PDF.objects.get(id=id) with open('a.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), contenttype='application/pdf') response['Content-Disposition'] = 'filename=a.pdf' return response pdf.closed -
Search and display results using calendar in Django
I want to perform search operation using calendars. I shall select two dates i.e. max_date which shall not be more than the current date but can be less and min_date, these two shall be the days range. The result fields are: in_count, out_count, and dwell_time. The output should sum up all the results of all the days which are between the max_date and min_date. How can I do that? Please help. Is there a need to define a model for this? I am completely clueless. Currently I am performing search operation using a search bar. My model : class Result(models.Model): in_count = models.PositiveIntegerField() out_count = models.PositiveIntegerField() date_time = models.DateTimeField() time = models.TimeField() def __str__(self): return "{},{},{},{}".format(self.in_count, self.out_count, self.date_time, self.time) My views.py class ResultListView(ListView): def get_queryset(self, *args, **kwargs): qs = Result.objects.all() print(self.request.GET) query = self.request.GET.get("q", None) if query is not None: qs = qs.filter( Q(in_count__icontains=query) | Q(out_count__icontains=query) | Q(date_time__icontains=query) | Q(time__icontains=query)) return qs def get_context_data(self, *args, **kwargs): context = super(ResultListView, self).get_context_data(*args, **kwargs) return context class ResultDetailView(DetailView): queryset = Result.objects.all() My result_list.html <div class="card-header">Result on {{ object.date_time}}</div> <div class="card-body"> <h3 class="card-title"><a href="{% url 'result:result' %}"style="color: white; ">Result of Model</a></h3> <p class="card-text"> In Count {{ object.in_count }}</p> <p class="card-text">Out Count {{ object.out_count}}</p> Expected … -
How to create button filter in django, without reloading the page?
I am getting a list containing books, I have to make filter button to categorise it, Right now I am passing argument in the link "?filter=2" with each button click. But this requires reloading the page. -
How to filter the options that can be seen in a foreignkey field that has been put into a django form using drop down menu?
I have a model for Advertisements and I display a list of them on a page. The user is to click the advertisement that they want added to their profile. When a user clicks one of the advertisements they would like added they are redirected to a page that lets them add that advertisement object to their profile. However I would like to filter the advertisements in the drop down form displayed on that page to only show the advertisement object that they selected from the list. How would I filter the results to just one option (i.e the advertisement they selected.) ad_update view def ad_update(request, my_id): obj = Advertisement.objects.get(id=my_id) profile = get_object_or_404(Profile, user=request.user) amount = getAddressAmountUSD(request.user.profile.advertisement.ethAddress) if request.method == 'POST': ad_form = AdvertisementUpdateForm(request.POST, instance=profile) if ad_form.is_valid(): ad_form.save() messages.success(request, f'Your account has been Updated!') return redirect('profile') else: ad_form = AdvertisementUpdateForm(instance=profile) context = { 'ad_form': ad_form, 'object': obj, 'amount': amount, } return render(request, 'users/advertisement_update.html', context) form class AdvertisementUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['advertisement'] model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ethAddress = models.CharField(max_length=42, default='') advertisement = models.ForeignKey(Advertisement, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' -
Django/gunicorn Systemd error status=210/CHROOT
I'm following this guide to set up my Django app on my Raspberry Pi: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-debian-9 I have tried many different configurations of the /etc/systemd/system/gunicorn.service file without success. Here is my most recent version: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=pi Group=www-data Environment=DJANGO_SETTINGS_MODULE=config.settings.production WorkingDirectory=/home/pi/projects/securedash ExecStart=/home/pi/.venvs/securedash/bin/gunicorn \ --access-logfile - \ --log-level debug \ --workers 3 \ --bind unix:/run/gunicorn.sock \ config.wsgi:application [Install] WantedBy=multi-user.target After starting things up, if I run sudo journalctl -u gunicorn I see the following. Apr 30 22:31:15 raspberrypi systemd[1]: Started gunicorn daemon. Apr 30 22:31:15 raspberrypi systemd[1]: gunicorn.service: Main process exited, code=exited, status=210/CHROOT Apr 30 22:31:15 raspberrypi systemd[1]: gunicorn.service: Unit entered failed state. Apr 30 22:31:15 raspberrypi systemd[1]: gunicorn.service: Failed with result 'exit-code'. If I run gunicorn --bind 0.0.0.0:8000 config.wsgi:application from my project root, I'm able to see my app at 127.0.1.1:8000 on the rPi. I haven't been able to find anything regarding the status=210/CHROOT message that I'm seeing.