Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call a view with many parameters
I am trying to create a very simple custom view for my application. Lets imagine I have a simply model: class Person(models.Model): Name = models.CharField(max_length = 255) pass class Company(models.Model): Title = models.CharField(max_length = 255) pass I would like to display a list of objects. On one url - list of person, on another - list of companies. So I create simply views: def PersonListView (request): _persons = Person.objects.all() context = { "object_list": _persons } return render (request, "PersonListView.html", context) def CompanyListView (request): _companies = Person.objects.all() context = { "object_list": _companies } return render (request, "CompanyListView.html", context) Then add path to urls - /Person for list of persons and /Company for list of companies. urlpatterns = [ path('/Person', PersonListView), path('/Company', CompanyListView) ] All working well. But I already have a question 1. Why my view function have a request variable, but I can call this function from urls without defining this variable? 2. Why I can't use this syntax path('/Person', PersonListView**()**)? What is wrong with this brackets? And another part of my question. But then I decided to make some refactoring - I intended to use one view both for person and companies, so I have to pass a variable … -
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured - Scraper
When I try to run my scraper in Django I get the following error. This happened when I tried to put the scraped data into the database using the built-in Django models. traceback and error: /usr/bin/python3.6 /home/xxxxxx/Desktop/project/teo/movierater/scrap.py Traceback (most recent call last): File "/home/xxxxxx/Desktop/project/teo/movierater/scrap.py", line 7, in <module> from teo.movierater.api.models import * File "/home/xxxxxx/Desktop/project/teo/movierater/api/models.py", line 3, in <module> class Author(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I put it in bin/activate: export DJANGO_SETTINGS_MODULE=mysite.settings Here is the code snippet from scraper.py: import django import os import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from teo.movierater.api.models import * os.environ['DJANGO_SETTINGS_MODULE'] = 'movierater.settings' django.setup() My project structure and the settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'movierater.api', ] wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movierater.settings') application = get_wsgi_application() -
504 Gateway Time-out nginx/1.10.3 (Ubuntu)
I'm trying to host django 1.11 application on ubuntu 16.4 server using Nginx. But After running the server I'm getting 504 Gateway Time-out here is my all port log Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN 3209/redis-server 1 tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 15218/nginx -g daem tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1204/sshd tcp6 0 0 :::9200 :::* LISTEN 28810/java tcp6 0 0 :::9300 :::* LISTEN 28810/java tcp6 0 0 :::22 :::* LISTEN 1204/sshd udp 0 0 0.0.0.0:68 0.0.0.0:* 963/dhclient Nginx error.log *1 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 118.179.95.25, server: 18.136.204.142, requ$ 2019/07/24 18:13:13 [error] 15221#15221: *1 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 118.179.95.25, server: 18.136.204.142, requ$ 2019/07/24 18:20:17 [error] 15485#15485: *1 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 118.179.95.25, server: 18.136.204.142, requ$ any one have any idea about this issue? any sort of help will be appreciated -
How to compress images before uploading them to Amazon s3 using django storages and django rest framework?
I'm trying to compress the images before uploading them to the amazon s3 server, but I couldn't do it, I used 'PIL', to do it, but it didn't work This is the code I used with the library 'PIL': from io import BytesIO from PIL import Image from django.core.files import File def compress(image): im = Image.open(image) im_io = BytesIO() im.save(im_io,'PNG', quality=70) new_image = File(im_io, name=image.name) return new_image class MyModel(models.Model): file = models.FileField(blank=True, null=True, validators=[validateFileSize]) def save(self, *args, **kwargs): new_image = compress(self.file) self.file = new_image super().save(*args, **kwargs) -
Django - how do I override default date formats per locale?
We are using Django 1.11 for Speedy Net. I want to override the default values of DATE_FORMAT and MONTH_DAY_FORMAT in English, but keep the default values (or define them again) in Hebrew. So they will not be the same and will not be identical to Django's default values. In English we will have: DATE_FORMAT = 'j F Y' MONTH_DAY_FORMAT = 'j F' And in Hebrew: DATE_FORMAT = 'j בF Y' MONTH_DAY_FORMAT = 'j בF' The template currently looks like this: {% if can_view_profile and user.date_of_birth %} {% if can_view_dob_day_month or can_view_dob_year %} <tr> <th>{% if can_view_dob_day_month %}{% trans 'Birth Date' %}{% elif can_view_dob_year %}{% trans 'Birth Year' %}{% endif %}</th> <td> {% if can_view_dob_day_month and can_view_dob_year %} {{ user.date_of_birth|date:settings.DATE_FORMAT }} {% elif can_view_dob_day_month %} {{ user.date_of_birth|date:settings.MONTH_DAY_FORMAT }} {% elif can_view_dob_year %} {{ user.date_of_birth|date:'Y' }} {% endif %} </td> </tr> {% endif %} {% endif %} And I want it to display the dates in these formats in each language. How do I do it? -
Restrict or check for multiple data entries before saving in Django
How can restrict or checking data entries before saving? Example So i have different Dogs who are eating Meals with different Sizes (in Gramm) and different Foodtypes (Pork, Beef etc.). models.py class Dog(models.Model): name = models.CharField(max_length=255) meal = models.ManyToManyField('Meal') def __str__(self): return self.name class Meal(models.Model): food = models.ForeignKey('Foodtype', null=True, blank=False, on_delete=models.SET_NULL) min_g = models.PositiveIntegerField() max_g = models.PositiveIntegerField() def __str__(self): return 'Meal: %s Size: %s g to max. %s g' % (self.food, self.min_g, self.max_g ) class Foodtype(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name Every Time i enter a new Dog i also can create a new Meal. For Instance i added Harry (Dog.name) who is eating Beef (Foodtype.name) of a Size min. 200 (Meal.min_g) gramm to 300 (Meal.min_g) gramm So in my Meal Table is now a Entry of Beef, 200, 300 But Harry the Dog can have multiple Meals so i choose also Pork, 200, 300. If a other user now enters a new Dog who is eating exactly the same, the user could choose the data-point Beef, 200, 300 but he could also easily end up with a double entry by accident because it is a many-to-many relation (see following picture). On the Other Hand i need this … -
How to create User and User Profile in a single Django Admin form
I am struggling to figure out how to save User Profile for a new user created within Django Admin. I have a custom User model and a simple user Profile with OneToOneField: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(_('staff'), default=False) is_active = models.BooleanField(_('active'), default=True) ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(_('first name'), max_length=80, blank=False) last_name = models.CharField(_('last name'), max_length=80, blank=False) ... I have the following user creation form: class UserAdminCreationForm(forms.ModelForm): password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput ) first_name = forms.CharField(label="First name") last_name = forms.CharField(label="Last name") class Meta: model = User fields = ("email",) def save(self, commit=True): user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user My admin Add user form is rendered correctly and includes fields from both User and Profile models. After saving the form, a new user and a new profile are created in the database. However, the first_name and last_name fields in profile table are empty. What I need to do to ensure that profile is saved together with the new user? -
when Deploying a django project the site doesn't load as it's not there?
I tried deploying a project on ubuntu machine on AWS but the site doesn't load as it's not there. I followed this video with slight changes as the machine was already set up and I took the ssh key and connected here's my folder structure of the project /Eyelizer /Eyelizer /App1 /App2 /Eyelizer /etc The commands I followed sudo apt-get install python-pip python-dev nginx git Y sudo apt-get update sudo pip install virtualenv git clone https://github.com/mruanova/zillow.git cd Eyelizer cd Eyelizer virtualenv venv source venv/bin/activate pip install -r requirements.txt pip install django bcrypt django-extensions pip install gunicorn cd zillow sudo vim settings.py # Inside settings.py modify these lines allowed host public IP address I for INSERT i ALLOWED_HOSTS = ['ip_address'] Save your changes and quit. ESC :wq cd .. gunicorn --bind 0.0.0.0:8000 Eyelizer.wsgi ctrl+c sudo vim /etc/systemd/system/gunicorn.service i [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/Eyelizer/Eyelizer ExecStart=/home/ubuntu/zillow/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/Eyelizer/Eyelizer.sock Eyelizer.wsgi:application [Install] WantedBy=multi-user.target ESC :wq sudo systemctl daemon-reload sudo systemctl start gunicorn sudo systemctl enable gunicorn sudo vim /etc/nginx/sites-available/Eyelizer i server { listen 80; server_name ip_address; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/Eyelizer/Eyelizer; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Eyelizer/Eyelizer/Eyelizer... } } … -
Has anybody experience with the django-star-ratings plugin from wildfish?
I want to use a star rating system but I'm a bit overwhelmed. I found this django plugin: https://django-star-ratings.readthedocs.io/en/latest/?badge=latest%2F# I have a form where a user can rate a product. The user should be able to rate the product by clicking on the stars(with hower effects would be nice). Then this rating value (0-5) should be saved in my database. Currently I only have a field where a number can be entered and with a post request I save the data to my database. I also show all the reviews on my product page and it would be idealy when I also could use this plugin. So if there is someone that has experience with this plugin...is it possible to do all of this stuff with this plugin? Please let me know if you need more information. At the moment i use a combination of HTML CSS and JavaScript to show the stars on my product page but I think there is a more elegant slution and additionally I have no idea how I can implement that the users are capeable of clicking on the stars in the review form with my current solution. -
Django GET API for image field from different model
I am trying to get the image url from some model. I have made 2 models: Restaurant model: class Restaurant(models.Model): from location.models import Area from business.models import Business name = models.CharField(verbose_name=_('Name'), max_length=255, unique=True) address = models.CharField(verbose_name=_("Address"), max_length=255) phone = models.CharField(verbose_name=_('Phone Number'), max_length=255) email = models.EmailField(verbose_name=_('Email'), max_length=255, blank=True, null=True) website = models.URLField(verbose_name=_('Website / Online Listing Link'), max_length=255, blank=True, null=True) is_active = models.BooleanField(verbose_name=_("Is Active?"), default=True) is_veg = models.BooleanField(verbose_name=_('Is Veg?'), default=True) class Meta: verbose_name = 'Restaurant' verbose_name_plural = 'Restaurants' And Restaurant Image model: class RestaurantImage(models.Model): image_type = models.CharField(verbose_name=_('Image Type'), choices=IMAGE_TYPES, max_length=255, default=RESTAURANT) restaurant = models.ForeignKey(verbose_name=_('Restaurant'), on_delete=models.PROTECT, to=Restaurant) image = models.ImageField(verbose_name=_('Select Image'), upload_to='media/') def __str__(self): return self.restaurant.name + " - " + IMAGE_TYPES_DICT[self.image_type] class Meta: verbose_name = 'Restaurant Image' verbose_name_plural = 'Restaurant Images' I need to get the image of the restaurant, so I tried to get the image by property method but got UnicodeDecodeError. @property def images(self): images = [] for i in RestaurantImage.objects.filter(restaurant=self.id): images.append(i.image) return images Please help me in getting the image url. Thank you. -
django REST API calls scripts from different python environment
I have a django rest API which would allow to call different prediction method. These methods/scripts are in different conda environment. I can certainly work with one enviroment script, by activating the enviroment of that script and run django service in it. But I am not sure how to do it for another script. My last resort would be to run two django services in different enviroment settings, but looking for a better approach. -
The view news.views.Comment didn't return an HttpResponse object. It returned None instead
I am making it possible to comment on the article and I have a problem "The view news.views.Comment didn't return an HttpResponse object. It returned None instead." I tried to add HTTPresponse but nothing comes out where I have to else I return everything but still this error views.py def Comment(request): if request.method == 'POST': comment = Comments(request.POST) name = request.POST['name'] text = request.POST['text'] context = { 'name': name, 'text': text, } if comment.is_valid(): comment.save() return render_to_response(request, 'news/post.html', {'comment': comment}) else: return render_to_response(request, 'news/post.html') post.html <form method="post" action="{% url 'comment' %}"> {% csrf_token %} <input type="text" name="name" value="{{ name }}"> <input type="text" name="text" value="{{ text }}"> <input type="submit"> </form> {% for comment in object_list %} <h1> {{ comment.name }} </h1> <h1> {{ comment.text }} </h1> {% endfor %} forms.py class Comments(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = Comment fields = ('name', 'text') models.py class Comment(models.Model): name = models.CharField(max_length=100) text = models.TextField(default='') dates = models.DateTimeField(auto_now=True) class Meta: ordering = ['-dates'] def __str__(self): return self.name -
How can we use Django LiveServerTestCase with Selenium to test https urls
Our end-to-end tests use Django's LiveServerTestCase with Selenium. So far we have only been able to run these on insecure urls. However, some of the libraries that we use (Square) require a page to be on https even in sandbox mode. Does anyone know if it is possible to enable https on a LiveServerTestCase? If not, does anyone have a working workaround for this? I'm trying to avoid running a separate https proxy on our build box, but it seems like it might be the only way. -
How to calculate time interval using Django models
Django Project: Countdown! I have a countdown on my html page, but everytime I refresh the page it restarts the countdown. So everytime I refresh the page I have to pass a time interval (in seconds) to my html page in order to take time from the counter. class Timer(models.Model): timeNow = models.TimeField(auto_now_add=True) time_interval = models.IntegerField(default=0) I have tryied in my views.py file: Timer.time_interval = Timer.timeNow - timezone.now() seconds = Timer.time_interval return render(request, 'countdown.html', {'time': seconds }) how do I pass a time interval in seconds to Timer.time_interval since it gives me an HH:MM am format? -
Django REST - queryset order_by doesn't work in descending order
Currently I'm learning Django and Django Rest framework and I am working on an API project. The project is about returning simple statistics about text records from database. I want to list ten most common words from the database. This is models.py file: from django.db import models class Word(models.Model): word = models.CharField(max_length = 100) word_count = models.IntegerField() class Meta: db_table = 'djangorest_word' managed = False And this is view.py file: from rest_framework.response import Response from rest_framework import generics from djangorest.api.models import Word, Author, WordPerAuthor from djangorest.api.serializers import WordSerializer, AuthorSerializer, WordPerAuthorSerializer from django.db.models import Sum class WordList(generics.ListAPIView): queryset = Word.objects.values('word', 'word_count').order_by('word_count').annotate(Sum('word_count'))[:10] serializer_class = WordSerializer def get(self, request): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) data = {obj['word']: obj['word_count'] for obj in serializer.data} return Response(data) Ascending order works properly: { "Karolina": 1, "hand": 1, "correctness": 1, "inform": 1, "memory": 1, "Possible": 1, "modules": 1, "guy": 1, "pitching": 1, "expensive": 1 } But whenever I use order_by('-word_count') or order_by('word_count').reverse() there isn't ten words but only two: { "the": 1120, "to": 1104 } I don't understand why order_by works properly in ascending order but doesn't work in descending. Am I missing something? Is there other way to achieve receiving top ten values? -
Testing django user login failing to redirect appropriately (url issue?) with selenium and pytest
I've got a project that I'm having some issues with and I think it might have to do with the URL's. My project URL's look like this: urlpatterns = [ path("", include("dock.urls"), name="dock"), path("admin/", admin.site.urls, name="admin"), ] My app (named dock) URL's look like this: urlpatterns = [ path("", views.dock, name="dock"), path( "login/", LoginView.as_view(template_name="dock/login.html"), name="login", ), path("dock/", views.dock, name="dock"), path( "logout/", LogoutView.as_view(template_name="dock/thanks.html"), name="logout", ), ] My views.py is pretty simple and only has the dock method in it since I use the Django built-ins for logging in and logging out: @login_required(login_url="dock:login") def dock(request): if not request.user.groups.all(): return render(request, "dock/no_docks.html") return render( request, "dock/dock.html", { "apps": App.objects.filter( groups__in=request.user.groups.all() ).distinct() }, ) My test looks like this (I create the user in the setUp method and can confirm it is all setup properly): def test_log_in_for_userone(self): # Opening the link we want to test self.client.get(self.live_server_url) assert "log in" in self.client.page_source time.sleep(2) self.client.find_element_by_id("id_username").send_keys("userone") self.client.find_element_by_id("id_password").send_keys("thepassword") self.client.find_element_by_id("log_in").click() time.sleep(2) # Check the returned result assert "You are logged in!" in self.client.page_source When I run this test - it fires everything up fine, opens firefox, enters the username and password and the user is appropriately logged in (according to the timestamps in the database); however the browser itself … -
Docker Compose with Django error when I add new command to compose
Docker compose doesn't recognize an echo command. Recently I added the command: echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', '2222bbbb')" | python manage.py shell Compose code: version: '2' services: postgres: image: postgres container_name: app_postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres django: image: python:3.6.8 container_name: app_django environment: - DJANGO_SETTINGS_MODULE=project.settings_staging - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_HOST=postgres working_dir: /code volumes: - ./:/code - ./requirements.txt:/code/requirements.txt ports: - 6000:8000 command: bash -c "pip install -r requirements.txt && python manage.py migrate --noinput && echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', '2222bbbb')" | python manage.py shell && python manage.py test" depends_on: - postgres When i execute this compose Django finished with next message: app_django | Apply all migrations: account, admin, auth, authtoken, contenttypes, filters, sessions, sites, users app_django | Running migrations: app_django | No migrations to apply. app_django | from app_django exited with code 0 Django doesn't recognize the echo command -
How to Assign States to Viewers of Django Web Application?
Problem Statement I'm working on building out a single-page Django web app and am trying to implement the following functionality: - All viewers of the page are associated with a state. There are buttons on the page which enable viewers to change their state. - The application stores a list of all current viewers of the page, and their associated states. Whenever a user changes their state, this stored list of viewers updates with this new information. - The application should display how many people are online (viewing the page) at a given time. Blockers I'm unsure of how to collect a list of all current viewers of a page in Django, nor how to collect how many users are currently viewing the page. Ideally, my application would not require a login to use: therefore, I'd rather either associate viewer state with a user object that doesn't require sign-in, or not associate viewer state with a user object (I'm still new to user objects though, so forgive me if this point doesn't make complete sense). What I'm Looking For A discussion of higher-level strategies which I can use to implement this functionality, or other places to look to gain insight … -
How to load a form with options from a querryset in Django
I am trying to load a form with user payment options, so this is needing a query set from the users profile. I have tried initializing the form (below code) with user being required. The issue is if I make self.options when I am initializing. I have also tried creating the choice_field class ListPaymentOptionsForm(forms.Form): choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=options) def __init__(self, user, *args, **kwargs): self.options = list(UserPaymentOption.objects .values_list('last_four', 'last_four') .filter(user=user, active=True)) super(ListPaymentOptionsForm, self).__init__(self, *args, **kwargs) The above code gives this error: choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=options) NameError: name 'options' is not defined Then I have tried adding the options on the view instead like this form = ListPaymentOptionsForm(user=request.user) form.fields['choice_field'].choices = list(UserPaymentOption.objects .values_list('id', 'last_four') .filter(user=request.user, active=True)) This causes an error with the form being used on post, it seems like because it is trying to validate the options is allowed but in the actual form the option is set. The reason I believe this is the problem is this is what the form returns as form=ListPaymentOptionsForm(request.POST) print(form) This returns: Choice field:Select a valid choice. 54 is not one of the available choices. Any input on this would be very appreciated. Thanks. -
How to login with different user type in django?
How can I properly authenticate a type of user based on the models below. It only seems to be working for Manager type therefore I wonder what is wrong about my implementation. models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class User(AbstractUser): is_customer = models.BooleanField(default=True) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customers') bio = models.CharField(max_length=200) def __str__(self): return self.user.username class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='managers') company_name = models.CharField(max_length=50) def __str__(self): return self.user.username forms.py from django.contrib.auth.models import User from django import forms from django.contrib.auth import ( authenticate, login, ) class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('This user does not exist') if not user.check_password(password): raise forms.ValidationError('Incorrect password') if not user.is_active: raise forms.ValidationError('This user is not active') return super(UserLoginForm, self).clean(*args, **kwargs) views.py from django.contrib.auth import ( authenticate, login, ) from django.shortcuts import ( render, redirect ) from user.forms import UserLoginForm def login_view(request): next = request.GET.get('next') form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user.is_active: # Redirect to the appropriate type of … -
How to redirect from a CreateView of model A to another CreateView of a model B while passing key information from model A to the next view?
I am new to Django and do not know what I need to know to do this task. I am tasked with creating a web app that has two models. Model A is the employee and model B is a company that contains many employees. During signup, I have a form for model A. Once model A form is filled out, I need to pass an id from the employee to the company signup url so that when I save the company model to the table, I can make sure that the employee id is stored and so the two tables are related. How do I go about sending the employee_id to the company form page? Do I need to use some sort of redirect? Flow: dashboard/employee_signup -> dashboard/company_signup -> completed_signup I've looked through multiple tutorials on Django and most seem to be too simple to solve what I need done. Here is my EmployeeSignUpView. Right now it redirects to a 'login' page. I need to instead redirect to a CompanySignUpView while passing along an employee_id. A company can't have zero employees, so the first person to signup for the company needs to be stored in the company model. The … -
issues with template after a ajax request in django
i have added like feature to my project ajax and django is perfectly working fine ajax is able to send a request and django is able to recieve it and vice versa but the thing where i'm stuck is i cant update it in my template properly ,i'm able to update the changes but that not happening for all objects whenever i click on like button the count is getting incremented for only one object lets say i have two objects with title facebook and instagram when i click on facebook the count increments to 1 and click the same button it decrements to 0 its perfectly working but when i click the like button for my instagram object instead of updating its own object its is updating the facebook object the facebook likes counts is incrementing/decrementing i'm not sure if the issue is with the template or it is with the ajax part AJAX: $('button').on('click',function(event){ event.preventDefault(); var element=$(this); $.ajax({ url: $(this).attr("data-href"), type:'GET', success:function(response){ // $('#lik').html(response); // console.log(response); // alert(response.message); // alert('Company likes count is now ' + response.likes_count); // document.getElementById('like-count').innerHTML = response.like_count; // $('#like_count').html(response.likes_count); $('#lik').html(response.likes_count); // element.html(' ' + response) } }); }); template : <div class="reaction" > <button … -
Creating a Django object from a dict - obj must be an instance or subtype of type
I'm trying to create an object from a json: r = requests.post(url, headers=headers, data=data) response = r.json() link = MyObject.objects.create(**response['data']) link.save() This generates the following error: web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method web_1 | return getattr(self.get_queryset(), name)(*args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 422, in create web_1 | obj.save(force_insert=True, using=self.db) web_1 | File "models.py", line 106, in save web_1 | super(Issue, self).save(*args, **kwargs) web_1 | TypeError: super(type, obj): obj must be an instance or subtype of type While reponse is valid and everything else seems to be okay, I don't see from where comes this error. Any ideas ? -
How to access the __str__ method of a model via a ForeignKey?
I have created a File model and a Folder model. The File model is connected to the Owner (User) and a Folder via a Foreign key. Now I want to upload the file at the path: 'owner_username/folder_title'. My question is how to access the str method of the Folder model using the ForeignKey, from inside the File Model ? My guess was to set at the FileField the argument upload_to equal to str(folder) but as a result my file was uploaded at:<django.db.models.fields.related.ForeignKey>/graph2.jpg at models.py: class Folder(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length = 20) def __str__(self): return self.title class File(models.Model): owner = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE) folder = models.ForeignKey(Folder, related_name = 'files', on_delete=models.CASCADE, default="") file = models.FileField(upload_to = !!!!?ownername/foldername?!!!!) def __str__(self): return str(self.file) I expect somehow to upload the file at the path that has the following format: nameOfTheOwner/nameOfTheFolder -
django crop already loaded image (without using the input tag)
This solution lets the user crop the image when he uploads it. What I want to do is to let him do the crop on an already loaded image after clicking on a "crop" button for example. The big picture here is that the user uploads a pdf file, I convert it into images, he selects the one he wants to work on, THEN, I need him to select the Region Of interest for me to work on by cropping that selected image. Any approach on how I can do that?