Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing Middleware value for testing a Django DetailView
I am writing a test for a DetailView that queries get_object() by accessing a value set in a Middleware. This is for a Companies application and Company Model. Each user is in a Company. To access the company throughout the project, I set the current user's Company.uuid on the request via a custom middleware. Middleware from django.utils.deprecation import MiddlewareMixin class DynamicCompanyUUIDMiddleware(MiddlewareMixin): """ Adds the current organization's UUID from the current user.""" def process_request(self, request): try: company_uuid = request.user.company_uuid except: company_uuid = None request.company_uuid = company_uuid That is used in the CompanyDetailView's get_object() method via a Mixin that I use for the other Company Views. Mixin class CompanyMixin(LoginRequiredMixin, SetHeadlineMixin): model = Company def get_object(self): return get_object_or_404( self.model, uuid=self.request.user.company_uuid) Test The test that I'm trying to write is: class TestCompanyDetailView(BaseCompanyTestCase): def setUp(self): super(TestCompanyDetailView, self).setUp() self.client.login(username="testuser", password="password") self.view = CompanyDetailView() self.view.object = self.object request = self.factory.get(reverse('companies:detail')) request.user = self.user request.view = CompanyDetailView response = self.client.get(reverse('companies:detail')) self.assertEqual(response.status_code, 200) def test_get_headline(self): self.assertEqual( self.view.get_headline(), '%s Members' % self.object.name Result This results in a 404 with the testuser's company not being found. response = self.client.get(reverse('companies:detail')) Walking through it: I create the user Create the company for this new testuser Set the user.company_uuid This should allow the mixin … -
Django how to file field with array for uploading
I have html template: <input name="image[1]" class="file input-image " type="file"> <input name="image[2]" class="file input-image " type="file"> <input name="image[3]" class="file input-image " type="file"> With Django how to integegrate: Django From: class AdsForm(forms.Form): title = forms.CharField(required=True) description = forms.CharField(required=True) price = forms.DecimalField(required=True, max_digits=10, decimal_places=2,) currency = forms.ChoiceField(choices=CurrencyChoise.CURRENCY_CHOICES, label=_('backend', 'ads_currency')) images = forms.FileField() I know : class FileFieldForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) bu it is noy my sloution. I tried: for x in range(0, 6): image[x] = forms.ImageField() but not working. error : IndexError: list assignment index out of range please help me! -
Django / Python - sorting different Class objects sharing the same attribute?
So let's say I have the following models in Django: class Review(models.Model): datetime = models.DateTimeField(("Date"), default=timezone.now) class Rating(models.Model): datetime = models.DateTimeField(("Date"), default=timezone.now) And my view looks like this: def get_page(request, id_slug): context_dict = {} reviews = Review.objects.filter(attribute=id_slug).order_by('-datetime') ratings = Rating.objects.filter(attribute=id_slug).order_by('-datetime') context_dict['reviews'] = reviews context_dict['ratings'] = ratings return render(request, 'page.html', context_dict) What I want to do is make a query set that would include both Review and Rating objects, ordered by the datetime attribute, so something like: activity = reviewsANDratings.order_by('-datetime') context_dict['activity'] = activity What would be the best way to achieve this? Thank you! -
Wagtail custom settings not showing
I created a new project using python 3.6 by following the link tutorial: http://docs.wagtail.io/en/stable/getting_started/index.html. Then I tried to create a custom configuration following the link tutorial: http://docs.wagtail.io/en/stable/reference/contrib/settings.html?highlight=Settings However, the link in settings never appears. Any tips on what it might be? -
Issue while trying to login automatically in django
I have following code in Django. def accountactivation(request): userid =request.GET['id'] userobject= User.objects.get(id=userid) print userobject.username print userobject.password new_user = authenticate(username=userobject.username, password=userobject.password) print new_user #login(request, new_user) #return redirect(reverse('home')) return render(request, 'blog/login.html') The problem is if I manually login, it always works but when I try to login automatically, it never works. Am I missing anything? Printed value of new_user is always None -
django template tag on multiple line
I am creating a custom django template tag by using such a code : @register.simple_tag(takes_context=True) def render_listing(context, *args, **kwargs): ... my code ... This works well, but in my template, it seems that all parameters must be on a single line, for example : this works: {% render_listing param1=val1 param2=val2 ... paramN=valN %} but on multiple lines, it does not work : {% render_listing param1=val1 param2=val2 ... paramN=valN %} I tried multiple escape sequences but I did not succeeded, Is there a way to specify a template tag on multiple lines ? -
Django Heroku Postgres Deployment TCP/IP connections error
I'm having a lot of trouble with the Heroku Postgres setup for my Django app. I'm trying to use the Postgres.app. When I run the Heroku Debugging Command: heroku pg:psql, I get: --> Connecting to postgresql-horizontal-77797 psql (10.3, server 10.2 (Ubuntu 10.2-1.pgdg14.04+1)) SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help. sales-mark-dash::DATABASE=> The Heroku App URL Error says: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port ####? File "/app/.heroku/python/lib/python2.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port ####? The Postgres.app documentation says the password is blank by default in the settings.py. Under the "How to connect" section on the Python tab it says (PASSWORD": "",). How do I set the password for the Postgres.app on a Mac? Maybe it will help me connect. Because I keep getting: psql: FATAL: password authentication failed for user "aliciaalexander" -
Removing a single <li> item causes everything to break in nested {% if %} statement
Removing the very first <li> item in this <ul> will strangely prevent everything else in the page from loading. And it will only happen for anonymous users. So something tells me it has to do with the is_authenticated check which occurs just below it. I can't figure out why removing the first <li> will break everything else. Any idea? <ul class="navbar-nav mr-auto"> <li class="nav-item"> {# this one #} </li> {% if request.user.is_authenticated %} {% if request.user.is_profile_to.profile_photo_thumbnail %} <li class="nav-item"> </li> {% else %} <li class="nav-item"> </li> {% endif %} <li class="nav-item"> </li> <li class="nav-item dropdown dropdown-notifications" data-open-notifications="{% url 'notifications:notifications_ajax' %}"> </li> <li class="nav-item"> </li> {% else %} <li class="nav-item"> </li> {% endif %} </ul> -
Django - Passing data from a view to be used client side using JavaScript in a template
Scenario: I am developing a text-based RPG game in Django and I am wondering what the best way would be to run an event (such as a fight between two characters) server side, and instead of simply passing the result back to the client via a template, such as who won, I want to re-run this 'fight' but in a slower speed using JavaScript. This would show each characters 'turn' and the damage they dealt, although this would be processed instantly on the server. The methods I thought about using were as follows: Pass the combat log/fight through to the template via context using some dictionary or JSON and access the template variable via JavaScript Send this data to an API which the JavaScript code in the template will fetch and modify to show at a reduced speed Do anyone have any better solutions? I don't think I should be posting the outcome of each fight using an API just to transfer this data to client side for use with JS, it's a waste of storage if this is the only use. Thanks! -
Django or Django Rest Framework
I have made a certain app in django and I know that django rest framework is used for API.But when I started to read about django rest framework on there website.Each and every thing in API Guide(like request, response, views etc).talks about it is superior than django(request, response, views etc.) The thing I am not understanding whether these API's will replace my existing django models, views etc. or how can I use them differently in my existing django code I am quite familiar with django but not able to understand what exactly what django rest framework is even after spending some time on it.(I know it is used for API) -
Saving two related models via one serializer and passing the first's id to the second as a foreign key in django rest framework?
I have a JourneySchedule model which stores depart and return journeys: class JouaneySchedule(models.Model): Owner = models.ForeignKey('Profile', on_delete=models.PROTECT) ReturnOf = models.ForeignKey('self', on_delete=models.CASCADE, null=True) JourneyDate = models.DateField(null=True) JourneyStartTime = models.TimeField() IsDepart = models.BooleanField(default=True) Fare = models.PositiveIntegerField(null=False, default=0) Depart and return journeys are connected via ReturnOf self foreign key. Journey serializer is: class JourneyScheduleSerializer(serializers.ModelSerializer): Owner = serializers.ReadOnlyField(source='user.id') ReturnOf = serializers.ReadOnlyField() class Meta: model = JourneySchedule fields = ( 'id', 'Driver', 'ReturnOf', 'JourneyDate', 'JourneyStartTime', 'IsDepart', 'Fare' ) I have defined Commute model to save depart and return journeys at once using nested object (both are instances of journey) class CommuteSerializer(serializers.Serializer): depart_journey = JourneyScheduleSerializer(required=False) return_journey = JourneyScheduleSerializer(required=False) class Meta: model = JourneySchedule fields = ('depart_journey', 'return_journey') So I need to save depart_journey first and then pass the id to return_journey as ReturnOf field. How can I achieve that? -
How to convert status of the user from Django Administration Page
I want to change the status of a registered user to staff or active/notactive. While logging in the Django Administration Page as a superuser I couldn't find any option to do that as you can see from the below screen shot. How can we do it. -
Django: Permission per instance
At the moment, I plan to write a website where users can write blog posts. I haven't started with the implementation yet because I am new to Django and want to get an overview in how I should solve problems and structure the overall project. My problem: The users aren't allowed to use Django's admin page (/admin). The users should only interact with the website that I write. The users at my website will be able to create blog posts. Now, I have to ensure that only the creator of the blog post should be able to edit/delete his own post. All the other users should only be able to read this post. So, I need permissions per user/instance. I know that there are some full-blown permission-systems like django-guardian, but I would like to prefer to solve it on my own. Also to better understand the Django framework. I`ve already read the Django docs, but I am overwhelmed. I guess this is such a common problem that I there is also a common solution to this problem. Can someone help me where I should look at, where to start? My idea so far (please comment): In create a page like … -
How to pass HyperLinkedModels to a form in Django with django-rest-framework
I have this serializer: class ProjectSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Project fields = ('id', 'name', 'project_id', 'user_set') read_only_fields = ('created', 'modified') Then I have a form which is derived from this answer. This is the code from it that I think is relevant: user_set = forms.ModelMultipleChoiceField(queryset=User.objects.all()) You might already see the problem. The API expects HyperLinkedModels to be passed, but instead I pass plain User objects. So posting the form results in this error: "user_set": [ "Invalid hyperlink - No URL match." ] I could edit the serializer to not expect a HyperLink but I would like to maintain that functionality. How can I parse the result from the queryset as HyperLinkedModels? Or how do I make it return HyperLinkedModels from the get go? Is there an easy way to do this? -
Django: 404 error No comment found matching the query
I'm having problems posting a comment related to a park when there are no previous comments posted. Everything works as expected after adding a comment to the park using the admin page. The comment app uses a GenerigForeignKey and currently only has a model. The parks app uses two different classbased views 'formview' and 'detailview' on a single url, as is explained in the django docs here. I have found that no code is executed after this line of code in the CommentFormView post definition: self.object = self.get_object() I have searched on stackoverflow for similar errors but those were mostly related to wrong url configurations. Error message Page not found (404) Request Method: POST Request URL: http://localhost:8000/parks/detail/1 Raised by: parks.views.ParkDetail No comment found matching the query Project urls.py urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), # Django Admin, use {% url 'admin:index' %} url(settings.ADMIN_URL, admin.site.urls), # User management url(r'^users/', include('mtbhub.users.urls', namespace='users')), url(r'^accounts/', include('allauth.urls')), # Your stuff: custom urls includes go here url(r'^parks/', include('mtbhub.parks.urls', namespace='parks')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Project settings.py LOCAL_APPS = [ # custom users app 'mtbhub.users.apps.UsersConfig', # Your stuff: custom apps go here 'mtbhub.parks.apps.ParksConfig', 'mtbhub.comments.apps.CommentsConfig', ] Parks app urls.py app_name='parks' urlpatterns = [ path('', ParkList.as_view(), name='list'), … -
Django: Make Object only editable by creator
I plan to create a small website, where users can log in and write a blog post. However, those users do not have access to the admin page! My goal ist that only the creator of a blog post can edit/delete this post. To be honest, I am a little bit overwhelmed because Django provides so many options in the auth/permissions area and I do not know which approach is best. How would you solve this permission problem in Django, is there a default way to handle this? -
How to create dropdown list in django based on user input / file?
I'm new to Python and Django. I want to create a dynamic drop down list based on uploaded user csv file. when user upload csv file, then use pandas's read_csv() and get columns and I want to create drop down list based on these columns. I can store csv columns in variable but,I don't know how to give that csv columns to forms.py. Here is simple code I tried. Please help me. mycode.py import pandas as pd def read_csv(csv_path): df = pd.read_csv(csv_path) return [x for x in df.columns] view.py from mycode import read_csv from . import forms def upload_form(request): if request.method != 'POST': return render(request,'ML_app/upload_form.html') csv_file = request.FILES["csv_file"] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CSV_UPLOAD_DIR = os.path.join(BASE_DIR,"My_app/csv/") path = os.path.join(CSV_UPLOAD_DIR + csv_file.name) destination = open(path,'wb') for chunk in csv_file.chunks(): destination.write(chunk) columns = read_csv(path) # how to give argment? form = forms.CsvForm() d = {'columns_list':columns,'form':form} return render(request,'My_app/columns_list.html',d) forms.py class CsvForm(forms.Form): return forms.CharField(label='user columns',widget=forms.Select(choices=columns_for_form)) -
Django objects get deletes after a while automatically on heroku server
Does anyone know why my django saved objects getting deleted automatically after a while ' this happened like most of the times that i check my website and see's one of my files get's delete automatically from the server also the deleted file's is not the last saved file but 3rd last file sometime's maybe 2nd last file... and i don't think it's a problem with my written code because this doesn't happens on local development server where usually i keep running development server for more than 4-5 hours sometime's whole day.. -
How to clean 'forloop.counter' variable (reset variable to 1)
in my database there are customers and each customer have sensors. For example customers 1 have 2 sensors. am gettin sensors infos and put them separately in tables. but items's ID (NO) is wrong. please take a look to pic1 as coding, i use standard django template filters. {% for info in infos %} ...... ...... <span> {{ forloop.counter }} </span> {% endfor %} -
How to get selected data from different table in Django database and return json to web client
I have Company, product, customer table in view.py, and product.id, customer.id are forighen key in Company class, how to get the selected data. like sql (select * from Company, customer, product where Company.customer_id = customer.id and company.product_id =product.id) and make it return json, so that in the client side can get the json data? and how to use the json data in the web client? Im new in Django, can you help me with this issue? class Company(models.Model): id = models.IntegerField(blank=True, primary_key=True) customer_id = models.IntegerField(blank=True, null=True) product_id = models.IntegerField(blank=True, null=True) class product(models.Model): id = models.IntegerField(blank=True, primary_key=True) name = models.TextField(blank=True, null=True) class customer(models.Model): id = models.IntegerField(blank=True, primary_key=True) name = models.TextField(blank=True, null=True) -
How to Pass a value from mysql to a form field in create view
I have a PatientConsultationView with a createview class that creates, and an AllConsultationView that List all consultation. I will like to pass the consultation ID to the PatientObservationView and use it to populate the PatientObservationForm OR, just saved it in the PatientObservation Model without end users havent to enter the ID manually since it can be gotten from the AllConsultationView views.py class PatientConsultationView(CreateView): model = PatientConsultation template_name = 'patient/patient_consultation_add.html' form_class = PatientConsultationForm context_object_name = 'Patient_Consultation' success_url = reverse_lazy('patient_list') class AllConsultationView(ListView): model = PatientConsultation template_name = 'patient/all_consultation.html' context_object_name = 'All_Patient_Consultation' def get_consult_id(self): return PatientConsultation.objects.filter(consultation_id=self) class PatientObservationView(CreateView): model = PatientObservation template_name = 'patient/patient_observation_add.html' form_class = PatientObservationForm context_object_name = 'Patient_Observation' success_url = reverse_lazy('patient_list') forms.py class PatientConsultationForm(forms.ModelForm): class Meta: model = PatientConsultation fields = ('patient_id', 'weight', 'temperature', 'blood_pressure', 'pulse', 'oxygen_saturation', 'body_mass_index', 'status',) widgets = { 'patient_id': forms.Select(attrs={'class': 'form-control input-height', 'placeholder': 'Patient ID'}), 'weight': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Weight'}), 'temperature': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Temperature'}), 'blood_pressure': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Blood Pressure'}), 'pulse': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Pulse'}), 'oxygen_saturation': forms.TextInput(attrs={'class': 'form-control input-height ', 'placeholder': 'Patient Oxygen Saturation'}), 'body_mass_index': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Body Mass Index'}), 'status': forms.Select(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Status',}), } class PatientObservationForm(forms.ModelForm): class Meta: model = PatientObservation … -
Django development server static files 404
I know there's a lot of questions about the same topic out there, still there was not one which helped me. I can locate my static files using python manage.py findstatic --verbosity 2 FILENAME, yet when I run server it gives me 404 on those files. I have {% load staticfiles %} command at the beggining of my templates and every file is loaded with {% static FILENAME %} How can I fix this? -
Deploy Django Python 3 MySQL on AWS elastic beanstalk
Can anyone help to deploy django python 3 app on AWS Elastic Beanstalk. Need suggestions for- Configuration for settings.py Static & Media files to S3 RDS mysql setup and configuration Thanks in advance. -
The good bootcamp for python learner and django library
Im a learner of python for a year and i wanna become web app dev with django,is there any bootcamp in highly recommened to that purpose I apprecaite your helps -
Django templates. Comparing variable and constant not working/
I am using Django+python+Docker. I am trying to compare variable and constant in Django templates as: {% if some_variable < 1.25 %} <td class="success"></td> {% else %} <td class="danger"></td> {% endif %} When i'am runing this on localhost, it works fine. When i run this on server it doesn't work. Docker settings are same. All versions are same too. Variable got from django models as models.FloatField(). Db on server and localhost are migrated.