Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Digital ocean Kubernetes + Django / PostgreSQL getiing an database error inside cluster
my app is inside a docker container and works perfectly fine in local host..but when i run this docker image in kubernetes cluster it gives me this error conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known here is my database settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } I deployed the image into kubernetes cluster with frontend.yml manifest file..it looks like this frontend.yml apiVersion: extensions/v1beta1 kind: Deployment metadata: name: dockersample-app labels: app: polls spec: replicas: 3 template: metadata: labels: app: dcokersample-app spec: containers: - name: dcokersample image: mahesh61437/dockersample:v6 imagePullPolicy: Always ports: - containerPort: 8000 ---service.yml apiVersion: v1 kind: Service metadata: name: dockersample-app labels: app: dockersample-app spec: type: LoadBalancer ports: - port: 8000 targetPort: 8000 selector: app: dockersample-app here is my DOCKER File FROM python:3 RUN apt-get update EXPOSE 8000 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ CMD python manage.py runserver my docker-compose.yml version: '3' services: db: image: postgres restart: always environment: POSTGRES_USER : postgres POSTGRES_PASSWORD: POSTGRES_DB: db expose: - "5432" volumes: - postgres_data:/var/lib/postgresql/data/ web: restart: always build: … -
How to run a python script in django propject which has multiple django models in it
I have a script that I want to run from terminal inside a django project and that script is a python script and it has multiple django models in it .So how can I run that script since I am not able to run it directly.Also everything resides inside docker container. -
How to use client_credentials in Django Oatuh2
I want to use cleint_crendetials in Django Oauth2 Rest Framework. But when i am sending request with access token it is always say Unauthorized -
How to show dynamic drop down in django?
I want to show the Bank account number of an employee based on his saved banking details while adding salary. But now I am getting all employee's bank account number rather than just selected one. below is my forms.py I tried to set the field in forms.py but I do not know how to filter using employee id in that. class SalaryCreateForm(forms.ModelForm): class Meta: model = Salary_Rotation fields = ('Sal_Emp_Desig', 'Payment_Mode_of_Salary', 'Emp_Acc_number', 'Cheque_Number', 'Transaction_Number', 'P_Tax', 'Salary_Amount', 'Salary_Date') def __init__(self, *args, **kwargs): super(SalaryCreateForm,self).__init__(*args, **kwargs) self.fields['Sal_Emp_Desig'].queryset = Designation.objects.filter(Is_Del=0) self.fields['Emp_Acc_number'].queryset = Employee_Bank_Detail.objects.filter(Is_Del=0) below is my template <form class="form-group" method="POST"> {% csrf_token %} <label class="control-label"> Employee Name:- </label> <input class="form-control" value="{{emp.Emp_Name}}" type="text" name="compnay" readonly/ > <label class="control-label"> Company Name:- </label> <input class="form-control" value="{{emp.Emp_company}}" type="text" name="compnay" readonly/ > <label>Bank Account</label> <select id="id_Emp_Acc_number" name="Emp_Acc_number" class="form-control" > <option value="" selected="">---------</option> {% for acc_num in bank_acc_numbers %} <option value="{{acc_num.id}}" >{{ acc_num.Emp_Acc_num }}</option> {% endfor %} </select> {%endfor%} {{ form|crispy }} <button class="btn btn-rounded btn-success" type="submit">Add Experience</button> {% for emp in employees%} <a href="{% url 'employee-detail' emp.id %}" class="btn btn-rounded btn-brand ml-4">Cancel</a> {%endfor%} </form> below is my view.py class SalaryCraeteView(LoginRequiredMixin,SuccessMessageMixin,CreateView): #permission_required = 'Company.add_company' model=Salary_Rotation success_message = " Salary added successfully!" reverse_lazy('employee-detail') login_url= "login" template_name = 'employee_salary_form.html' form_class = SalaryCreateForm … -
The joined path (relative path) is located outside of the base path component (full path)
I am trying to use thumbnail packages to generate thumbnail images from base images. Originally, I had my source images in my static dir, and as the thumbnail packages want to generate them to my media dir, I thought that was the cause of the SuspiciousFileOperation error I was getting. No problem, I just copied my images to my media dir, which I thought would solve the issue, but no, the issue remains. From what I can tell, it seems to be a problem with having a relative path vs a full path? The full error is: SuspiciousFileOperation at /toys/ The joined path (/media/images/test.jpg) is located outside of the base path component (/home/username/django/first_webapp/my_site/media) The path /home/username/django/first_webapp/my_site/media/images/test.jpg is valid and test.jpg is a valid jpg image. The abridged code I am using in my template, with sorl-thumbnail (although I have also tried with easy_thumbnails) is: {% for instance in prods %} <img src=" {% thumbnail instance.image_url 300x300 %} "> {% endfor %} instance.image_url, in this case, is set to /media/images/test.jpg My media directory settings from my settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I am unsure where to begin to troubleshoot this. -
Oauth2 Django Token
How can i specify who is accessing my api using Oauth2. Because when i am generating Oauth2 with grant type password. It is telling me to create app. But i want to create a named on Company and when user is accessing it should client_id and client_secret password and username. Basically i want to create one token against company so that its users can acess the api. But when i am creating it is creating token against only one user who has created it. Please Help. I need a guide to help me out -
I am getting operation error no such table in django after renaming the user model
I created a custom user model and then I added some users in it. After that I tried to change the user model's name and then after changing the name and running the migrations When I tried to open the admin panel I am getting No Such Table operational Error saying no such table (previous name of user model) For the solution I deleted the complete register app and tried to create model's in another apps. The models got created an they are in admin panel and when I am trying to add some thing in these models I am getting that same error. OperationalError at /admin/home/test/add/ OperationalError at /admin/home/test/add/ no such table: main.reg_boouser Request Method: POST Request URL: http://localhost:8000/admin/home/test/add/ Django Version: 2.0.6 Exception Type: OperationalError Exception Value: no such table: main.reg_boouser -
Can there be a general way of extracting 'cleaned_data' from a django form after post? Such that this can be used for any django form
I was wondering if we can create a general method that would accept a form instance after POST and extract all fields into a dict with keys same as the field names from the django form. -
When exactly do I need staticfiles_urlpatterns
currently I am dealing with django static/staticfiles and I learnt a lot about static_url, static_root, staticfiles_dirs here at stackoverflow and in youtube tutorials. However I don't understand what "staticfiles_urlpatterns" does and when exactly I have to use it? Thanks for an answer. -
how to upload file in a specific address using django admin panel?
I'm Developing a django admin panel that has image upload capability ,image upload works successfully , but i cant access to images from entering urls in browser . When I want to try to access to a picture like this : http://127.0.0.1:8000/media/485508.jpg I get this error : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/485508.jpg Here Is My Codes : Models.py : picurl = models.ImageField() Settings.py : STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'http://127.0.0.1:8000/media/' if not os.path.exists(MEDIA_ROOT): os.makedirs(MEDIA_ROOT) and i can see the file in the specified folder successfully uploaded . How can i access to pictures in the url ? and How Can I upload files to Wamp WWW Folder ? any suggestions will be helpfull . thanks . -
Manually Rendering Django Form with Validation
I've started to create a form. Basically the form is a "test" of twenty words. The form consists of twenty text fields which I want to contain the definition of a word. The user would input the word. Once complete, the form should validate the data and mark what is correct and what isn't. I've done plenty of modelforms in django, but this one is different. All the data in this form has to be passed through as context. views.py def get_test(request, username='default'): template_name = 'main/test.html' if request.method == 'POST': pass else: lang = Language(config('USER'), config('PASS')) streakinfo = lang.get_streak_info() uniquewords = lang.get_unique_words() testwords = get_test_words(uniquewords) wordsdict = get_word_dict(testwords) form = TestForm() context = { 'testwords': testwords, # list of random unique test words 'wordsdict': wordsdict, # dict of words + definitions {word: {pronounciation, definition}} 'form': form, } return render(request, template_name, context) forms.py class TestForm(forms.Form): word_1 = forms.CharField(label='1', max_length=100) word_2 = forms.CharField(label='2', max_length=100) word_3 = forms.CharField(label='3', max_length=100) word_4 = forms.CharField(label='4', max_length=100) word_5 = forms.CharField(label='5', max_length=100) word_6 = forms.CharField(label='6', max_length=100) word_7 = forms.CharField(label='7', max_length=100) word_8 = forms.CharField(label='8', max_length=100) word_9 = forms.CharField(label='9', max_length=100) word_10 = forms.CharField(label='10', max_length=100) word_11 = forms.CharField(label='11', max_length=100) word_12 = forms.CharField(label='12', max_length=100) word_13 = forms.CharField(label='13', max_length=100) word_14 = forms.CharField(label='14', max_length=100) … -
Django query set object query taking too much time?
I am using a job model fetching the related jobs data which is also relationship with others model too for one-to-one or foreign key relations i have used select_related() and pass relative model inside and another one manny-to-manny relations i have used prefetch_related() and pass relative model inside. I have used this queryset on page 2 times based on different conditions filter everythings working fine but 1job queryset taking time and 2nd working well I can't understand that what's thing i missed up and how to resolved it. Please help if any one understand. -
Django: Login a user after clicking on the activation link from email
I have tried to login a user after the user clicks the activation link send to the user's email. But directly using the login() method will throw me the error 'User' object has no attribute 'backend'. I have tried using authenticate() method but since i need to use the password already stored in the backend, authenticate(username, password) does not return any user. Here is my activation view def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') To solve the issue of User object has no attribute backend I used authenticate as: username = user.username password = user.password user = authenticate(username=username, password=password) if user is not None: login(request, user) No user is returned. Can somenone help me? Edit: I am using Django 1.8.11 and python2.7 -
How to handle [Errno 13] Permission denied
While saving the file it is throwing following error [Errno 13] Permission denied I am trying to save the file in the current working directory but it is not saving file_data = base64.urlsafe_b64decode(i['body']['data'] .encode('UTF-8')) store_dir = os.getcwd() path = ''.join([store_dir, i['filename']]) f = open(path, 'w') f.write(file_data) f.close() -
Nested Relationship in Django Doesn't Work
These are my models here: class Site(models.Model): siteID = models.CharField(max_length=255, primary_key=True) class EndDevice(models.Model): class Meta: unique_together = ("edevID", "siteID") edevID = models.CharField(max_length=255) siteID = models.ForeignKey(Site, related_name='endDeviceList', on_delete=models.CASCADE) deviceCategory = models.BigIntegerField() This is my serilaizer: class DeviceSerializer(serializers.ModelSerializer): class Meta: model = EndDevice fields = ("edevID", "siteID", "deviceCategory") class SiteSerializer(serializers.ModelSerializer): endDeviceList = DeviceSerializer(many = True, read_only=True) class Meta: model = Site fields = ("siteID", "endDeviceList") This is my view: class IndividualSite(generics.RetrieveUpdateDestroyAPIView): ''' PUT site/{siteID}/ GET site/{siteID}/ DELETE site/{siteID}/ ''' queryset = EndDevice.objects.all() serializer_class = SiteSerializer def get(self, request, *args, **kwargs): print('Individual Site') try: s1 = self.queryset.get(siteID=kwargs["pk"]) return Response(SiteSerializer(s1).data) except Site.DoesNotExist: return Response( data={ "message": "Site with id: {} does not exist".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND ) I am trying to get/put/delete results using this class and I am trying to get all the EndDevice instances which have same siteID. But my serialzer only shows the siteID and doesn't show the endDeviceList (which should have the instants of the model EndDevice) The problem is quite similar to this link:django rest-farmework nested relationships. I have been trying different ways to serialize the objects, I think this is probably the smartest way, but have been really unsucccessful. Any help will be appreciated. -
celery tasks converts python list into strings. how to avoid this?
I have an email sending tasks running in celery shared task. i am passing a python list into html template. but celery converts this list into string. but without using celery task , i am getting actual list. -
How to install virtualenv on windows path without permission denied error?
I got a new computer and I am setting up my environments to run django. I'm installed python and virtualenv. In windows 10, I tried to run virtualenv -p python . in the directory C:\Users\user\Dev\folder, but I'm getting the following error: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python\\python37-32\\lib\\site-packages\\pip-18.1.dist-info\\entry_points.txt' Consider using the--useroption or check the permissions. How do I give myself permissions to create an environment here? I have all admin privileges. -
AttributeError : 'NoneType' object has no attribute '_meta'
custom_user model class User(AbstractBaseUser): objects = UserManager() email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) domainID = models.ForeignKey(Domain, on_delete = models.CASCADE, null=True,blank=True) roleID = models.ForeignKey(UserRole, on_delete = models.CASCADE, null=True,blank=True) user_name = models.CharField(max_length = 200,null=True,blank=True) phone = models.CharField(max_length = 50,null=True,blank=True) is_verified = models.BooleanField(default=False) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser created_DT = models.DateTimeField(auto_now_add=True) updated_DT = models.DateTimeField(auto_now=True) carrier model class CarrierExtraInfo(models.Model): CustomUserID = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True) somevalue = models.CharField(max_length=100,null=True,blank=True) is_active = models.BooleanField(default=True) created_DT = models.DateTimeField(auto_now_add=True) updated_DT = models.DateTimeField(auto_now=True) custom_user serializer class CreateCarrierSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email','domainID','roleID','user_name','phone') carrier serializer class CarrierExtraInfoSerializer(serializers.ModelSerializer): class Meta: model = CarrierExtraInfo exclude = ('created_DT','updated_DT') output error not field.remote_field.through._meta.auto_created AttributeError: 'NoneType' object has no attribute '_meta' "POST /carr/api/carr_user HTTP/1.1" 500 16718 why i'm getting this?? on migration there is no error but on post request this error arrives. -
Django Tenant Users with DRF, table for tenant app not found
We're creating a backend API using Django REST Framework (DRF), and it will also be multi-tenant via django_tenants. I just added the django_tenant_users module and have successfully created and provisioned a user. One custom app in our site is "projects", and it is in the settings.py file under TENANT_APPS. In my postgres client, I can see the tenant schema (mrr), and the table in that schema named "projects_project". I can even view the table in the client, though it is empty. I then browse the API via the API browser feature included in DRF. But even logged in as the tenant user I created, I get the following error when I try to view the Projects list... ProgrammingError at /projects/ relation "projects_project" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "projects_project" Do I need to specify the tenant somewhere in my project model? Or perhaps it needs to be subclassed from something other than models.Model? -
model class treated as local variable in django
When i tried to access the form for editing, this error occurs local variable 'Profile' referenced before assignment views.py from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect,get_object_or_404 from home.models import UserCreateForm,Profile from home.forms import ProfileCreateForm # Create your views here. def update(request,pk): profiles=Profile.objects.all() print(profiles) if request.method == 'POST': form = ProfileCreateForm(request.POST,request.FILES) if form.is_valid(): Profile = form.save() return redirect('home') else: form = ProfileCreateForm(instance=profile_instance) return render(request, 'registration/profile.html', {'form': form}) the model is Profile models.py # -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.forms import UserCreationForm from django import forms GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) class Profile(models.Model): firstName = models.CharField(max_length=128) lastName = models.CharField(max_length=128) address = models.CharField(max_length=250) dob = models.DateTimeField() profilePic = models.ImageField(blank=True) gender=models.CharField(max_length=2, choices=GENDER_CHOICES) def __str__(self): return self.firstName Adding new form works perfectly but accessing the saved form from the db results in an error -
Django: How to override default error message?
I'm trying to customize This field is required error message but it doesn't work as expected. First I tried to create custom validator. validators.py def required_field(input): if input is None or input == '': raise ValidationError("Custom error message") and models.py a_field = models.TextField(validators=[required_field]) However, the validator doesn't work and the default error message This field is required. shows up. Second, I override the clean method models.py def clean(self): if not self.a_field: raise ValidationError({'a_field': 'Custom Error Message'}) The error message shows up but it is followed by default error message. How can I override it directly? I'm using crispy_form btw. html {{ form|crispy }} -
How to download file from local directory using javascript
I want to download a file from the local directory when the user clicks on a particular link. I have used django and javascript. Whatever path I have given in django is working. When the user clicks on the particular link it goes to the correct location but the file does not download. How can I do it using javascript? else if(currentobj.filename != null){ var xy = '{% static "/documents/dataset/" %}' + currentobj.filename; alert(xy); var $tr = $('<tr><td style="padding:5px;"><a href="'+ xy +'" target="_blank" >' + currentobj.filename.slice(0,25) + "....." +'</a></td> </tr>'); $tbl.append($tr); } -
can i set django model paranoid which acts like in Sequelize.js
// don't delete database entries but set the newly added attribute deletedAt // to the current date (when deletion was done). paranoid will only work if // timestamps are enabled paranoid: true, I used Sequelize.js ORM, and there was option paranoid like above description. (from Sequelize.js tutorial docs) I want to make my Django Model paranoid. I googled with keywords like "django paranoid", but i couldn't find informations. What is a general name for the option "paranoid" and how can i make my django model act like the option? Or should I make mixins or middlewares to make paranoid? -
AttributeError: module 'django.contrib' has no attribute 'admin'
When I run python manage.py runserver,encounter the following errors Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10fb4cc80> Traceback (most recent call last): File "/Users/apple/Desktop/learning_log/ll_env/lib/python3.7/site- packages/django/apps/config.py", line 118, in create cls = getattr(mod, cls_name) AttributeError: module 'django.contrib' has no attribute 'admin' and below ImportError: cannot import name 'AutocompleteSelect' from 'django.contrib.admin.widgets' (/Users/apple/Desktop/learning_log/ll_env/lib/python3.7/site-packages/django/contrib/admin/widgets.py) -
Filtering based on ManyToManyField - Get record if item present in list
I wanted to know if there was a way for me to filter based on ManyToManyField field. I know there is a __in filter however it seems like this filter requires an id and I dont have an id (I could get the ids but I wanted to know if it was possible without it). This is what my model looks like class modelJob(models.Model): skills = models.ManyToManyField(modelSkill,blank=True) title = models.CharField(max_length=200, unique=False,blank=False,null=True) and this is the model of many to many class modelSkill(models.Model): skill_description = models.CharField(max_length=50, unique=True) Now I have a list that looks like this skillList = [SkillA,SkillB,SkillC...] #Description field Currently its not possible for me to do this modelJob.objects.filter(skills__in=skillList) The reason I cant do the above is because skills__in is expecting a list with id nos of the skills and not some other field of the skills. My question is how do I tell skills__in that the list I am passing in are the skill_description of the modelSkill and not the ids ?