Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple Inlineformset_factory. Using one "child" model and multiple parent modules in a single form
I'm trying to create a single form instance using multiple foreign key references from a single model. I'm fairly new to Django, so I'm not really sure how to implement this. The docs only gives one foreign key reference for inlineformset_factory uses. The reason for so many FK references is each referenced table has its own auto_update and auto_update_now field that need updated separately, so they need to stay that way, I think! Open to any suggestions. Thanks! class HiringPlan(models.Model): """ SHORTLISTED = 'sht' FIRST_INTERVIEW = 'inp' SECOND_INTERVIEW = 'inp' THIRD_INTERVIEW = 'inp' OFFER = 'off' ACCEPTED = 'acc' WITHDRAWN = 'wtd' """ STATUS_CHOICES = ( ('Added', 'Added'), ('Assigned Role', 'Assigned Role'), ('Shortlisted', 'Shortlisted'), ('In Process', 'In Process'), ('Rejected', 'Rejected'), ('Offered', 'Offered'), ('Accepted', 'Accepted'), ('Withdrawn', 'Withdrawn'), ('Started', 'Started'), ('Exited', 'Exited'), ) role_plan = models.ForeignKey( 'RolePlan.RolePlan', on_delete=models.CASCADE, ) status = models.CharField( default=None, max_length=15, choices=STATUS_CHOICES ) status_date_change = models.DateTimeField(auto_now=True, null=True, blank=True) shortlisted = models.ForeignKey('Shortlisted', on_delete=models.CASCADE, null=True, blank=True, related_name='candidate_shortlisted') first_interview = models.ForeignKey('FirstInterview', on_delete=models.CASCADE, null=True, blank=True, related_name='candidate_first_interview') second_interview = models.ForeignKey('SecondInterview', on_delete=models.CASCADE, null=True, blank=True, related_name='candidate_second_interview') third_interview = models.ForeignKey('ThirdInterview', on_delete=models.CASCADE, null=True, blank=True, related_name='candidate_third_interview') offer = models.ForeignKey('Offer', on_delete=models.CASCADE, null=True, blank=True, related_name='candidate_offer') accepted = models.ForeignKey('Accepted', on_delete=models.CASCADE, null=True, blank=True, related_name='candidate_accepted') withdrawn = models.ForeignKey('Withdrawn', on_delete=models.CASCADE, null=True, blank=True, related_name='candidate_withdrawn') candidate_has_hiring_plan = … -
Insert multiple keywords in one field
My question is how i can insert multiple keywords in one django field and show them in a template like stackoverflow tags. Models: class Jobs(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(blank=True, default='') company = models.ForeignKey(Company, on_delete=models.CASCADE) tags = ????? -
Heroku - React not rendering
I have created a Django, Reactjs Web application. I have created the react using create-react-app. Now, I have followed this to deploy to heroku and this to set us postgre sql. After deploying to heroku, the django-rest-framework API end-points are working. So, '/api/..' are working. Also, the django's '/admin/' is working But, the reactjs URL is not rendering anything. I am just getting this error in console. GET http://localhost:3000/static/js/bundle.js 0 () I have no idea on how to solve this! Please state in comments if I have to mention any more details! -
Dockerizing Django App
I have a Django application that uses Python 2.7.10 and Django 1.10.3. My Dockerfile contains the following: FROM python:2.7.10 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ My requirements.txt contains the following: Django>=1.10,<2.0 Mysql-python My docker-compose.yml contains the following: version: '2' services: localhost: image: mysql restart: always environment: MYSQL_DATABASE: 'test' MYSQL_USER: 'test' MYSQL_PASSWORD: 'password' web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - localhost I a docker-compose build, I do a docker-compose up and get the following error: web_1 | django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' I've looked and tried the solutions available on Stackoverflow with no luck. Any help would be much appreciated. Thanks. -
How to change values from database in template using django?
I am using django to build a website. In my template I have some comments that can be liked and disliked. How to change number of likes and dislikes on the spot and store that number in the database without rendering the page every time the count changes? -
Django order_by, multiple fields and with prioritisation
I want to sort a QuerySet based on two factors. A and B, but it should prioritise A over B. That is that it should sort on A, but if A is equal for two objects in the QuerySet, it should sort sort those two objects on factor B. For example, if factor A is time_to_event, and factor B is price. Then it should list all objects with the smallest time_to_event, but if they are the same for two or more objects, it should sort by its price. I have no code examples since I have not tried anything, although I tried to google with no satisfying results. -
ES6 module paths when deployed across multiple web servers
ES6 modules are easy enough to leverage, however I am struggling with how to get them to work in both dev and prod. In dev, they're stored in Django's static folder, which means I can import them like this: import { buildTable } from './customTable.js'; And in the html templates: <script type="module"> import { buildTable } from '../../static/customTable.js' example('hello world') </script> However, in prod, the static folder is on a different webserver, so these paths wont be the same. What is the best way to get these modules to load both in dev and prod? -
Django App on Heroku :Application crashed
guys i tried to add django to heruko but when i tried to access my my site through the given domain i have faced an issue as Application error here is my error log kuapp.com request_id=3226d7fe-a42e-4c41-8618-74f00206f5af fwd="103.49.121.34" dyno= connect= service= status=503 bytes= pr otocol=https 2018-07-23T14:37:30.570428+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=m xiondrf.herokuapp.com request_id=7bfb5e64-d420-4454-9ae2-bcc5845708f2 fwd="103.49.121.34" dyno= connect= service= status=50 3 bytes= protocol=https 2018-07-23T14:38:07.207498+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/robots.txt" host=mx iondrf.herokuapp.com request_id=7172dd6c-03e3-4b97-a671-a8955e17a9b0 fwd="88.99.195.205" dyno= connect= service= status=503 bytes= protocol=http 2018-07-23T14:38:07.399990+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mxiondrf.her okuapp.com request_id=5ef69e04-2675-43c3-b498-1c31b9d734cc fwd="88.99.195.205" dyno= connect= service= status=503 bytes= pr otocol=http 2018-07-23T14:38:10.972312+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mxiondrf.her okuapp.com request_id=1269c22d-b338-4a5c-b3c5-eae226c0a479 fwd="103.49.121.34" dyno= connect= service= status=503 bytes= pr otocol=https 2018-07-23T14:38:11.368496+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=m xiondrf.herokuapp.com request_id=fe34bf01-5208-48f5-99f1-855268cc8853 fwd="103.49.121.34" dyno= connect= service= status=50 3 bytes= protocol=https any kind of help is appreciated -
Can't login on Heroku deployed app, but can login locally
On my web-app, registering and signing in works great while am using the developing server http://127.0.0.1:8000/, But when I deployed the website on Heroku ,, it is not working well .. only users created using createsuperuser works .. Also, after registering the user signs in automatically after registering. But when they logout .. they can't login again here are my code : signup view def signup(request): current_user_ip = get_client_ip(request) current_temp = Temp.objects.filter(created_by_ip=current_user_ip) current_temp.delete() if request.method == 'POST': signup_form = SignUpForm(request.POST, request.FILES) if signup_form.is_valid(): signup_form.save() messages.info(request, "Thanks for registering. You are now logged in.") new_user = authenticate(username=signup_form.cleaned_data['email'], password=signup_form.cleaned_data['password1'], ) login(request, new_user) return redirect('dashboard') else: signup_form = SignUpForm() context = { 'signup_form': signup_form, } return render(request, 'signup.html', context) forms.py class EmailAuthForm(AuthenticationForm): def clean_username(self): return self.cleaned_data["username"].lower() class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, help_text='Must be a valid E-mail') user_name = forms.CharField(required=True, help_text='') password1 = forms.CharField(widget=forms.PasswordInput, help_text='') password2 = forms.CharField(widget=forms.PasswordInput, help_text='Password confirmation') avatar = forms.ImageField() class Meta: model = User fields = ('email', 'user_name', 'password1', 'password2', 'avatar') labels = { 'user_name': 'user_name', 'email': ' email', 'password1': 'password1', 'password2': 'password2', 'avatar': 'avatar', } def clean_email(self): data = self.cleaned_data['email'] return data.lower() urls.py path('login/', auth_views.LoginView.as_view(authentication_form=EmailAuthForm), name="login"), path('signup/', web_site_views.signup, name='signup'), -
initial time in Django form does not update
I have a class like this in Django forms class DateForm(forms.Form): to_date = forms.DateTimeField( label='To Date', input_formats=[settings.API_DATEFORMAT], widget=forms.DateTimeInput( attrs={ 'placeholder': 'yyyy-mm-ddThh:mm:ss', 'class': 'form-control', } ), required=True, initial=datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ'), ) However, the initial time is not being updated when I use this form in Django views. Looks like the time at which the server is started is cached. Any suggestions how to resolve this? -
Django site fails with "ImportError: cannot import name '_BACKCOMPAT_MAGIC_NUMBER'" after working fine for months
I have Django app on hosting which has been running since June last year. I forgot to buy credits and so my hosting provider freezed my app. I bought new credits but I does not start. I simply get: "502 Bad Gateway". I checked the logs, and in python.log found possible problem. Here is the traceback: Traceback (most recent call last): File "/srv/venv/bin/gunicorn", line 7, in <module> from gunicorn.app.wsgiapp import run File "/srv/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 10, in <module> from gunicorn.app.base import Application File "/srv/venv/lib/python3.5/site-packages/gunicorn/app/base.py", line 12, in <module> from gunicorn import util File "/srv/venv/lib/python3.5/site-packages/gunicorn/util.py", line 12, in <module> import pkg_resources File "/srv/venv/lib/python3.5/site-packages/pkg_resources/__init__.py", line 26, in <module> import zipfile File "/opt/python/lib/python3.5/zipfile.py", line 9, in <module> import importlib.util File "/srv/venv/lib/python3.5/importlib/util.py", line 7, in <module> from ._bootstrap_external import MAGIC_NUMBER, _BACKCOMPAT_MAGIC_NUMBER ImportError: cannot import name '_BACKCOMPAT_MAGIC_NUMBER' As far as I know there weren't any changes prior to this problem. Moreover I cannot find similar issues here on SO or elsewhere on the net. importlib should be part of Python 3 so I thought I could try commenting out the import from "/opt/python/lib/python3.5/zipfile.py" but I don't have write permissions on the server. I also tried recreating the venv which did not help. Same with switching Python … -
Unable to apply CSS, possibly because of Bootstrap
There are a lot of questions on StackOverflow that ask this question, but none of the solutions I've tried (i.e. personal stylesheet pasted below Bootstrap link, using a bootstrap-override id to add more weight to my selectors, forcing selectors) are working for me. I validated my CSS, so there are no stray semicolons or similar throwing it off. Also, strangely, the !important attribute does not override the styles. I am building a site with Django. All of my pages are being extended from my "base_generic.html" file, and everything is linked to one stylesheet. When I make any change in my stylesheet, it isn't reflected on the html page. Even the most basic changes that have nothing to do with Bootstrap (e.g. changing font-size or color) of an HTML selector. So, I thought maybe there was an issue with the link between my base-generic.html and my stylesheet. However, commenting out the link clearly makes a huge difference in the appearance of my page, so the stylesheet is definitely properly linked. I have no clue why my CSS is not being reflected on the page. I don't think it's a Bootstrap issue since making all the text in my p selector green … -
How to order by fields in Django
For my case it will be very important to get the order right. I need to sort my MonthlySpending objects by its index. I have tried the dictsort from django template but does not work. I have also included the ordering in my models, however, the ordering is not shown in the HTML but it does show in the admin. Are there anyways i can sort my objects by its index? HTML {% for month in object.monthlyspending_set.all|dictsort:"index" %} <tr class="yeardata "> <td>{{ month.name }}</td> <td>$ {{ month.monthly_income }}</td> <td>$ <a href="{% url 'finances:detail' month.slug %}">{{ month.target_savings }}</a></td> <td>$ {{ month.actual_savings }}</td> <td>{{ month.percentage_met }} %</td> </tr> {% endfor %} Models.py class MonthlySpending(models.Model): name = models.CharField(max_length=100) annualspending = models.ForeignKey(AnnualSpending, on_delete=models.CASCADE) index = models.IntegerField() slug = models.SlugField() objects = models.Manager class Meta: ordering = ['index'] -
How to Perform a Delete operation in Django rest Framework?
Hello Iam new in Django rest framework,i want to create custom delete funtion to delete .I successfully created create and update as in my below code but i cant create delete function.But i searched lots of article about it but i havent found .Hopefully U will help me . models.py model for User class User(AbstractUser, BaseModel): full_name = models.CharField(max_length=64) addresss=models.CharField(max_length=40) phoneno=models.IntegerField(null=True, blank=True) email=models.EmailField() password=models.CharField(max_length=40) re_password=models.CharField(max_length=40) gender=models.IntegerField(choices=gender_choice,default='0') models for student register class Student(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) father_name=models.CharField(max_length=64) mother_name=models.CharField(max_length=60) date_of_birth=models.DateField(null=True) def __str__(self): return self.user.full_name Serializer.py class StudentSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model=Student fields=( 'id', 'father_name', 'mother_name', 'date_of_birth', 'user', ) serializer.for user class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields=('full_name','id','addresss','phoneno','email','password','re_password','gender') views.py class StudentViewset(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer http_methods = ['get', 'post','put',] def create(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) row = serializer.data user = row['user'] if user['password'] != user['re_password']: return Response({'message':'pw not matched'}) email = username = row['user']['email'] user, created = User.objects.get_or_create(email=email, defaults={'full_name':row['user']['full_name'],'addresss':row['user']['addresss'], 'phoneno':row['user']['phoneno'],'password':row['user']['password'] ,'re_password':row['user']['re_password'], 'gender':row['user']['gender'] ,'username':username}) if created == False: return Response({'message':'Sorry the student is already registered.'}) student = Student.objects.create(user_id=user.id) return Response(row) def update(self,request,*args,**kwargs): instance=self.get_object() serializer=StudentUpdateSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.data if data.get('father_name', False): instance.father_name = data.get('father_name') if data.get('mother_name', False): instance.mother_name = data.get('mother_name') instance.save() return Response(serializer.data) -
Permission for field in Wagtail Page
How can permissions be applied to individual fields of a Wagtail page? Let's say we have a page like this one: class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] Everyone should be allowed to edit the title - but only users with a certain permission should be able to alter the body. -
Django celery task getting stuck on blocking the chain
I am using the celery with python 3.5. I am using chain to perform serialize task and I only want to process single task at a time. The follow piece of code works fine: @shared_task(name='dummy1') def dummy1(val): logger.info('received: ' + val) with RedisLock('testing.pid',60*60): try: logger.info("Lock acquired by " + val) res = chain(dummy2.s(val), dummy3.s(val)).delay() logger.info("Lock released") except Exception as e: logger.exception(str(e)) @shared_task(name='dummy2') def dummy2(val): logger.info('Dummy2 : ' + val) time.sleep(3) logger.info('Dummy2 complete') return None @shared_task(name='dummy3') def dummy3(prev, val): logger.info('Dummy3 : ' + val) time.sleep(3) logger.info('Dummy3 complete') RedisLock is a distributed cache based lock for running a single task at a time. However, when i do: with RedisLock('testing.pid',60*60): try: logger.info("Lock acquired by " + val) res = chain(dummy2.s(val), dummy3.s(val)).delay() res.get() # blocking the process here logger.info("Lock released") the chain does not work as expected and gets crashed very often. -
$nImageInput.fileupload is not a function
I am trying to use the SummernoteInplaceWidget for my django-summernote installation. I am getting the editor to display by including the Bootstrap and Jquery and Summernote Libraries in my HTML header as shown below. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-bs4.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-bs4.js"></script> This works correctly and I get the editor to display as shown below: but when I try to drag and drop an image on the editor, I get the following error message: I'm new to Jquery and Javascript. I've done some searching on this topic and I tried the solution listed here...jQuery-File-Upload - TypeError: $(...).fileupload is not a function But it did not resolve my issue. Thanks in advance for any suggestions. -
Filter an ArrayIngerField using Django
I am new to Django and i need to make a filter comparing arrays of integers. I have: class MyClass(Model): array_int = ArrayField(models.IntegerField()) So I need to do something like # array_int is [5,0,0,0] MyClass.objects.filter(array_int<'{6,0,0,0}') How to make this comparison in django? -
How can I create a csv importer in django?
I have an application in which the database shows people information. I currently import the data from a csv file through the following script: import csv, sys, os dir_projeto = "/home/danilo/Documentos/Projetos/transparencia/transparencia/" sys.path.append(dir_projeto) os.environ['DJANGO_SETTINGS_MODULE']='settings' import django django.setup() from pessoal.models import Pessoa data = csv.reader(open("CC_JUNHO.csv"), delimiter=";") for linha in data: importacao = Pessoa() importacao.matricula = linha[0] importacao.funcionario = linha[1] importacao.cargo = linha[2] importacao.data_admissao = linha[3] importacao.salario_fixo = linha[4] importacao.tota_bruto = linha[5] importacao.total_desconto = linha[6] importacao.liquido = linha[8] importacao.save() However, is it possible to do this import through a view and a django template? Example: The template would have a form to add the csv file, in which it would be imported into the db by the view. It is possible? If yes, how? -
How to store an admin form file in a model text field?
I am pretty new to Django. I need some help. I am working on an admin page that allows me to edit objects. My model has a text field that I want to fill with a file contents which will be uploaded with a FileInput widget in a form. So I want to read the file contents, put it in a string and store it in the model text field. Therefore it should be saved in the database. Any help with this? I dont know how to get the file , read it and store it in my model as string. I am using an AdminForm btw. -
convert pdf to image using pdf url (pdf2image)
images_from_path = convert_from_path(settings.MEDIA_ROOT+'file/some.pdf',100) images_from_path[0].save(settings.MEDIA_ROOT+'image/'+'a.jpg')) I can get or save the images like this. How do I use a pdf file-url(https://example.com/xyz.pdf) to get the images? -
Django restful API - get user id with token
How to obtain User ID from Django API having authentication token? Basically, I want to send authentication token and get back User id. I have tried this solution: How can I return user ID with token in Django? but it is returning token with provided username and password, which is not what I want. -
How to test celery with django on a windows machine
I'm looking for a resource, documentation or advise on how to test django celery on my windows machine before deploying on a Linux based server. Any useful Answer would be appreciated and accepted. -
Django App on heroku :Application Error
im trying to add my django application to heroku but everything went well from migration and migrate commands as well but when i tried to acess the site mxiondrf.herokuapp.com there is a error called Application error here are my logs 2018-07-23T13:59:00.436425+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/api/li st" host=mxiondrf.herokuapp.com request_id=5af5f21f-7e9b-4934-8e84-c6fca34477e1 fwd="103.49.121.34" dyno= connect= service= status=503 bytes= protocol=https 2018-07-23T13:59:00.862661+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favico n.ico" host=mxiondrf.herokuapp.com request_id=5400e512-b34b-47a1-b7c7-d276cc311374 fwd="103.49.121.34" dyno= connect= servi ce= status=503 bytes= protocol=https 2018-07-23T13:59:03.975204+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host =mxiondrf.herokuapp.com request_id=93d450c2-3a0a-44e1-83a7-e9e041c0b628 fwd="103.49.121.34" dyno= connect= service= status= 503 bytes= protocol=https 2018-07-23T13:59:04.353339+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favico n.ico" host=mxiondrf.herokuapp.com request_id=580a6deb-a105-4442-a9fc-01ed7af39811 fwd="103.49.121.34" dyno= connect= servi ce= status=503 bytes= protocol=https if anyone could help me in solving this issue any kind of help is appreciated -
Share data between serializes fields
I have a ModelSerializer class which implements some fields with SerializerMethodField. There are a few fields which calculates currency data according to the rates retrieved from a database if there are, otherwise from a bank API. With current implementation there are a lot of short queries to the database just to retrieve or check a rate. I'm thinking of reducing the number of queries by sharing already calculated data between fields. The code will explain the idea better: class CalcualteSomethingSerializer(ModelSerializer): currency_value_1 = serializers.SerializerMethodField() currency_value_2 = serializers.SerializerMethodField() def get_currency_value_1(obj): if obj.currency_code != 'USD': rate = get_rates('USD', obj.currency_code, obj.date) return calculation_logic1(obj.value, rate) def get_currency_value_2(obj): if obj.currency_code != 'USD': rate = get_rates('USD', obj.currency_code, obj.date) return calculation_logic2(obj.value, rate) I've tried to save the rates into self._kwargs but it reduced a number of queries only for 5 queries.