Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializing the Django object in the required format
I have a Storage model in which I get objects using serialization: tree_data = serializers.serialize ("json", Storage.objects.all ()) It looks like this: [ {"model": "hello_extjs.storage", "pk": 9, "fields": {"code": "000", "name": "Title 1", "id_parent": 0}}, {"model": "hello_extjs.storage", "pk": 10, "fields": {"code": "111", "name": "Test 1", "id_parent": 9}}, {"model": "hello_extjs.storage", "pk": 11, "fields": {"code": "222", "name": "Test 2", "id_parent": 9}}, {"model": "hello_extjs.storage", "pk": 12, "fields": {"code": "333", "name": "Title 2", "id_parent": 0}}, {"model": "hello_extjs.storage", "pk": 13, "fields": {"code": "444", "name": "Test 3", "id_parent": 12}}, {"model": "hello_extjs.storage", "pk": 14, "fields": {"code": "555", "name": "Test 4", "id_parent": 12}} ] I need to have the data in this form: { text: 'Storage', expanded: true, children: [{ text: "Title 1", children: [{ text: "Test 1", leaf: true }, { text: "Test 2", leaf: true }], leaf: false, "expanded": true }, { text: "Title 2", children: [{ text: "Test 3", leaf: true }, { text: "Test 4", leaf: true }], leaf: false, "expanded": true } ] } How should I serialize objects to get the data in the form in which I need it? -
How to add helptext when mouse hovers on text?
HTML: <ul style="list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #2370b4"> <li style="float:left; display:block; text-align:center; padding:14px 16px; text-decoration:none"><a class="active" href="/home/" style="color:white">Home</a></li> <li style="float:left; display:block; text-align:center; padding:14px 16px; text-decoration:none"><a href="/search/" style="color:white">Search</a></li> <li style="float:left; display:block; text-align:center; padding:14px 16px; text-decoration:none"><a href="/upload/" style="color:white">Library</a></li> <li style="float:left; display:block; text-align:center; padding:14px 16px; text-decoration:none"><a href="/adddata/" style="color:white">Add Data</a></li> <li style="float:left; display:block; text-align:center; padding:14px 16px; text-decoration:none"><a href="#about" style="color:white">About</a></li> <li style="float:right; display:block; text-align:center; padding:14px 16px; text-decoration:none"><i>{{ username }}</i></li> <li style="float:right; display:block; text-align:center; padding:14px 16px; text-decoration:none"><a href="/logout/" style="color:white">Logout</a></li> </ul> Here I have my tabs and I want to display some help text when the cursor is hovering over, e.g. when cursor hovers over "Search", it should display "Search questions and responses". -
Django USE_L10N with JQuery DateRangePicker
I'm trying to use the JQuery DateRangePicker in my Django Forms. I enabled the USE_L10N=True option in my settings.py to allow Django to automatically detect the Date Format according to the user localization. Anyways, even if the DateRangePicker plugin allows me to choose the locale format, it doesn't detect it automatically like Django does, so I'm not able to match the two date formats. Which is the best practice? Django doesn't change the date format according to the website language, so I can't use the language code to change the JQuery plugin format. Maybe should I ask Django the current country code? Is it possibile? Thank you -
(2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
I am on mac with homebrew mysql, making a django app. I also use jupyter. I don't know which of these things is the root cause of the issue. I used to get this error message coming up every now and again, and I know how to fix it: just type brew services restart mysql and wait a bit. The problem is that it's now happening with increasing frequency, several times an hour. Is there a known fix for this, when working on a local machine? I thought, since I'm ctrl-c ing programs frequently, that might be exhausting the connection pool so I increased the connection pool size using SET GLOBAL max_connections = 5000;, but that has not helped. -
how to post foreign key fields in django rest framework
Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Count class CatalogSerializer(serializers.ModelSerializer): # company_details = CompanyData(many=True) total_pieces = serializers.SerializerMethodField() total_price = serializers.SerializerMethodField() # company = CompanySerializer(source='company_name') class Meta: model = Catalog fields = ('name','no_of_pcs','per_piece_price','company_name','total_pieces','total_price') depth = 1 def get_total_pieces(self, obj): totalpieces = Catalog.objects.aggregate(total_pieces=Count('no_of_pcs')) return totalpieces["total_pieces"] def get_total_price(self, obj): totalprice = Catalog.objects.aggregate(total_price=Sum('per_piece_price')) return totalprice["total_price"] def to_representation(self, instance): rep = super(CatalogSerializer, self).to_representation(instance) rep['catalog'] = instance.name return rep here is my views.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset = Catalog.objects.select_related('company_name') serializer_class = CatalogSerializer please check the screen shot i have shared. here no fields is coming for company. i wants to post company along with all fields … -
Action when a foreign key is being changed on django
The question in general is about finding the modification of a foreign key of a model and call some function of the related model. Assume I have two model class: class Discount(models.Model): def use(self, sell_item): if self.max_price: self.max_price -= sell_item.net() if self.max_count: self.max_count -= sell_item.amount self.save() def deuse(self, sell_item): if self.max_price: self.max_price += sell_item.net() if self.max_count: self.max_count += sell_item.amount self.save() max_price = models.PositiveIntegerField(blank=True, null=True) max_count = models.PositiveIntegerField(blank=True, null=True) amount = models.PositiveIntegerField(blank=False, null=False) class SellItem(models.Model): def net(self): price = self.amount * self.price if self.discount: price -= self.discount.amount * price / 100 return price * (1 + self.tax / 100) amount = models.PositiveIntegerField(balnk=False, null=False) price = models.PositiveIntegerField(blank=False, null=False) tax = models.PositiveIntegerFeidl(blank=False, null=False) discount = models.ForeignKey(Discount, blank=True, null=True) Now I want to execute use function whenever a discount add to an item and deuse it whenever it is being removed from an item. I found a post about it and to do that I write below code for sell item: def __init__(self, *args, **kwargs): super(SellItem, self).__init__(*args, **kwargs) self.dirty = False self.pre_states = [] self.new_states = [] def __setattr__(self, name, value): if name == 'discount': if hasattr(self, name): pre_discount = self.discount if pre_discount != value: self.dirty = True if pre_discount: self.pre_states = ['pre_discount'] self.pre_discount … -
ModuleNotFoundError: No module named 'registration'
I have an issue with Django-Registration. The package is properly installed, however when I run python3.6 manage.py runserver, I get the following error : ModuleNotFoundError: No module named 'registration' The screenshot of my Settings.py, Urls.py and HTML Template file is attached below: [enter image description here][1] Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10df3cb70> Traceback (most recent call last): File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/melissamalala/PycharmProjects/moringatribune/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in … -
Django: displaying different navbar options depending on if the user has created a userprofile or not?
I have a question on how can I display different options for navbar depeding on if the user has created a userprofile or not. I have tried many options including {% if profiles_list %} as well as {% ifequal user userprofiles.objects.all %} on base.html as well as creating a simple tag on templatetags but it does not seem to work. I have also tried changing views but since I am relatively new to coding I prefer to play around with "base.html". However, any suggestion will be welcomed. I want options to display in a way where if a user has not created a profile then only options of search, messages, about us and create new profile will appear. And if they have created a profile, then create new profile will be replaced with Edit profile, and further options of Delete profile and View Profile will also appear. My code is as below: base.html <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="{% url 'home:index' %}"> <img src="{% static "images/rainbow.jpg" %}" width="100" height="100" alt=""></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> {% if user.is_authenticated %} <li class="nav-item active"> <a … -
A server error occurred. Please contact the administrator error in django?
I am Trying to built a custom 404 and custom 500 error page in my django project but whenever I am trying to access it through some wrong url I am getting this error message 'A server error occurred. Please contact the administrator.' This is my setting.py file """ Django settings for erpcloud project. Generated by 'django-admin startproject' using Django 2.0.5. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') MEDIA_DIR = os.path.join(BASE_DIR,'media' ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # During development only MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'erpcloud.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, … -
Django rest framework default value random identifier
I'm trying to debug a weird behaviour when I try to save a DynamicDocument in MongoEngine. The document class is declared as follows: class Command(DynamicDocument): meta = { 'collection': 'executor_data_commands' } name = StringField() args = DynamicField() issued_at = LongField(default=time.time()) sync_with_kafka = BooleanField(default=False) correlation_id = StringField( default=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) ) commands_output = DynamicField(default=None) @classmethod def post_save(cls, sender, document, **kwargs): """ Send data to Kafka executor data topic after a new instance has been saved :param sender: the sender who emitted the signal :param document: the saved instance """ if kwargs['created']: CommandHandler(document).send_command() class CommandHandler: """ Command handler class """ def __init__(self, command_instance): self.command_instance = command_instance def send_command(self): """ Send command to Kafka queue and save the response in the local database :return: True if message is published over Kafka channel False otherwise """ headers = { "Content-Type": "application/vnd.kafka.json.v2+json", "Accept": "application/vnd.kafka.v2+json" } logger_kafka_handlers.info( "Got new command: %s - %s" % (self.command_instance.name, self.command_instance.args)) args = self.command_instance.args if 'machine_identifier' in args: args['machine_identifier'] = MACHINE_MAPPING.get(args['machine_identifier'], args['machine_identifier']) response = requests.post( KAFKA_BROKER_EXECUTOR_COMMANDS_IN['host'], json={"records": [{"value": { "name": self.command_instance.name, "args": args, "correlation_id": self.command_instance.correlation_id, "issued_ts": time.time() }}]}, headers=headers, auth=(KAFKA_BROKER_EXECUTOR_COMMANDS_IN['user'], KAFKA_BROKER_EXECUTOR_COMMANDS_IN['password']) ) self.command_instance.sync_with_kafka = True if response.status_code == 200 else False self.command_instance.save() logger_kafka_handlers.info( "Handled new command; Name: … -
django rest framework post data with foreign key
Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Count class CatalogSerializer(serializers.ModelSerializer): # company_details = CompanyData(many=True) total_pieces = serializers.SerializerMethodField() total_price = serializers.SerializerMethodField() # company = CompanySerializer(source='company_name') class Meta: model = Catalog fields = ('name','no_of_pcs','per_piece_price','company_name','total_pieces','total_price') depth = 1 def get_total_pieces(self, obj): totalpieces = Catalog.objects.aggregate(total_pieces=Count('no_of_pcs')) return totalpieces["total_pieces"] def get_total_price(self, obj): totalprice = Catalog.objects.aggregate(total_price=Sum('per_piece_price')) return totalprice["total_price"] def to_representation(self, instance): rep = super(CatalogSerializer, self).to_representation(instance) rep['catalog'] = instance.name return rep here is my views.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset = Catalog.objects.select_related('company_name') serializer_class = CatalogSerializer i wants to choose company for each catalog.which is defined as foreignkey please check the screen shot i have shared. here no fields is … -
How can I manually edit a specific attribute in a model through Django Shell?
I recently added a created_by attribute in Store model. Since this automatically gets a current logged in user when a store is created, if I don't manually assign any user, that column will be forever null. class Store(models.Model): ... created_by = ForeignKey(settings.AUTH_USER_MODEL, related_name='stores_of_created_by', null=True, blank=True) So, I want to assign a user manually. I think Django Shell (something that can be triggered through python manage.py shell) would be a good way to assign users manually. I'm very confused how I can manually assign a user in a specific attribute of all stores. So far I got a specific user and all stores in the following way. from django.contrib.auth.models import User from boutique.models import Store stores = Store.objects.all() user = User.objects.get(username='admin@gmail.com') After that, I need to loop through all stores and assign the user in created_by of all stores. How can I do that in Django Shell? -
Django : Calculated field + admin_order_field + action => FieldError: Cannot resolve keyword
I am using django admin (1.11.x) and I defined a calculated field (_due_date_in_days) to display it as a column. I wanted to be able to sort of this column like regular fields. I have a model class "Registration" that contains a date field "due_date" and a calculated field "_due_date_in_days" def _due_date_in_days(self): return (now().date() - self.due_date).days On the manager of class "RegistrationManager", I added an annotation def get_queryset(self): qs = super(RegistrationManager, self).get_queryset().filter() return qs.annotate(_due_date_in_days=now() - F('due_date')) In RegistrationAdmin I added format_due_date_in_days in the order list def format_due_date_in_days(self, obj): return (now().date() - self.due_date).days format_due_date_in_days.admin_order_field = '_due_date_in_days' The sort on the calculated field is working well until I am using an action (https://docs.djangoproject.com/fr/1.11/ref/contrib/admin/actions/) define on the ExampleAdmin class : def mark_as_printed(self, request, queryset): rows_updated = queryset.update(is_printed=True) When I am sorting on the calculated field AND I am using this action than error occured : django.core.exceptions.FieldError: Cannot resolve keyword '_due_date_in_days' into field. Choices are: ... -
Django delete confirmation view displaying variable name instead of information
Can anyone help me with following scenario? I have 3 tables like bellow. 1 & 2 is my data tables. and 3 keeps the relationship with 1 & 2. 1.Qa table ------------- |ID | QA | ------------- |1 |qa1 | |2 |qa2 | |3 |qa3 | ------------- a field of my Qa model tags = select2.fields.ManyToManyField(Tag, blank=True, verbose_name='Tag') 2.Tag table ------------- |ID | Tag | ------------- |1 |tag1 | |2 |tag2 | |3 |tag3 | ------------- 3.qa tag relation --------------------- |ID |QA_ID |Tag_ID | --------------------- |1 |1 |2 | |2 |1 |3 | |3 |2 |1 | |4 |3 |1 | |5 |3 |2 | |6 |3 |3 | --------------------- If i delete list of Tag (from above 2.Tag Table) it redirect to the confirmation table. And it display the list with some variable name like bellow Tag: tag1 Qa-tag relation: Qa_tags object Qa-tag relation: Qa_tags object Tag: tag2 Qa-tag relation: Qa_tags object Tag: tag3 Qa-tag relation: Qa_tags object Qa-tag relation: Qa_tags object Qa-tag relation: Qa_tags object what i really expect is (something user readable information) Tag: tag1 Qa-tag relation: qa2 Qa-tag relation: qa3 Tag: tag2 Qa-tag relation: qa1 Tag: tag3 Qa-tag relation: qa1 Qa-tag relation: qa2 Qa-tag relation: qa3 … -
Can not convert Django request.data.get("file") output to string: Can't convert 'InMemoryUploadedFile' object to str implicitly
I can print the uploaded file's content while posting it by using Response(request.data.get("file"), status=status.HTTP_404_NOT_FOUND) But, when I want to use the content by converting it to string and use string operations I get this error: Can't convert 'InMemoryUploadedFile' object to str implicitly How can I convert it to String? -
Django include template using Javascript
I came from a Rails background thus the question may seem stupid. In Rails, when we create a Ajax request, then we can update a view by rendering a partial using the javascript selector like the following: $("#dashboardEmails").html("<%=j render partial: 'emails', locals: {emails: @emails} %>"); How can I do that in Django template? I've tried the following: $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize() + "&submit=connect", success: function (data) { if(data['tables'].length > 0){ $('#data-connection-info').html("{% include 'projects/connection_info.html' with data='"data"' %}"); } console.log(data); }, error: function (data) { console.log("Error"); } }); Here, I want to update the view with a template projects/connection_info.html, also passing a javascript variable (data) to the template using with. But it is not working. Any idea how can I achieve that? -
How to get foreignkey field name insted of id in django rest framework
Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Count class UserSerializer(serializers.ModelSerializer): # name = serializers.StringRelatedField() # company_name = serializers.CharField() class Meta: model = User fields = '__all__' here is my views.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer I am getting api like this.. Here i am getting id instead of company_name. [ { "id": 1, "name": "soubhagya", "company_name": 1 }, { "id": 2, "name": "nihar", "company_name": 2 } ] But i am expecting output-- like this: [ { "id": 1, "name": "soubhagya", "company_name": "google" }, { "id": 2, "name": "nihar", "company_name": "facebook" } ] I am expecting my … -
check_password() returning False
I have made a model with its own password field. This is wholly separate from the User object. I'm using the django.contrib.auth.hashers library for this. In the create method for this model (overwriting a generic CreateListAPI view) def create(self, request, *args, **kwargs): data = request.data data['password'] = make_password(data['password']) serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) This stores a hashed password in my database as expected, but when I try to authenticate with the password def get_object(self): queryset = self.filter_queryset(self.get_queryset()) try: # Grabs the 'name' parameter from the URL obj = queryset.get(name=self.kwargs['name']) except Group.DoesNotExist: raise Http404 print(self.request.data['password']) # raw password string print(obj.password) # encoded password from database if check_password(self.request.data['password']), obj.password): raise Http404 obj.user_set.add(self.request.user) self.check_object_permissions(self.request, obj) return obj check_password returns False. However, passing in the encoded password as the raw string password works. So hashing the password works, but not comparing the raw password to it after the fact. -
Python virtualenv Can't set up! MAC OS
Hello everyone i'm trying to set up virtualenv and virtualenvwrapper on MAC OS and made huge resource tried everything what i can. DOESN't Work. I had python 2.7, i installed python 3.7 using regular installer from the python website. Installed everything what i need but getting error: /usr/bin/python: No module named virtualenvwrapper virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is set properly. Here is my ~/.bashrc : export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/code export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv export VIRTUALENVWRAPPER_VIRTUALENV_ARGS='--no-site-packages' source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh Here is where my python3 is installed /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 So in the end i did create one using virtualenv -p python3 "desired-path" but when i tried to set up everything with Django nothing is working bc of problem above. Any help please!! -
Error 500 (Internal Server Error) When Submission in Django using AJAX
When I click submit, It's Error 500 (Internal Server Error).I see this error in "Inspect Elements : Network" This is my code: HTML <form id="new_user_form"> <input type="text" id="name" placeholder="Name" name="" value=""> <select class="" name="skill_type" id="type"> <option value="1">Developer</option> <option value="2">Network</option> <option value="3">System</option> <option value="4">Database Analysis</option> </select> <input type="submit" name="" value="submit"> </form> JS $(document).on('submit','#new_user_form',function(e){ e.preventDefault(); $.ajax({ type : 'POST', url : 'skill/create', data : { name : $('#name').val(), type : $('#type').val(), }, sucess:function(){ } }); }); view.py def create_skill(request): if request.method == 'POST': name = request.POST['name'] type = request.POST['type'] skill = Skill(skill_name=name,skill_type=type) skill.save() return HttpResponse() This is image Error : enter image description here Please Help me TT -
Which JavaScript library/Framework (Reactjs/vuejs/Angular) Fits best with Django
Hello fellow developers, I was working on a Django project then I realized that the formal HTML templates have their own limitations. Then I started googling for a better frontend Which brings me too - Vuejs, ReactJs, Angular. No doubt all three of them are fantastic in their own way, But Which one works best with Django keeping in mind performance and scaling and rendering pages fast. Most of the tutorials on the internet are About Django+React some people claim that they are made for each other, But Just don't know why I don't like the way react works and it's syntax specifically maybe because I am from python background that's why. On the other hand, Angular looks way cleaner. Another great framework is VueJs but it lacks resources because it is not backed by companies like Google and Facebook. I can't be sure about its future. I am personally more biased towards Angular but we don't have many tutorials on Angular+Django But I hope installation won't be different for the react one like creating an API then providing the endpoints and run. I bet many of you have already worked with these great frameworks/library will you please share your … -
User authentication for Spotify API
I am creating a small project using Spotipy for the Spotify API. Through development I have been using localhost as the redirect and then copy and pasting the link that opens in the terminal. How do I properly handle this interaction so that I do not need to copy and paste links? Thank you very much! -
Wagtail how to render an image: Unrecognised operation: orignal
How do I render an image from a ForeignKey('wagtailimages.Image') inside Productpage.html? I'm currently receiving the error: Unrecognised operation: orignal Why is this not working?: {% image page.productImage orignal %} Productpage.html {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block body_class %}template-productspage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <p class="meta">{{ page.count }}</p> <div class="intro">{{ page.intro }}</div> {{ page.description|richtext }} {% image page.productImage orignal %} <img class="" src="{{ productImage.url }}" style="width:100%;" alt="Card image"> <p><a href="{{ page.get_parent.url }}">Return to blog</a></p> {% endblock %} Products/models.py from django.db import models from modelcluster.fields import ParentalKey from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel, InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index from wagtail.images.models import Rendition class ProductPage(Page): intro = models.CharField(max_length=250) count = models.IntegerField(default=1) description = RichTextField(blank=True) productImage = models.ForeignKey( 'wagtailimages.Image', null=True, on_delete=models.CASCADE, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('description'), ] content_panels = Page.content_panels + [ FieldPanel('intro'), FieldPanel('count'), FieldPanel('description', classname="full"), ImageChooserPanel('productImage'), # ERRORS OUT IN HTML #InlinePanel('gallery_images', label="Gallery images"), # MULTPIPLE IMAGES ] -
Django request.user becomes anonymous after changing page
I'm using a custom user model that extends BaseAbstractUser. This is the user model: class cUser(AbstractBaseUser): def save(self, *args, **kwargs): pass role_id = models.IntegerField() user_id = models.IntegerField() email = models.CharField(max_length=40) password = models.CharField(max_length=40) f_name = models.CharField(max_length=40) l_name = models.CharField(max_length=40) address_id = models.IntegerField() phone_num = models.IntegerField() loan_item_count = models.IntegerField() id = models.IntegerField(unique = True, primary_key = True) def __init__(self, dictionary, *args, **kwargs): self.role_id = int(dictionary['role_id']) self.user_id = dictionary['user_id'] self.email = dictionary['email'] self.password = dictionary['password'] self.f_name = dictionary['f_name'] self.l_name = dictionary['l_name'] self.address_id = dictionary['address_id'] self.phone_num = dictionary['phone_num'] self.loan_item_count = dictionary['loan_item_count'] self.id = self.user_id USERNAME_FIELD = 'user_id' class Meta: managed = False I don't want the model to affect the DB in any way. I'm loading it by a simple raw SQL query from a gateway method. This is how I'm handling login: def login_request(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = userGateway(username,password) if user is not None: print("=========USER==========") print(user.email) user.backend = 'django.contrib.auth.backends.ModelBackend' login(request,user) print(request.user.is_authenticated) if user.role_id==1: return render(request, 'biblioteca/admin/landing.html') # return HttpResponseRedirect('/') else: return render(request, 'biblioteca/landing.html') else: print("=========NOT USER==========") else: if(request.user is not None and not request.user.is_anonymous): return render(request, 'biblioteca/admin/landing.html') form = LoginForm() return render(request, 'biblioteca/login.html', {'form': form}) As you can see, … -
Postgresql Update Causes: 'django.db.utils.OperationalError: could not access file "$libdir/postgis-2.4": No such file or directory'
Our Django project running on an OSX instance is having an issue after a accidental upgrade with brew. Previously, the Django system was running postgresql-9.5 with postgis-2.3 and worked with no issues. However once brew installed postgresql version 10.5 and postgis 2.5 everything started to break. After this update we receive the following error when trying to run a database query in Django: django.db.utils.OperationalError: could not access file "$libdir/postgis-2.4": No such file or directory When going into psql to try and get the extenstion to 2.4 by running: ALTER EXTENSION postgis UPDATE TO "2.4.0"; We get the error: ERROR: extension "postgis" has no update path from version "2.5.0" to version "2.4.0" We have been unsuccessful in reinstalling postgresql 9.5 and postgis 2.3 with brew and are not sure where to turn next to try and get the development system running. Looking for suggestions on how to either get the Django instance to look for extension 2.5 which I'm guessing now exist or to return the postgres system to it's former state on the mac through brew. Django version 2.0.1 and psycopg2 version 2.7.3.2