Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django save relationship data to db
i unable to save data to db class my code is MagicPlanItemCreate(SuccessMessageMixin,CreateView): model = MagicPlanItem template_name = 'magic-plan/magicplanitem/magicplanitemadd.html' fields = ['code','name','unit','category'] success_url = '/magic-plan-item' success_message = "Magic Plan Category was created successfully" def get_context_data(self, **kwargs): context = super(MagicPlanItemCreate, self).get_context_data(**kwargs) context['categories'] = MagicPlanCategory.objects.all() # And so on for more models return context -
Creating user specific form access permissions / validation in django admin
I'm using a 'Task' Model to create operations/administrative tasks in my dashboard. Each task has an assignee, and a reviewer. The assignee completes the task by passing several checks, and the reviewer verifies their work, both of these require each user to edit a check, but neither user should be able to access or modify the other's result. If the assignee views the Task (with checks inline), they should only be able to modify the "result" and "comment" elements of the check, where as the reviewer can only edit the "review_result" and "reviewer_comment" elements. To validate this I need to use the fact that given a check, the current user editing the page is equal to check.task.assignee or check.task.reviewer. I cannot find a simple way to do this, even using django-guardian, as this requires field-level permissions, rather than object level. I considered using modelForm validation, but cannot find a way to access the user from within the model with some hacks such as django-cuser. Is there another architecture which would allow this? The only way forward that I can see is to use django-guardian combined with two checks, a check and a checkReview, and set object level permissions as the … -
Catching error on celery group, instead of individual task
Is it possible to error handling on celery group? instead of using error handle on task individually? I tried on_error method. But when my task appended in group how can i handle specific group element error? I tried using chord but when error occurred chord's callback wont be called. So how can i handle this error? -
Can run server in Docker but can't acces to it (windows DockerTollbox)
I started a Docker server and Kinetic says that my container is runnig. Everything seems okay but i can't access the server via http://127.0.0.1:8000/ Though i can access the server and see my django project if i run server without docker I have not even a idea on what to do Here's Dockerfile FROM python:3.6.8-alpine MAINTAINER Sabir Javadov ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt WORKDIR /Test COPY ./Test /Test RUN adduser -D Sabir USER Sabir Here's docker-compose version: "3" services: test: build: context: . ports: - "8000:8000" volumes: - ./Test:/Test command: sh -c "python manage.py runserver 0.0.0.0:8000" -
Running Django on an Apache server give "ModuleNotFoundError: No module named 'encodings' "
I'm trying to migrate the SQLite db on my Django application to MySQL. For some problem with the MySQL python connector I've decided to upgrade to python 3.6 on the Debian distribution where I'm working. After the migration of the db, I've tried to run the application but I got this error on the apache error-log file: Current thread 0x00007f1488aee780 (most recent call first): Could not find platform independent libraries Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' I've add this in my httpd.conf: ` # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, … -
Drop down widget with adding choices in admin page
i want to create a Drop-Down Widget with choices which can be added in the admin page. I was thinking of creating a model for the choices and registering these in the admin webpage and implementing this model into a Form but i can´t seem to grasp on how to go about solving this. Is my way of thinking in creating a model and implementing it in a Form / ModelForm the right way or is there a easier/better way ? -
Models and authenticate are disabled after importing in Django
I am using a model User and I have to authenticate the email and password for login. When I am trying to import the model it is disabled and also the authentication failed. I have used Django User model and used built in authentication. views.py from django.contrib.auth import login, authenticate # authenticate is diable from registration.models import User # User model is disabled` def signup(request): if request.method == "POST": if (request.POST.get('initial_name') and request.POST.get('first_name') and request.POST.get('last_name') and request.POST.get('hospital_name') and request.POST.get('username') and request.POST.get('password') and request.POST.get('email') and request.POST.get('address') and request.POST.get('zip_code') and request.POST.get('dob') and request.POST.get('gender') and request.POST.get('phone_number')): user = User() user.initial_name = request.POST.get('initial_name') user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.hospital_name = request.POST.get('hospital_name') user.username = request.POST.get('username') user.email = request.POST.get('email') user.password = request.POST.get('password') user.address = request.POST.get('address') user.zip_code = request.POST.get('zip_code') user.dob = request.POST.get('dob') user.gender = request.POST.get('gender') user.phone_number = request.POST.get('phone_number') user.save() return redirect("registration:login") else: return render(request, 'signup.html') class LoginView(TemplateView): template_name = 'login.html' def get_context_data(self, **kwargs): context = super(LoginView, self).get_context_data(**kwargs) return context def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect("registration:prescription") return super(LoginView, self).dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): form = Loginform(request.POST, request=request) if form.is_valid(): user = User.objects.filter(email=request.POST.get('email')).first() if user is not None: if user.is_active: user = authenticate(request, email=request.POST.get('email'), password=request.POST.get('password')) if user is not None: login(request,user) return … -
Importing model in utils.py causes ImproperlyConfigured
I have created a file called utils.py in my Django app, where I keep random classes or functions that do something. I have run into an issue, where I can't import any model in utils.py file. I have models called User which inherit from AbstractUser and it's been said to Django by: AUTH_USER_MODEL = 'main.User' I have also a model called Project. Whenever I type from main.models import Project or User in utils.py I get django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'main.User' that has not been installed Of course main is in installed apps in settings. I have solved this before by using get_user_model() for User, but there is no such a function to get a Project. -
Usage of {{ and {% in django?
In views.py I passed 'key_tp_list': tb_list,'key_tb_list': tb_list. Their type is dictionay list. Then in my html, I wrote : {% for i in range(key_tp_length) %} <li>{{ key_tp_list[i].eid }} | {{ dict.user }} | {{ dict.start_time }} | {{ dict.note }}</li> {% endfor %} And it turned out to have 2 errors : I can't use a range(key_tp_length) in {% %}, neither I can use a key_tp_list[i] in {{ }}. How can I fix this? -
Pytest django ModuleNotFoundError: No module named *
What could be the problem, pytest raises - ModuleNotFoundError: No module named 'order', but django server runs perfectly *settings.py INSTALLED_APPS = [..., "order"] Structure: app/ order/ apps.py __init__.py settings.py __init__.py manage.py tests/ pytest.ini It works if use INSTALLED_APPS = [..., "app.order"], how could I use just "order"? -
How does Django, sorl thumbnail can display images for AMP <amp-img src="{{}}...?
I'm trying to display thumbnails on amp website. I changed " This following code doesn't work. {% thumbnail item.image "100x100" crop="center" as im %} <amp-img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"></amp-img> {% endthumbnail %} This works. {% thumbnail item.image "100x100" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} But " -
How to Override Djoser Login API?
I need to return value more than auth token after user djoser login, without customize their original code. So, now the login API if success it returns token. I need to return spec value that will query on it on other table and if found it will returns true also. How can I do that? please anyone can help. -
Import Error: No Module named
I am getting this error when I am trying to execute a python file utils.py. Not sure if this is related to Sublime Text or Python. The file utils.py has been created inside the Django app and in the file I am trying to import some modules and this is where I am getting this error. Rest of the files are working just fine. Also I have checked that I am getting the "untracked" notification on the file from Sublime Text. -
Django python inserting multiple rows using serializer is_valid(raise_exception=True) , insert each object
Wanted to Insert multiple rows to the database but I am having error in if user_serializer.is_valid(raise_exception=True): I dont know if I made this wrong at this line user_serializer = UserSerializer(data=each_employee_data). The goal is to insert each_employee_data objects to the database, what I did wrong on my code below ?. Object to insert (each_employee_data data) [ { 'mname':'Tap', 'password':'helloworld12345', 'fname':'Jelord Rey', 'is_applicant':True, 'email':'jelordreygulle@gmail.com', 'lname':'Gulle' }, { 'mname':'van', 'password':'asdasdasdas', 'fname':'anthonasdasdasd', 'is_applicant':True, 'email':'jelordrey@gmail.com', 'lname':'asdas' } ] code def post(self, request, format=None): data = request.data print("Data::" , data) for each_employee_data in data: each_employee_data["verification_code"] = verification_code(self) password = hashers.make_password(each_employee_data["password"]) each_employee_data["password"] = password print("hahahahaha", each_employee_data) user_serializer = UserSerializer(data=each_employee_data) if user_serializer.is_valid(raise_exception=True): if not each_employee_data["is_applicant"]:#company company_serializer = CompanySerializer(data=data) if company_serializer.is_valid(raise_exception=True): user_ins = user_serializer.save(password=password) company_serializer.save(user=user_ins) else: applicant_serializer = ApplicantSerializer(data=data) if applicant_serializer.is_valid(raise_exception=True): user_ins = user_serializer.save(password=password) applicant_serializer.save(user=user_ins) send_confirmation.delay(data) if not user_ins.is_applicant: send_business_confirmation.delay(data) -
BaseCommand for delete data from specific model by argument in parser
I need a BaseCommand that deletes entries from the specified model in the parameters. Run this: ./manage.py delete_data_model app.shop # delete_data_model.py from django.core.management.base import BaseCommand, CommandError from django.db.transaction import atomic class Command(BaseCommand): help = "Deleted data from model" def add_arguments(self, parser): parser.add_argument('model', required=True, type=str) def handle(self, *args, **options): self.stdout.write("Begin") with atomic(using='default'): try: path = options['model'] app, model = path.split('.')[:2] from (app) import (model) as Model # ??? how do this Model.objects.all().delete() except Exception as e: raise CommandError("Error {}".format(e)) self.stdout.write("Complete") I expect empty table Shop. -
website which uploads wireshark csv file and provide analysis
I am building a project which upload wireshark csv file which has domain addresses mix with ip address, now i want first to separate the domain names then categories this websites like fitness, health, etc and also the pattern in which sites are accessed, all the things we can find from that file in graphical format that also for each separate user where he can add up more files also -
I am getting TypeError:"int() argument must be a string, a bytes-like object or a number, not 'Question'"
I am getting error when I try to fetch Question object from my Choice object. The error is : int() argument must be a string, a bytes-like object or a number, not 'Question' I have two Models: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def __str__(self): return self.question_text class Choice(models.Model): choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE) def __str__(self): return self.choice_text Here is my view : @api_view(['POST', ]) def selectChoice(request): try: choice_id = request.query_params.get('choice_id') selected_choice = get_object_or_404(Choice, id=choice_id) selected_choice.votes += 1 selected_choice.save() questions = get_object_or_404(Question, id=selected_choice.question) serializer = QuestionWithAnswer(questions) return Response(serializer.data) except ValueError as e: return Response(e.args[0], status.HTTP_400_BAD_REQUEST) -
Add a new field on my model and on my user interface
I'm new to Django and Angular, I've just started my internship and I'm working on an app that uses Angular for the front and django for the backend. I've added a new field to one of my models, I did the migration, but I don't know what the next step is going to be? Do I need to add something in the views? My goal is to also add this field on the user interface so that the user can select the correct info. -
Django: How to get a Object over a Object related with Foreign Keys
I'm doing a webapp with django. At the moment i'm a bit stuck with DetailViews and displaying data from different models in relation to Foreign Keys. For excample i have the following models: - Library - Book (related to Library) - Page (related to Book) At the moment I have a DetailView with the model Book. I managed to access the Book with "_set.all". Now I also need to access the Page of that Book. Models.py: class Library(models.Model): name = models.CharField(max_length=50) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Book(models.Model): title = models.IntegerField() library = models.ForeignKey(Library, on_delete=models.CASCADE) class Page(models.Model): content= models.CharField(max_length=50000) book = models.ForeignKey(Book, on_delete=models.CASCADE) Views.py class TableDetailView(User, LoginRequiredMixin, DetailView): model = Library template_name = 'library/table.html' context_object_name = 'library' table.html <ul> {% for book in library.book_set.all %} <li>{{ book.title }}</li> {% endfor %} </ul> <!-- Works until here --> <ul> {% for book in library.book.page_set.all %} <li>{{ page.content }}</li> {% endfor %} </ul> How can i get the content of the page displayed on my view? Thanks for any help <3 -
How to have get_or_create() save an object, even if object.attribute passed in doesn't exist
I have a function: podcast_instance = Show.objects.get_or_create(title=parsed_podcast.title day_published=parsed_podcast.title ) It's getting the data from an object (parsed_podcast) being passed in. It has a large number of attributes, depending on the podcast, some are there and some are not. I have a lot of datasources being passed into the 'Podcast' object, so I'd like for my function to save what is available, and if there is nothing available, or 'parsed_podcast object has no attribute x' then to just save 'nothing' into that attribute and carry on. The model Show allows for these attributes to have no value. However, get_or_create just throws an AttributeError and stops, and if I put it in a Try block and print the error this way: try: podcast_instance = Show.objects.get_or_create(title=parsed_podcast.title) except AttributeError: Exception It still does not save the data. How can I create an object and just save what is available? -
Check object permission for user with global permission
How i can check permission to object for user with global permission ? joe = User.objects.get(username="joe") assign_perm('parse.show_company', joe) # assign global permission company = Company.objects.get(id=id) joe.has_perm('parse.show_company', company ) # check permission for object, return False -
Connecting to django server with google cloud database
Hey I am trying to connect to google cloud database using Django and a whole lot of errors just popped out and I don't know how to deal with them. Basically I have created virtual env outside of my source folder (virtualenv --python=python3 ../ge-env`), then loaded that env with source ../ge-env/bin/activate, installed all the dependencies using pip3 install -r requirements.txt, then chmod 777 /var/www/django, then ./manage.py collectstatic and then the part where it errored: ./manage.py migrate. /Users/juriczech/Documents/work/ge-env/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) System check identified some issues: WARNINGS: integrations.MapwizeConfig.event: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. integrations.TitoConfig.event: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. Traceback (most recent call last): File "/Users/juriczech/Documents/work/ge-env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/Users/juriczech/Documents/work/ge-env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/Users/juriczech/Documents/work/ge-env/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/Users/juriczech/Documents/work/ge-env/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, … -
How to make function using update_or_create?
I'm setting two Serializers. TimesheetEntrySerializer and TimesheeSerializer. TimesheetEntrySerializer is also inline and is made it in admin.py file. I need help to make a funcion with update_or_create for the two models. This is the API This is the API "results": [ { "id": 46, "date": "2019-04-10", "user": { "pk": 4, "username": "Boris", "email": "", "first_name": "", "last_name": "" }, "total_hours": "9.00", "timesheet_entries": [ { "hours": "9.00", "project": { "id": 8, "client": { "id": 3, "created": "2019-04-02T13:49:21.437562Z", "modified": "2019-04-02T13:49:21.437584Z", "name": "Sp33d" }, "roles": [ { "name": "Development" }, { "name": "Design" }, { "name": "Testing" } ], "created": "2019-04-02T14:35:13.410254Z", "modified": "2019-04-02T14:35:13.410277Z", "name": "Speed-HR", "type": "internal" }, "project_role": { "name": "Development" } } ] }, This is the code where I have to do update_or_create class TimesheetEntrySerializer(ModelSerializer): project = serializers.PrimaryKeyRelatedField( queryset=Project.objects.all(), label=_("Project"), style={"value_accessor": "id"} ) project_role = serializers.PrimaryKeyRelatedField( queryset=ProjectRole.objects.all(), label=_("Project role"), style={"value_accessor": "id"} ) class Meta: model = TimesheetEntry fields = ['hours', 'project', 'project_role'] def to_representation(self, instance): result = super().to_representation(instance) result['project'] = ProjectSerializer(instance=instance.project).data result['project_role'] = ProjectRoleSerializer(instance=instance.project_role).data return result class TimesheetSerializer(ModelSerializer): user = serializers.PrimaryKeyRelatedField( queryset=User.objects.all(), label=_("User"), style={"value_accessor": "pk"} ) timesheet_entries = TimesheetEntrySerializer(many=True) class Meta: model = Timesheet fields = ['id', 'date', 'user', 'total_hours', 'timesheet_entries'] def to_representation(self, instance): result = super().to_representation(instance) result['user'] = UserDetailsSerializer(instance=instance.user).data … -
Authintication problem when accessing MSSQL from Django
I have been trying to link my mssql database to Django. When I run the Django server I get the error below. For normal query out of Django, it works fine, however, the Django doesnt even connect. File "C:\ProgramData\Anaconda3\lib\site-packages\sql_server\pyodbc\base.py", line 307, in get_new_connection timeout=timeout) django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'EMEA\\kmoh'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'EMEA\\kmoh'. (18456); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") Windows 10 django-pyodbc-azure: version 2.1 Django 2.1 Pyodbc: 4.0.25 my Django settings.py looks like this: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'xxx', #has been hide for this post 'PORT': '1433', 'NAME': 'BBL_Result', #'ODBC_DSN': 'BBL' 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'extra_params': "Persist Security Info=FALSE;server=xxx", #has been hide for this post }, }, } -
how To resolve django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account django 1.5
File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 338, in execute django.setup() File "/strong textusr/local/lib/python2.7/dist-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 89, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account