Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django_filters gives an error "QuizFilter has no len()"
I have one filter: import django_filters from .models import Quiz class QuizFilter(django_filters.FilterSet): class Meta: model = Quiz fields = ['title', 'level'] class QuizList(ListView): """List of quizzes + pagination""" model = Quiz template_name = 'quizapp/home.html' context_object_name = 'quizzes' paginate_by = 15 def get_queryset(self): qs = self.model.objects.all() filtered_quizzes = QuizFilter(self.request.GET, queryset=qs) return filtered_quizzes When I open the page I got this error: In templates I just write {% for quiz in quizzes.qs %} and for filtering I use {{ quizzes.form.as_p }} How can I solve the problem? -
Different forms with custom fields creating users in Django
I have two forms. One creates a Client and the other an Employee. The Client has a model Clients and is placed on the Clients group. The Employee is simply a user which is placed on the Employees group. This the Clients model: class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") city = models.CharField(max_length=200, verbose_name="Cidade") postal = models.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], verbose_name="Código Postal") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) And this is the form used to create a client: class SignUpForm(UserCreationForm): address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Av. da Liberdade, 170',})) nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Deve conter 9 dígitos',})) mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Deve conter 9 dígitos',})) city = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Lisboa',})) postal = forms.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'0000-000',})) def clean_nif(self): nif = self.cleaned_data['nif']; if Clients.objects.filter(nif=nif).exists(): raise forms.ValidationError("NIF já existente.") return nif class Meta: model = User fields = ('username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'address', 'nif', 'mobile', 'city', 'postal') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget = TextInput(attrs={'class': 'form-control', 'placeholder': 'Utilizador do Cliente'}) self.fields['password1'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Mínimo 8 caracteres'}) self.fields['password2'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Mínimo 8 caracteres'}) self.fields['first_name'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['last_name'].widget = … -
Error with psycopg2 when execute runserver with DJANGO
I've been all morning trying to start my django project and it seems impossible, everytime I try to start it i get the next error: (venv) djimenez@TADEL-INF:/mnt/c/Users/djimenez/Desktop/bfl$ python bullfrogloader/manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f04b7d7b6a8> Traceback (most recent call last): File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/core/management/base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor self.ensure_connection() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/utils.py", line … -
Why the attributes of a object in __init__() and get_context_data() different?
class SomeView(DetailView) : def __init__(self, *kwargs): print(type(self), dir(self)) def get_context_data: print(type(self), dir(self)) __ init__ does not prints "request attribute" for dir(self), but get_context_data() prints. Why such a difference? -
405 Method not allowed on Django Form POST
everytime I click submit button on my POST form to upload a csv file. I get a code 405 Method not allowed. I already tried changing other importing methods like django_import_export but still get the same response (405). please help! This is my views.py: class AdvisoryView(TemplateView): template_name = 'advisory.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["adv"] = Mobile.objects.all() return context def mobile_upload(request): template = "advisory.html" prompt = { 'order': 'blah' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES('file') if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar='|'): _, created = Mobile.objects.update_or_create( mobile_owner=column[0], mobile_number=column[1], ) context = {} return render(request, template, prompt) and mobile.html look like this, I actually put the form inside a model form. <div class="modal-body"> {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <p>Only accepts .csv file</p> <button type="submit">Upload</button> </form> {% endblock content %} </div> <div class="modal-footer"> and urls.py from django.urls import path, include from . import views from .views import AdvisoryView, HomeView urlpatterns = [ path('', HomeView.as_view(), name='home'), path('advisory/', AdvisoryView.as_view(), name='advisory'), ] -
Django static file 404
Everything works fine when I want to add an image from admin I can see my photo which is visible in the file path field. I am able to add my object but when it comes to running part, No image. "GET /static/static/images/python_logo.png HTTP/1.1" 404 1713 Models.py class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path='static/images') Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] and my folders -
Django Urls Corresponding With Jquery File
I am using Django with a Bootstrap template, that requires Jquery. But I am having trouble with a js file. I created static directory, and static_cdn directory. I am using a Bootstrap 4 template. My project template requires a js file (template doesn't working correctly without this js file) but this js file is not using a valid url; It is calling all my svg files, but with a nonvalid URL. This is my project static files folder : This is my urls.py urls : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^panel/$', panelView, name='panel'), url(r'^pageOne/$', pageOne, name='pageOne'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(os.path.dirname(BASE_DIR), "static"), # '/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = '/evrak/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "evrak") This is my html page : <!-- BEGIN: Vendor JS--> <script src="{% static 'app-assets/vendors/js/vendors.min.js' %}"></script> <script src="{% static 'app-assets/fonts/LivIconsEvo/js/LivIconsEvo.tools.js' %}"></script> <script src="{% static 'app-assets/fonts/LivIconsEvo/js/LivIconsEvo.defaults.js' %}"></script> <script src="{% static 'app-assets/fonts/LivIconsEvo/js/LivIconsEvo.min.js' %}"></script> {% block vendorJS %} {% endblock vendorJS %} <!-- END Vendor JS--> <!-- BEGIN: Page Vendor JS--> {% block pageVendorJS %} {% endblock pageVendorJS %} <!-- END: Page Vendor JS--> Now, Django is able to load … -
Using external API for token based authentication in Django (DRF)
Context My API accepts a jwt-token that I can pass to an external endpoint which will return 401 if invalid/expired or user information if still valid. Based on this I will either return 401 or filtered data belonging to the user. Also, POST request's need to involve writing who this resource belongs to for the GET to work. I tried to do this by overriding the get_queryset and perform_create methods. My viewset looks something like this: class ReportViewSet(AuthorizedUserBasedFilteredViewset): queryset = Report.objects.all() serializer_class = ReportSerializer def perform_create(self, serializer): try: username = self.get_authorized_user()['user']['username'] except Exception as e: return Response({'error': 'Token does not exist'}, status=HTTP_401_UNAUTHORIZED) serializer.save(creatd_by=username) def get_queryset(self): try: username = self.get_authorized_user()['user']['username'] except Exception as e: return Response({'error': 'Token does not exist'}, status=HTTP_401_UNAUTHORIZED) return Report.objects.filter(created_by=username) This doesn't work because get_queryset expects a queryset as response. Questions How do I bubble up the authorize exception in get_queryset? Is there some other method I should be overriding to the authentication entirely? I still need to pass the username recieved to get_queryset for the authentication to be successful Is there a better way to do this? I looked at the RemoteUserAuthenticationBackend but that still involved creation of a User object but for this use case the … -
Python issues with form.cleaned_data.get('username')
When I submit my form, if valid, it should redirect me to my home page but it doesn't due to this line username = form.cleaned_data.get('username'), when I remove it works fine but then again I need that line to get the form data. Here's my code views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') #Where the problem lies messages.success(request, 'Account created!') return redirect('home-page') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) I honestly can't figure out what's wrong with that line of code. I'm using Django v 3.0.4 btw -
Problem loading images from static in a .js file
scripts.js code: $(document).ready(function(){ $('#user').hover(function() { $('#user img').attr('src', "{% static 'images/user_selected.png' %}"); }, function() { $('#user img').attr('src', "{% static 'images/user.png' %}"); }); }); It works fine when I write it directly in my base.html file, but when I place it in an external .js file it fails to load images. Scripts.js file loads but images do not. base.html code: <head> ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'js/scripts.js' %}"></script> ... </head> <body> ... <a href="{%url 'logout' %}">LOG OUT</a> <a id="user" href="#"><img src="{% static 'images/user.png' %}" height="14px" width="14px" id="user-icon" /><span id="user-name"> {{request.user.username}}</span></a> ... </body> -
Celery beat sends task regularly, but celery only processes them from time to time in production
I have a django project with celery integrated using redis. My celery worker works perfectly in local development, and now I'm deploying in production. Before daemonizing the process I want to see how celery behaves in the server. The thing is, celery beat sends the tasks correctly every minute (as I scheduled) but the worker seems not to receive it every time. Sometimes it requires 4/5 minutes until the task is received and processed. How is that possible? I have tried debugging, but there is very few information. see my setup: settings.py CELERY_TIMEZONE = 'Europe/Warsaw' CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' # Other Celery settings CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'predict_assistance.alerts.tasks.check_measures', 'schedule': crontab(minute='*/1'), }, } tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task() def check_measures(): print('doing something') celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('predict_assistance') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() hereby my logs in production: [2020-03-11 16:09:00,028: INFO/Beat] Scheduler: Sending due task task-number-one (predict_assistance.alerts.tasks.check_measures) [2020-03-11 16:09:00,038: INFO/MainProcess] Received task: predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e] [2020-03-11 16:09:00,046: WARNING/ForkPoolWorker-3] doing something [2020-03-11 16:09:00,047: INFO/ForkPoolWorker-3] predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e]: doing something logger [2020-03-11 16:09:00,204: INFO/ForkPoolWorker-3] Task predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e] succeeded in 0.16194193065166473s: … -
Django Form Select Function
I have 2 class views Account And Transaction What I want is whenever I click add transaction and enter the amount type as debit it should Account.Balance = Account.Balance - TransactionAmount and whenever amount type is credit it should Account.Balance = Account.Balance + TransactionAmount. My Template {% load static %} <!DOCTYPE html> <head> <meta charset="UTF-8"> <title>Order Management</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <div class="container"> <ol class="breadcrumb"> <li><a href="/home">Home</a></li> <li> &nbsp; / &nbsp; </li> <li class="active">Add Transaction </li> </ol> </div> {% block title %}{% endblock title %} {% block content %} {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} {% if submitted %} <p class="success"> Your message was submitted successfully. Thank you. </p> {% else %} <form action="" method="post"> <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit"></td> </tr> </table> {% csrf_token %} </form> {% endif %} {% endblock content %} Views def AddAccount(request, fk): if request.method == 'POST': form = AccountModelForm(request.POST) form.customer_id = 5 if form.is_valid(): cd = … -
Form adding new user missing 1 required positional argument in Django
I created a form to add a new user, but it throws an error _wrapped_view() missing 1 required positional argument: 'request'. This is the form: class NewEmployee(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'password1', 'password2', 'email', 'first_name', 'last_name') And this is my view: @login_required(login_url='./accounts/login/') def NewEmployee(request): if request.method == 'POST': form = NewEmployee(request.POST) if form.is_valid(): form.save() return redirect('backend') else: form = NewEmployee() return render(request, 'backend/new_employee.html', {'form': form}) -
Import Django settings from several files
There are lots of hints, why one cannot pull settings from multiple files easily, like so: import base import app1 import app2 import local neither of them sees the settings from the files before and cannot modify them. One solution is to import all the file in chain: local.py: import app2 app2.py: import app1 app1.py: import base It's clumsy. ==== Another solution was to merge all the files into a single one. I actually like this one. I would like to search multiple directories (OK, at least one) for *.py files, sort them by filename and import/merge them, so: base.py -> 000_base.py local.py -> zzz_local.py ensure that base is first, local is last, the order of the other ones do not matter. Is there some Django tool / framework / model, that implements this already or, at least, helps? Thanks -
How to redirect to a different page in Django when I receive an input from a barcode scanner?
The whole project is as follows: I'm trying to build a Django based web-app for my college library. This app when idle will be showing a slideshow of pictures on the screen. However when an input is received from the barcode scanner, it is supposed to redirect it to a different age containing information related to that barcode. I'm not able to figure out how to get an input from the scanner and only then redirect it to the page for 3 seconds containing the relevant information, after the interval, it should redirect back to the page containing the slideshow. -
I am having problem : loading static files in HTML code in a Django Project . As I know for a href link we use "{% static 'addressOfFile' %}"
'How to use django template language to load these images in data-zs-src attribute . if it was data-zs-src="images/b1.jpg" then it would be easy like data-zs-source="{% static 'images/b1.jpg' %}" . but I have double quatation inside single quatation . so it is not working . plz help me with right code -
How can I save cloned form elements as Json strings in Django forms?
I have a django project. In one of my forms, I have an attribute which its name is "count" and I have a combobox which its name is "type". I want to show the "type" combobox as many as the number entered in the "count" field. So I cloned the "type" combobox by using jquery clone() function. For ex; If I enter "5" to count field, my view saves only one of the value of combobox values. How can I send these combobox values as a Json string to backend view for saving in only one charField? Here is my jquery code: $(function(){ $("#id_form-0-baglama_sayi").on('change', function(){ var count = parseInt(this.value); for(var i = 0; i < count; i++){ $( "#id_form-0-baglama_sekil" ).clone().appendTo( "#div_id_form-0-baglama_sekil"); } }); }); Here is my view: if form.is_valid(): data_list = form.cleaned_data data_dict = data_list[0] label = list(data_dict.keys()) data = list(data_dict.values()) new_data = Data(author_id = user.id) for i in range(0, len(label)): setattr(new_data, label[i], data[i]) new_data.save() Thank you! -
Styles are missing in angular build while deploying Django
I was developed angular application and take build ng build --prod command before that, I added the "deployUrl": "/static/" inside the angular.json file. after that I copied dist folder files and paste it inside the django static folder. index.html files also changed based on the requirement, pages are working fine but "styles": [ "src/styles.scss", "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/font-awesome/css/font-awesome.css" ], this styles are missing. what can i do for this. any one help me. -
Setting up a dockerized python server on local machine gives Session data corrupted
I'm trying to set up a dockerized Python server named Bullet Train on my local machine: It has 3 components: A Postgres database A Python server A React frontend All of these 3 need to work together to get the server up and running, so this is the docker-compose file which sits at the top level of both the frontend and api-server: version: '3' services: db: image: postgres environment: POSTGRES_PASSWORD: password POSTGRES_DB: bullettrain ports: - "5432:5432" api: build: context: ./bullet-train-api dockerfile: docker/Dockerfile command: bash -c "pipenv run python manage.py migrate --noinput && pipenv run python manage.py collectstatic --noinput && pipenv run gunicorn --bind 0.0.0.0:8000 -w 3 app.wsgi && pipenv run python src/manage.py createsuperuser" environment: DJANGO_DB_NAME: bullettrain DJANGO_DB_USER: postgres DJANGO_DB_PASSWORD: password DJANGO_DB_PORT: 5432 DJANGO_ALLOWED_HOSTS: localhost ports: - "8000:8000" depends_on: - db links: - db:db frontend: build: context: ./bullet-train-frontend dockerfile: Dockerfile ports: - "8080:8080" This way, all the 3 components run in parallel. So far so good! Now to initialize it, I run the createsuperuser as stated here by following these steps: docker exec -it research_api_1 bash ## go to the context of the API server terminal run python manage.py createsuperuser ## run the createsuperuser command The command runs successfully and I … -
Django REST Framework pagination: Not found: GET /api/blog/list HTTP/1.1" 404 0
I am trying to implement simple pagination using Django rest frame work. But I am getting Status 404 Not Found in Postman. Custom urls.py included from base urls.py from django.urls import path from item.api.views import ( api_detail_item_view, api_create_item_view, ApiBlogListView ) app_name = 'item' urlpatterns = [ path('<slug_from_api_url>', api_detail_item_view, name="item_detail_api"), path('create_api/', api_create_item_view, name="item_create_api"), path('list', ApiBlogListView.as_view(), name="list"), ] serializers.py file: from rest_framework import serializers from item.models import ItemMaint class ItemMaintSerializer(serializers.ModelSerializer): class Meta: model = ItemMaint fields = ['name', 'itemDescription', 'active', 'slug'] views.py file: class ApiBlogListView(GenericAPIView): queryset = ItemMaint.objects.all() serializer_class = ItemMaintSerializer pagination_class = PageNumberPagination Settings.py file REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 1, } Thanks in advance. -
How to set a custom manager class parameter to required=False
I am writing an API to accept and save the user profile information. In total I want to accept 5 parameters from the user which are mentioned below. { "first_name":"", "last_name":"", "email":"", "password":"", "profile_picture":"" } Out of these 5 parameters first_name, last_name, email and password are mandatory and profile_picture is optional. In models.py I have mentioned profile_picture as an ImageField. models.py class Users(AbstractBaseUser, PermissionsMixin): """ This model is used to store user login credential and profile information. It's a custome user model but used for Django's default authentication. """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_picture/', max_length=None, blank=True) is_active = models.BooleanField(default=True) # defining a custom user manager class for the custom user model. objects = managers.UserManager() # using email a unique identity for the user and it will also allow user to use email while logging in. USERNAME_FIELD = 'email' In serializers.py I have mentioned profile_picture as an ImageField with required=False. serializers.py class UserSerializer(serializers.Serializer): """ This is a serializer class to validate create user request object. """ class Meta: models = 'Users' email = serializers.EmailField(allow_blank=False) first_name = serializers.CharField(max_length=255, allow_blank=False) last_name = serializers.CharField(max_length=255, allow_blank=False) profile_picture = serializers.ImageField(max_length=None, allow_empty_file=True, use_url= False, required=False) … -
django environment pyhon manage.py runserver
trying to start a project with django. I downloaded django and virtualenv package and everything went well ( I followed the installing instructions ) but, when I trued ti run in the command line : python manage.py runserver it displays an error and says that django does not exist and something about PYHONPATH. does anybody know a wat to get it installed and start a project easily? some how no matter what I do nothing works. thanks -
AttributeError: type object 'Product' has no attribute 'Objects'
from django.db import models class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Out Door', 'Out Door'), ) name =models.CharField(max_length=60) price =models.CharField(max_length=60) category =models.CharField(max_length=60, choices=CATEGORY) description =models.CharField(max_length=100) date_created =models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name from .models import * def products(request): products = Product.Objects.all() return render(request, 'Accounts/products.html', {'Products ': products}) -
how can i implement django oscar "categories" functionality(Parent, childs) in the Django oscar RESTFUL API?
In the oscar dashboard, I can make any root category, I can make children under a category. This functionality I am able to explore in the oscar Restful API. But I want to inherit the dashboard functionality, where we can make any category relative to another category. for example- I have 2 categories. 1) cat 1 a)subcat1 2)cat 2 now if I have to make subcat1 as a child of cat2 I can easily select from the dropdown and set 'subcat1' to cat2, in the oscar dashboard. But how can I do the same using Django oscar restful API? Please let me know. I have checked and found out that "category" model uses the Materialized Path trees, to achieve this functionality, how can I use this to achieve the treebeard functionality for adding the root nodes, adding children, and updating the categories under different categories etc? this is the request data I receive from the client side. { "id": 104, "url": "http://localhost:8000/api/admin/categories/104/", "breadcrumbs": "Cat1 > subcat1", "name": "subcat1", "description": "My new one test Desc", "slug": "subcat1", "parent": "Cat1", "children": "http://localhost:8000/api/admin/categories/Cat1/subcat1/", #here parent slug will be the name of parent category this category belongs to, if it is a parent category, … -
Django: Best way to extend auth_views.LoginView to do an extra check before allowing login to pass, only for login view
I've been trying to figure out the best way to add a single if statement to the baked in contrib.auth.LoginView from Django, to check if the login process should continue. I have in urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ ... url(r'^login/$', auth_views.LoginView.as_view(), name='account_login'), ... ] My task at this point is to check whether a user can log in, by checking their license, using a function that receives a License model instance: def check_license(lic_obj): file_contents = lic_obj.decrypt_license() expiry_date = file_contents['expiry_date'] expiry_date = dateutil.parser.parse(expiry_date) time_now = utc.localize(datetime.datetime.utcnow()) if expiry_date < time_now: users = User.objects.all() for user in users: user.remove_all_sessions() # If license is invalid, redirect to License page return HttpResponseRedirect(reverse('get_license')) # Otherwise, keep going with login, not sure how to go about this either, # depends on how extending LoginView works pass For clarity, a license is just an encrypted bit of JSON with some license related properties, one of which is the license's expiration date. That whole part of the code works, I'm just not sure how to have that check_license() function be run on login, before returning whether the login is successful or not. I was toying with adding a custom middleware class, but that …