Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix problem with ListView on django 2.4
I have a problem with ListView can't get queryset from the genre from movies. If i go to categories i can see movies from this category but if i wanna see movies from genre i see an empty list. sorry for my bad english. views.py class MovieListView(ListView): context_object_name = 'movies' def get_queryset(self): if self.kwargs.get('category') is not None: movie_list = Movie.objects.filter( category__slug=self.kwargs.get('category'), published=True, ) movies = movie_list elif self.kwargs.get('genre') is not None: movie_list = Movie.objects.filter( genre__slug=self.kwargs.get('genre'), published=True, ) movies = movie_list else: movies = Movie.objects.filter(published=True) return movies urls.py app_name = "movies" urlpatterns = [ path('', MovieListView.as_view(), name='movie_list'), path('<id>-<name>/', MovieDetailView.as_view(), name='movie_detail'), path("<slug:category>/", MovieListView.as_view(), name="category_post"), path("<slug:genre>/", MovieListView.as_view(), name="genre_list"), ] -
AttributeError at /basic_app/register/ : 'tuple' object has no attribute 'get'
I know this question have been asked alot and most of the time its due to render or HttpResponse in the views.py, i double checked mine but the code looks good to me, dont know where the problem is. This is a views.py file for a very basic django form but i can't get it to work def register(request): registered = False if request.method == 'POST': user_form = UserForm(data = request.POST) profile_form = UserProfileInfoForm(data = request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_from.save() user.set_password(user.password) user.save() profile = profile_form.save(commit = False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: return (user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'basic_app/register.html',{'user_form': user_form, 'profile_form':profile_form, 'registered':registered}) -
JSONField workaround on elasticsearch : MapperParsingException
How do we map Postgres JsonField of Django model to elastic search indexing? , Is there any workaround to make it work ?? Reference : https://github.com/sabricot/django-elasticsearch-dsl/issues/36 models.py class Web_Technology(models.Model): web_results = JSONField(blank=True,null=True,default=dict) web_results field format {"http://google.com": {"Version": "1.0", "Server": "AkamaiGHost"}} documents.py from elasticsearch_dsl import Index from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from .models import Web_Technology @registry.register_document class WebTechDoc(Document): web_results = fields.ObjectField() def prepare_content_json(self, instance): return instance.web_results class Index: name = 'webtech' class Django: model = Web_Technology fields = [] `→ python3 manage.py search_index --create -f Creating index '<elasticsearch_dsl.index.Index object at 0x7f368d6e4978>' Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 128, in handle self._create(models, options) File "/usr/local/lib/python3.5/dist-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 84, in _create index.create() File "/usr/local/lib/python3.5/dist-packages/elasticsearch_dsl/index.py", line 254, in create self._get_connection(using).indices.create(index=self._name, body=self.to_dict(), **kwargs) File "/usr/local/lib/python3.5/dist-packages/elasticsearch/client/utils.py", line 84, in _wrapped return func(*args, params=params, **kwargs) File "/usr/local/lib/python3.5/dist-packages/elasticsearch/client/indices.py", line 105, in create "PUT", _make_path(index), params=params, body=body File "/usr/local/lib/python3.5/dist-packages/elasticsearch/transport.py", line 350, in perform_request timeout=timeout, File "/usr/local/lib/python3.5/dist-packages/elasticsearch/connection/http_urllib3.py", line 252, in perform_request self._raise_error(response.status, raw_data) File "/usr/local/lib/python3.5/dist-packages/elasticsearch/connection/base.py", line … -
How to fix "required parameter name not set" in django
I am having a problem adding amazon S3 in my Django app, and the server keeps returning "value error required parameter name not set".please I need help because I am about to quit. ValueError at /app/ Required parameter name not set Request Method: GET Request URL: http://127.0.0.1:8000/app/ Django Version: 2.0.13 Exception Type: ValueError Exception Value: Required parameter name not set Exception Location: C:\Python34\lib\site- packages\boto3\resources\base.py in __init__, line 119 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 Python Path: ['C:\\Users\\Mustapha\\Desktop\\Myfirstapp', 'C:\\WINDOWS\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages'] Server time: Wed, 11 Sep 2019 01:20:16 +0000 templates required parameter not set: <img src="{{Blogger.image.url}}" width="70" height="70" class="c" /> -
add Formset for specific fields in a Django ModelForm
I have a form but I want to add Formset feature specific to fields. So how can I achieve this? model.py : class somemodel(model.): name=models.TextField(blank=True,null=True) somefield=models.TextField(blank=True,null=True) somefield=models.TextField(blank=True,null=True) somefield=models.TextField(blank=True,null=True) form.py: class somemodelForm(forms.ModelForm): name=forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) #I want to give Formset feature for these bellow fields somefield=forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) somefield=forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) somefield=forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model=somemodel fields='__all__' So those are the information and I want to add Formset feature for only "somefield" fields, not to "name" field. -
How to do python setup in CPanel
python Already have a main website, e,g. example.com and I want to add a Django one within it, How to do this in CPanel tell me with that example? tnx to advance? -
Django Rest & React: lookup_field = 'slug' not returning item from db
I'm trying to return items from my sqlite db such that the url in the browser reflects the slug, rather than the unique post id. I had this working before by using the primary key, whereby items were returned from the db when clicking a hyperlink for item detail - but swapping everything out for slug is not working. I have a PostListView in react which lists my items from the db successfully, when I click on one of these the url field in the browser properly shows the slug. However, no data is returned from the db in the underlying detail view. I am using django 2.2.1, django rest framework and react. Back end - django and rest framework modules: Models.py class Post(models.Model): post_id = models.UUIDField( primary_key=True, default=uuid.uuid4, help_text='Unique ID for this post') title = models.CharField(max_length=100) content = models.TextField() publish_date = models.DateTimeField(auto_now=True) slug = models.SlugField(default='') api/views.py class PostListView(ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetailView(RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostSerializer lookup_field = 'slug' api/urls.py urlpatterns = [ path('', PostListView.as_view()), path('<slug>', PostDetailView.as_view()), ] api/serializers.py class PostSerializer(serializers.ModelSerializer): ''' Serialisers will convert our JSON from web into python model ''' class Meta: model = Post fields = ('post_id', 'slug', 'title', … -
How to do RDS IAM Authentication with Django?
I want my django application connect to RDS postgres using IAM authentication. That means the db password expires every 15min and should be re-generated. The problem is how can I change the database password in the runtime? Or should I update my database URL environment? -
Displaying data in template
Hello guys i cannot display this data on my template i have tried few methods but failed is there any solution views.py def list_page(request): qs = Add.objects.annotate(month=TruncDate('date') ).values('month').annotate( total_income=Sum('budget'), total_expense=Sum('expense') ).order_by('date') for i in xy: print (ws['month'],) x = {'qs':qs,} return render(request, 'list_page.html', x) printing only in console and not clearly printing in template. -
Error while installing mysqlclient for windows
While installing mysqlclient for python in windows10 using pip an error is raising.I already installed mysql db. pip install mysqlclient it is giving error like this Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/4d/38/c5f8bac9c50f3042c8f05615f84206f77f03db79781db841898fde1bb284/mysqlclient-1.4.4.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'h:\python3.7.2\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\varun\\AppData\\Local\\Temp\\pip-install-x8dma35a\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\varun\\AppData\\Local\\Temp\\pip-install-x8dma35a\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\varun\AppData\Local\Temp\pip-record-iljjp945\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\varun\AppData\Local\Temp\pip-install-x8dma35a\mysqlclient\ Complete output (24 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'h:\python3.7.2\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\varun\\AppData\\Local\\Temp\\pip-install-x8dma35a\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\varun\\AppData\\Local\\Temp\\pip-install-x8dma35a\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\varun\AppData\Local\Temp\pip-record-iljjp945\install-record.txt' --single-version-externally-managed --compile Check … -
Convert UTC time to local time in django
How can I convert to from UTC time to local time? Here is the format from frontend: Tue Sep 10 2019 00:00:00 GMT+0800 (Singapore Standard Time) This is the print result from Django: 2019-09-09T16:00:00.000Z This is how I convert to local time : def convert_to_localtime(utctime): # print(utctime) fmt = '%Y-%m-%d' utc = datetime.datetime.strptime(utctime,'%Y-%m-%dT%H:%M:%S.000Z' ).replace(tzinfo=pytz.UTC) localtz = utc.astimezone(timezone.get_current_timezone()) # print(localtz.strftime(fmt)) return localtz.strftime(fmt) this is the result from function: 2019-09-09 My expected result: 2019-09-10 -
Iterating list and collecting corresponding from model
I have model which consist of three fields and in the table should look something like this: drg_code | drg_kof | drg_count --------------------------------- A08A | 0.45 | 215 A08B | 0.75 | 656 B03A | 0.33 | 541 B03C | 0.22 | 125 Code for it models.py class DrgCode(models.Model): drg_code = models.CharField(max_length=4) drg_kof = models.DecimalField(max_digits=6, decimal_places=3) drg_count = models.IntegerField() def __str__(self): return self.drg_code I created form for user input which returns QuerySet of drg_code variables. It looks like this in in print: <QuerySet [<DrgCode: A05Z>, <DrgCode: A06A>, <DrgCode: A06C>]>. So I converted it into list. Now I need to iterate through that list and using drg_code variables, find corresponding model fields values, and store them in separate lists so in the end I should end with 3 lists: one for drg_code, one for drg_kof and one for drg_count (these list will be needed for future calculations). I tried using method from my earlier question, but I keep getting error AttributeError saying 'str' object has no attribute 'objects' or similar (depending on code variation I tried) on obj = DRGkodas.objects.first() line. My relevant view.py code: from catalog.models import DrgCode from catalog.forms import DrgCalculator #up to this part everything works so I … -
invitoBidForm' object has no attribute 'ProjectName'
Good days guys need help for my ForeignKey Relationship in my models, i want my foreignkey values is equal to the user choose Here's my model view class ProjectNameInviToBid(models.Model): ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True) DateCreated = models.DateField(auto_now=True) def __str__(self): return self.ProjectName have relations to ProjectNameInviToBid class InviToBid(models.Model): today = date.today() ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE, null=True) NameOfFile = models.CharField(max_length=255, verbose_name='Name of File') Contract_No = models.IntegerField(verbose_name='Contract No') Bid_Opening = models.CharField(max_length=255, verbose_name='Bid Opening') Pre_Bid_Conference = models.CharField(max_length=255, verbose_name='Pre Bid Conference') Non_Refundable_Bidder_Fee = models.CharField(max_length=255, verbose_name='Non Refundable Fee') Delivery_Period = models.CharField(max_length=255, verbose_name='Delivery Period') Pdf_fileinvi = models.FileField(max_length=255, upload_to='upload/invitoBid', verbose_name='Upload Pdf File Here') Date_Upload = models.DateField(auto_now=True) This is my form view class invitoBidForm(ModelForm): class Meta: model = InviToBid fields = ('ProjectName','NameOfFile', 'Contract_No', 'Bid_Opening', 'Pre_Bid_Conference', 'Non_Refundable_Bidder_Fee', 'Delivery_Period', 'Pdf_fileinvi') and Lastly this my view Forms def project_name_details(request, sid): majordetails = ProjectNameInviToBid.objects.get(id=sid) if request.method == 'POST': form = invitoBidForm(request.POST, request.FILES) if form.is_valid(): majordetails = form.ProjectName form.save() messages.success(request, 'File has been Uploaded') else: form = invitoBidForm() args = { 'majordetails': majordetails, 'form': form } return render(request,'content/invitoBid/bacadmininvitoBid.html', args) but im have a error,, hope you can help me. thank you in advance -
how calculation be done in JSON object elements
I have declared instalment_2 as JSONField in Django model . My concern here is I am getting below error : string indices must be integers kindly help me how to solve this . I tried all ways which were available in internet . But no luck . "instalment_2":{"type":"instalment_2","mode":"cash","date":"1/09/2019","amount":"35000"} I am passing this JSON as Post request it should calculate paid n balance based on instalment amounts . Instalment_1 amount already in the table. Now I am trying to do below by passing instalment_2. . instalment_2={"type":body['instalment_2']['type'],"mode":body['instalment_2']['mode'],"date":body['instalment_2']['date'],"amount":body['instalment_2']['amount']} paid=int(obj.instalment_1['amount'])+int(obj.instalment_2['amount']) balance=int(obj.total)-paid -
Recommended Web Technology for an e-commerce product
I need help in choosing the right technology stack for my client's project. The website will provide services for pets by connecting the pet owner to the pet sitter. There will be no physical products to sell on the website. It will be just services like walking, grooming., etc for the customer to choose from the website. The website will primarily connect the pet walker or the pet sitter to the customer in getting these services. https://www.rover.com is a good example of what I am trying to build. We will also be building mobile apps for the same. My experience is mostly in Python and PHP. I have worked primarily on Django, Magento and Codeigniter based projects. But now I started learning NodeJs and I started liking it. So I thought of trying this new website using MEAN stack. But I am not sure if NodeJs is right for such a website. Or should I just stick to Django? -
How to properly pass django list/dictionary to javascript
I have a list of items and want to pass it to javascript array. Django version 2.2.3 In my views.py: my_list = ["one", "two"] context = { 'my_list ': json.dumps(my_list), } return render(request, 'my_template.html', context) my_template.html <script> var my_array = JSON.parse("{{ my_list|safe }}") document.write(my_array ) </script> According to the answers in most topics, my code is valid, but it doesn't display any data. Also tried: <script> var my_string = "{{my_list}}"; var my_array = my_string.split(','); document.write(my_array) </script> In this case when i want to display it i get [" one " -
How to Use CSV file in Django to Plot Graphs on web page with html
How to Generate Graphs from CSV file using Django on my HTML page. -
Django manytomanyfield with through model override through queryset
I have a project working on and it has one model that uses through for manytomany field. It worked as expected but I want to change the queryset through uses for some purpose. A.field.all() -> 1,2,3,4,5 will change to A.field.all() -> 1,2,5 when I do that. How can I change this behaviour? -
How to resolve "column {columnName} of relation {tableName} does not exist" for Django and Postgresql
I'm trying to insert data using a script into a postgresql database for Django, but unfortunately I can't get it to work. I've successfully migrated the datatables and manually generated data using the django backend. I've connected to the database using PgAdmin and confirmed that all the expected columns are there and the datatypes are correct. The django model Django model class Entries(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) quantity = models.IntegerField() typ = models.CharField(max_length=255) price = models.DecimalField(max_digits=20, decimal_places=2) def __str__(self): return self.name The psycopg2 insert line cursor.execute(f'INSERT INTO appname_entries (name, symbol, quantity, typ, price) VALUES (%s, %s, %s, %s, %s)', ('a01', 'AXB', 50, 'purchase', 50.25)) column "price" of relation "appname_entries" does not exist LINE 1: ...appname_entries (name, symbol, quantity, typ, price) ... -
create() takes 1 positional argument but 2 were given? Django
I was confused to why when I run this code it returns an error create() takes 1 positional argument but 2 were given if request.method == "POST": my_form = RawProductCreateForm(request.POST) if my_form.is_valid(): Product.objects.create(my_form.cleaned_data) but when I modify on the create method and add ** before passing the cleaned data it works! Product.objects.create(**my_form.cleaned_data) -
Django form widget does not display error
I have a model.py: class Author(models.Model): Author= models.CharField(max_length=500) ##field required and a form.py: class AuthorForm(forms.ModelForm): class Meta: model = Author widgets = { 'Author': TextInput(attrs={'class':'form-control', 'placeholder': 'Author...'}), in template I render whit: {{ form.Author }} Form works but if I try to save leave the field empty it not display any error. I try with {{ form.Author.errors }} but nothing appear! Any idea? TY -
How to make a Model and View that saves the data in DB for a guest user (not registered in User auth.model)
IS it possible to save the Form data from a Guest / Visitor in the DB? MY Idea is to display a form where a User is presented with the questions. The answers are unique for each user to I want to map the answers to the Users using a Foreign Key. Problem is that when I want to map it using ForeignKey it says that the answers come from a Null User. I ant my visiting users to access the website also. I have saved the Data in sessions and then used it I Do not want to use that approach Is there any way so that my users can access the website without saving the data in the website. Anyways, the flow of code deletes the answers data from DB once the work is done. It is not about getting the work done but exploring and getting knowledge. I can not do class AnsModel(model.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) ans=models.CharField(max_length=1024) What would be the Model and View for this? -
DRF/Multi-tenant - How to specify tenant host (domain) in unit tests?
Environment - Django, Rest Framework, Multi-tenant. In my unit tests, I'm trying to hit an endpoint in a tenant schema (not in Public). It is failing because the host is (for example) example.com instead of demo1.example.com. I've Googled (of course) but can't find how to specify the domain name part of a request. Other posts I've found say it's best to use "reverse" to get the URL instead of hard-coding it. Here's my test: def test_private_valid_authorization(self): self.demo1_tenant.activate() user = User.objects.get(username='test.admin@example.com') token, created = Token.objects.get_or_create(user=user) self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) response = self.client.get(reverse('clients:client-list')) self.assertEqual(response.status_code, 200, "Expected status code: 200; got %s." % response.status_code) Tenants (and their schemas) are created in the setUpTestData() method, so self.demo1_tenant.activate() simply connects to an already existing schema. Users are imported via fixtures, hence the "get" instead of "create_user". I get the following result: AssertionError: 403 != 200 : Expected status code: 200; got 403. Adding diagnostic displays to the code, I've narrowed it down to the process_request() method of django_tenants/middleware/main.py - specifically the hostname_from_request() method. If I put 'demo1.example.com' instead of using the return value from hostname_from_request (which is just 'example.com') my test succeeds. I hope someone can point me in the right direction here. -
How to run python scripts in one computer in LAN and send the output to other system in same LAN?
I have Django project in desktop destination and Apache24 installed in C drive. But I want to use this Django project on other system connected to Same LAN. I am using window 10. I have tried all the solution i found in SO as follows but nothing worked such as: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost','192.168.1.8'] Making debug = true/false adding IP address in ALLOWED_HOSTS But nothing worked. Please help in making/give direction how i can make a connection to get access to Django project via access of LAN. Below is some structure. -
How to implement SSO (single-sign-on) with third party CAS (Central Authentication Service) for a Django-React application?
I'm setting up a Django-React application, with authentication through third party CAS. The process of CAS authentication looks like following: The web application redirects the user's browser to CAS's login URL with a "service" parameter, for instance https://cas.com/login?service=http://myapp.com. Once the user has been authenticated by CAS, CAS redirects the authenticated user back to the application, and it will append a parameter named "ticket" to the redirected URL. Its ticket value is the one-time identification of a "service ticket". For instance, http://myapp.com/?ticket=abcdefg. The application can then connect to the CAS "serviceValidate" endpoint to validate the one-time service ticket. For instance, https://cas.com/serviceValidate?service=http://myapp.com&ticket=abcdefg. In response, CAS shall return an XML containing the authenticated user id, for instance, <cas:serviceResponse> <cas:authenticationSuccess> <cas:user>johnd</cas:user> </cas:authenticationSuccess> </cas:serviceResponse> I've done some research and found it could be implemented in mainly two ways: Serve react as part of Django's static content. Standalone react single page application(SPA) through JWT. I've tried the first approach and it works, but the problem is that every time I want to test the authentication with React, I need to build the static file first and put them in Django, which is kind of slow. So I would like to try the second approach. My question …