Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What will be the best way to perform the CRUD with DRF?
There are several ways of performing CRUD operation with django-rest-framework.One will be by using the plain API view, another is Generic API view and other is with ViewSets.I want to know which will be the better way to create an API ? -
Segmentation fault (core dumped) with django-storages
I'm using Django 2.x and Django-storages to upload files to the S3 Bucket. While running the sample test from manage.py shell, it gives the following error and terminates the console. Segmentation fault (core dumped) The console log as per the doc. In [1]: from django.core.files.storage import default_storage In [2]: default_storage.exists('storage_test') Out[2]: False In [3]: file = default_storage.open('storage_test', 'w') In [4]: file.write('storage content') Out[4]: 15 In [5]: file.close() In [6]: default_storage.exists('storage_test') Out[6]: True In [7]: file = default_storage.open('storage_test', 'r') In [8]: file.read() Segmentation fault (core dumped) File is uploaded to the S3 Bucket but unable to access or read it. -
PATCH with Django REST framework
I have models, serializers, and viewsets as following. models.py class OrderStatus(models.Model): ORDER_STATUS_CHOICES = ( ('NEW', 'New'), ('PROCESSING', 'Processing'), ('DELIVERING', 'Delivering'), ('DELIVERED', 'Delivered'), ) status = models.CharField( max_length=20, choices=ORDER_STATUS_CHOICES, default=ORDER_STATUS_CHOICES[0][0]) def __str__(self): return self.status class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='order', on_delete=models.CASCADE) order_items = models.ManyToManyField(OrderItem) order_status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username serializers.py class OrderItemSerializer(serializers.ModelSerializer): pizza_type = serializers.CharField(source='pizza_type.name') pizza_size = serializers.CharField(source='pizza_size.size') class Meta: model = OrderItem fields = ('pizza_type', 'pizza_size', 'quantity', ) class OrderSerializer(serializers.ModelSerializer): user = UserSerializer() order_items = OrderItemSerializer(many=True) order_status = serializers.CharField(source='order_status.status') class Meta: model = Order fields = '__all__' views.py class OrderViewSet(ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer Listing, retrieving and deleting worked expectedly but how can I execute PATCH correctly to change order_status with the code above? I tried to run http://0.0.0.0:8000/api/orders/3/?order_status=PROCESSING and received "PATCH /api/orders/3/?order_status=PROCESSING HTTP/1.1" 200 313 but the data didn't look like it changed. Any hints? -
how to create dynamic model in django?
How do i create a dynamic model in django? here i am trying to create dynamic model using CreateDynamicModel,but it is not creating model and admin interface. ''' def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None): class Meta: pass if app_label: setattr(Meta, 'app_label', app_label) if options is not None: for key, value in options.iteritems(): setattr(Meta, key, value) # Set up a dictionary to simulate declarations within a class attrs = { '__module__': 'myapp.models' } # Add in any fields that were provided if fields: attrs.update(fields) # Create the class, which automatically triggers ModelBase processing model = type(name, (models.Model,), attrs) from django.core.management import sql, color from django.db import connection # Standard syncdb expects models to be in reliable locations, # so dynamic models need to bypass django.core.management.syncdb. # On the plus side, this allows individual models to be installed # without installing the entire project structure. # On the other hand, this means that things like relationships and # indexes will have to be handled manually. # This installs only the basic table definition. # disable terminal colors in the sql statements style = color.no_style() with connection.schema_editor() as editor: editor.create_model(model) class Admin(admin.ModelAdmin): list_display = ['first_name', 'last_name'] admin.site.register(model, Admin) return model def CreateDynamicModel(request): … -
html page should be updated when mysql table is updated without reloading in django
I have an issue that i want html page should update values which are fetched from mysql database whenever mysql table is updated. I have tried to implement javascript. here is what i have tried. ''' <script type="text/javascript"> $(document).ready(function(){ $.ajax({ type = 'Get', url = '{% url 'index' %}', data = {response.id_data} success : function(response){ $("#user_info ").html(`<tr> <td>${response.id_data || "-"}</td> </tr>`) }, }); }) </script> ''' here is my views.py. ''' def index(request): mycursor.execute("select id from face_counter") data = mycursor.fetchall() id_data = { "id": data } return JsonResponse({'id_data':id_data.get("id"),},status=200) ''' i have tried this but html page gets only json data and displayed it. script doesn't work what should i do. -
Retrieving count of unique Django objects based on multiple fields of another Django model
I have a Django model defined as follows: class Session(models.Model): ... leader = models.ForeignKey(User, related_name='leader') follower = models.ForeignKey(User, related_name='follower') ... Now let's say I have a QuerySet of Session objects: all_sessions = Session.objects.all() How can I get a simple count of unique Users that have been either a leader or follower in any Session in all_sessions? For example, a particular User may have been a leader in some number of Session objects, but a follower in a handful of other Session objects. That particular User should only contribute 1 to the desired unique Users count. There are of course some naive solutions to this, but for performance reasons, I'm wondering if there's a solution that leverages the power of QuerySets a bit more, if possible. -
google auth redirect uri miss match issue
In my django project i want to use google authentication for user login. i followed some articles but now stuck at point, where i'm getting error like: Error: redirect_uri_mismatch. i searched allot but could not resolved this issue. plz help I'm sharing my code here: settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'xnph^f^z=wq^(njfp*#40^wran3' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'core', ] 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', 'social_django.middleware.SocialAuthExceptionMiddleware', # <-- ] ROOT_URLCONF = 'simple.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = 'login' LOGOUT_URL = 'login' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False WSGI_APPLICATION = 'simple.wsgi.application' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xxxxxx my key xXXXXXX' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xxx my secrete XXXX' 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', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N … -
Best way to specify dedicated sub domain for authentication views in Django Rest Framework
I'm building and API using DRF and will be using it with a React SPA. I've chosen session authentication for my project because of the following reasons: It's built-in to DRF, so no dependence on 3rd party developers (a lot of auth packages or their dependencies are not maintained) CSRF + Cookie protection Ability to use Secure and HTTPOnly cookies However, I'm aware that it's recommended that we use Django's authentication views for the authentication pages and the single page app for the post authentication API calls. In this scenario, there are some views (i.e. Login, Logout, Password Reset, Register) for which the server responds with HTML and the rest return JSON. I would like to use different subdomain for these views i.e. different subdomain for HTML views and different subdomain for the JSON views. I'm a Django newbie and would really appreciate some suggestions on the best way to handle the separation of subdomains. I have some idea that the few ways I could achieve this are: using django-hosts using django sites (although I'm not sure if the cookie made by one site, would work on the other) point 2 domains to my server and handle the separation bit … -
django project always trying (and failing) to load file in separate app
I'm going back to an old django project and am trying to make a new site in a new app I just made, popularify. I want to load an httpResponse and nothing else when I go to the /popularify path , but it keeps trying and failing to get a favicon.ico file, the 404 error always appears in the chrome web console and django logs. I have it set up correctly so my popularify page loads a basic httpResponse: my main urls.py file in my project folder has a path: path('popularify/', include('popularify.urls')), The popularify app urls.py file looks like this: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] And the popularify views.py file looks like this from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") All very basic to just load some text, but in console I am getting a unrelated 404 error trying to load a file I never directly specified, and dont want to load: If I click the favicon.ico link it shows the html file _base.html I have in my templates folder, a file I use as a base file in … -
How do I accept the friend request in django after sending a hyperlink in mail which redirects the user to accept/reject page?
models.py : class Friend(models.Model, LoginRequiredMixin): status = models.CharField(max_length=10) from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user') to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user") date_modified = models.DateTimeField(auto_now=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def create(self,request, **kwargs): friend = self.create(from_user_id=request.user.id, status="pending") return friend views.py : This view contains 2 buttons: Accept and reject and based on user response it will be updated in the database def accept_friend_request(request, uidb64, status): """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected based on status flag""" try: uid = urlsafe_base64_decode(uidb64).decode() friend_user = User.objects.get(id=Friend.to_user.id) & Friend.from_user print(friend_user) f = Friend.objects.filter(friend_id = friend_user) print(f) if f: f.status = "accepted" f.save() return render(request, 'users/friend_list.html', {"uidb64": uid, "status": status}) else: f.status = "rejected" f.save() return render(request, 'users/friend_list.html', {'uidb64':uid, 'status':status}) except(FieldError, AttributeError): return render(request, 'blog/base.html') Thanking you in advance, -
How to work with drf-extension (Django Rest Framework) if the model has lookup_fields assigned
It would be better if I give an example that I was working on. The Models are class Author(models.Model): id = models.IntegerField(db_column='a_id', primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class Book(models.Model): id = models.IntegerField(db_column='b_id', primary_key=True) title = models.CharField(max_length=60) author = models.ForeignKey(Author, on_delete=models.CASCADE) And the Serializers are, class AuthorSerializer(ModelSerializer): class Meta: model = Author fields = ('id', 'first_name', 'last_name') class BookSerializer(ModelSerializer): class Meta: model = Book fields = ('id', 'author', 'title') And the view sets are, class AuthorViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() class BookViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() Now The following APIs are working okay, /authors/ /authors/{author_id}/ /authors/{author_id}/books/ However, If I change the Author Views to class AuthorViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() lookup_field = 'first_name' Then, the following APIs work /authors/ /authors/{author_first_name}/ But the following doesn't work. /authors/{author_first_name}/books/ I understand that it's because of the Foreign key relations between these two tables. I was just wondering whether there is any workaround if I want to keep the lookup_fields. Thanks -
Unable to customize django-oscar model
I am trying to customize a django-oscar model. ( I am using version 2.0.3 ) I have created a separate folder labeled apps and have created my app in it. I want to customize Product model in catalogue My INSTALLED_APPS look like this INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', # 'oscar.apps.catalogue', # 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', 'rest_framework', 'apps.catalogue' ] and apps/catalogue/models.py looks like this from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct # from oscar.apps.catalogue.models import * class Product(AbstractProduct): custom_tag_field = models.CharField(default="Pending", max_length=100) from oscar.apps.catalogue.models import * I keep getting this error when I try to migrate and unable to solve it. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File … -
How to pass data from Django template (after submission) to DRF API without using a model?
I have a form in my template which allows a user to upload an image. Once the image is uploaded and submitted, it gets stored in a specified directory (not 'media'). Note: The image is not stored in a Django model since I didn't create one (don't need it). After doing so, I need to create an API using the Django Rest Framework. When calling the API URL, I intend to display that stored image name. The result will look like this: {"image_name" : <'stored_image_name_after_form_submission'>} This is what I had done so far: views.py: from rest_framework.views import APIView #code for uploading an image def upload(request): if (request.method == 'POST'): uploaded_file = request.FILES['image'] fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) image_path = fs.save(uploaded_file.name, uploaded_file) #name of the image file messages.success(request, 'Uploaded The Image.') return render(request, "template/upload.html") class API(APIView): def get(self, request): #API code comes here. The thing is, I can't seem to visualize how to create the API since I am fairly new to it. How can I capture the image name after the form submission and present it in my API view? Can someone explain how it works and what I should do to meet the requirement? Million thanks in advance. -
serving Angular build pack from django project
Hi have a django project with multiple apps. My project structure is: apt.yml DCMS_API/ infra/ manage.py* odbc-cfg/ requirements.txt static/ templates/ Authorize/ facility/ manifest.yml Procfile runtime.txt i have got angular6 buildpack from front end team, which i have copied it to static folder: ls: 3rdpartylicenses.txt fontawesome-webfont.af7ae505a9eed503f8b8.woff2 scripts.5bde77e84291ce59c080.js assets/ fontawesome-webfont.b06871f281fee6b241d6.ttf Staticfile devManifest.yml fontawesome-webfont.fee66e712a8a08eef580.woff json-data/ styles.38614f36c93ac671679e.css favicon.ico index.html main.e7b9143f2f482d6d3cc7.js fontawesome-webfont.674f50d287a8c48dc19b.eot polyfills.f3fc5ca24d1323624670.js fontawesome-webfont.912ec66d7572ff821749.svg runtime.a66f828dca56eeb90e02.js in settings.py i have added whitenose to serve the static build pack: middleware:'whitenoise.middleware.WhiteNoiseMiddleware', installed apps: 'whitenoise.runserver_nostatic', from my Authorize app: calling def dcmsApi(request): return render(request, 'index.html', {}) which opens index.html file. it however loads the home page, but if i click on anything it says Not Found The requested resource was not found on this server. is this is the right way to server static angular build pack from django Am i missing something? -
JSON parse error - 'utf-8' codec can't decode byte 0xc9 in position XXX when I try to upload Excel Sheet using Angular+REST
I am trying my hands on File Upload using Django REST and Angular. Following is the angular directory structure: app |-----uploadcomponent |-----uploadcomponent.module.ts |-----uploadcomponent.html |-----app.module.ts |-----app.component.ts |-----app.service.ts uploadcomponent.htl: <div> <form [formGroup]="form" (ngSubmit)="onSubmit()"> <input type="file" name="profile" enctype="multipart/form-data" accept=".xlsm,application/msexcel" (change)="onChange($event)" /> <button type="submit">Upload Template</button> <button id="delete_button" class="delete_button" type="reset"><i class="fa fa-trash"></i></button> </form> </div> uploadcomponent.ts: import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; .... export class UploadComponent implements OnInit { form: FormGroup; constructor(private formBuilder: FormBuilder, private uploadService: AppService) {} ngOnInit() { this.form = this.formBuilder.group({ profile: [''] }); } onChange(event) { if (event.target.files.length > 0) { const file = event.target.files[0]; this.form.get('profile').setValue(file); console.log(this.form.get('profile').value) } } onSubmit() { const formData = new FormData(); formData.append('file', this.form.get('profile').value); this.uploadService.upload(formData).subscribe( (res) => { this.response = res; console.log(res); }, (err) => { console.log(err); }); } } app.service.ts: upload(formData) { const endpoint = this.service_url+'upload/'; return this.http.post(endpoint, formData, httpOptions); } Now in the backend I am using Django Rest Framework: Following are the required files of code: models.py: from __future__ import unicode_literals from django.db import models from django.db import connection from django_mysql.models import JSONField, Model import uuid import os def change_filename(instance, filename): extension = filename.split('.')[-1] file_name = os.path.splitext(filename)[0] uuid_name = uuid.uuid4() return file_name+"_"+str(uuid_name)+"."+extension class UploadTemplate (Model): id = … -
django do not save thumbnails from imagekit
from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class Image(models.Model): image = models.ImageField(upload_to='home/', blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(50, 50)],format='JPEG', options={'quality':60}) when I uploading image. Everything OK with original image. But there is no thumbnail image. I guess this problem is related with cache. Maybe I am wrong. Can't figure out what to do... Please help. -
Django crispy-form changes lay on production server
I cannot seem to understand why crispy-form has changed the layout on my production server vs. the test server. Looking at the html code the only thing I can see is that classes for the form list is changes on the production server. Production Server HTML <div id="div_id_pants" class="control-group"> <label for="id_pants" class="control-label "> Test Server HTML <div id="div_id_pants" class="form-group"> <label for="id_pants" class=""> also noticed that on the test server there is a css file forms.scss.171 that provides the form-group class. Which is not being listed at all on the production site. Any info on where this might be mismatching would be greatly aprieciated. It doesn't look very good atm :( -
HTML file not understanding Django content
I'm using Django in HTML file. Normally whatever IDE you use, understands the syntax the highlights "load" in {% load xxxxx %}. But in my case, Pycharm or Intelllij Idea is not understanding the syntax and the output file too give a result as text, {% load xxxxx %} included in the result page. The environment I am using I have already included Django in that. I'm not able to understand the issue. Can anyone please help me with this -
TypeError: argument of type 'function' is not iterable : django error
i am creating an api for polls app and i struck into this error.TypeError: argument of type 'function' is not iterable : django error my models:how can i deal with it ..it seems like there is no error in code . from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=100) def __str__(self): return self.choice_text class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) voted_by = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ("poll", "voted_by") my views: from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from .models import Poll def polls_list(request): MAX_OBJECTS = 20 polls = Poll.objects.all()[:MAX_OBJECTS] data = {"results": list(polls.values("question", "created_by__username", "pub_date"))} return JsonResponse(data) def polls_detail(request, pk): poll = get_object_or_404(Poll, pk=pk) data = {"results": { "question": poll.question, "created_by": poll.created_by.username, "pub_date": poll.pub_date }} return JsonResponse(data) -
How to find whether django hits db [duplicate]
This question already has an answer here: Force evaluate a lazy query 2 answers As per my knowledge, django querysets are lazy and wont hit db until evaluated, in such case after assigning the queryset to a key in a dict, will the following lines cause db to be hit everytime? Please advice abc = model1.objects.all() content = { 'entry' : abc, # Once assigned will the below lines hits db? 'entry_count' : abc.count(), # will this hit db 'entry1_count' : abc.filter(name__icontains = 'a').count(), # will this hit db 'entry2_count' : abc.filter(name__icontains = 'b').count(), # will this hit db again? } return render(request, template, content} -
How to show number of rows in django
I have 6 tables and I had grab the total no of rows like this genre=Genere.objects.all().count() mood=Mood.objects.all().count() artist=Artist.objects.all().count() song=Song.objects.all().count() customuser=CustomUser.objects.all().count() favorite=Favorite.objects.all().count() Now I want to show number of rows in view so I try directly {{genre}} but it's saying name 'Genere' is not defined -
Django ORM unable to retrieve database model instances
I am working on a custom user model that subclasses AbstractBaseUser and a custom model manager that subclasses BaseUserManager.This model, Employee, authenticates by email address - USERNAME_FIELD is set to email. While I can create Employee instances and check my PosgreSQL DB to verify they are being saved, I am unable to retrieve them with the Django ORM and my custom model manager. If I try to retrieve all the employees, or 'get' one employee when running Employee.objects.get(id=1), I get an error that from_db_value() expected 4 arguments but received 5. I am stumped here. I had this same kind of custom user in another Django 1.11 app and worked fine. I have spent two days trying to resolve this. Any help? models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from phone_field import PhoneField from django.core.validators import RegexValidator # to ensure leading zeroes are captured in badge number numeric = RegexValidator(r'^[0-9]*$', 'Only numeric characters are allowed.') # Create your models here. class EmployeeManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) … -
CharField(editable=False) with local variable as deault
im new to django and am trying to figure out how to add a specific field to a django model. I want to upload a csv document and save its headers. As you can see, i want to use the headers i send with the document, or if they arent send, the ones from the first line of the document. from django.db import models class CSV_API_DB(models.Model): headers = models.CharField(max_length=250, blank=True) delimiter = models.CharField(max_length=1, default=';') filefield = models.FileField(upload_to='uploads/', max_length=100, default='empty') actual_headers = '' def __str__(self): actual_headers = '' if not self.headers: file_path = str(self.filefield) file = open(file_path) for line in file: string_line = str(line[:-1]) actual_headers = string_line.split(self.delimiter) break else: actual_headers = self.headers.split(self.delimiter) return str(actual_headers) true_headers = models.CharField(max_length=250, default = str(actual_headers), editable=False) The issue seems to be, that true_headers does not get overridden from the '__ str __' function, since the values in the database for true_headers are always just empty strings. -
Github doesn't change the database in our teams django environment
Our team is using a django environment to develop a website, the main issue is one team member recently updated one of the databases and the change will not care through mysql. We are literally on the same branch but the database tables are completely different. We are using the current version of django, python, and mysql are the development environment and github to share work. -
debug=true django not showing errors on deployment
My site has been deployed successfully on linode. All pages are working just fine, but except for one particular url. Whenever I click on that link, it gives an internal server error without showing any error messages even though DEBUG=TRUE. But when I go to a non existing url Django shows the errors. Here is the error log: [Tue Nov 19 09:18:37.378891 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] mod_wsgi (pid=22728): Exception occurred processing WSGI script '/home/shahid/django_project/djecommerce/wsgi.py'. [Tue Nov 19 09:18:37.379959 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] Traceback (most recent call last): [Tue Nov 19 09:18:37.380186 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner [Tue Nov 19 09:18:37.380235 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = get_response(request) [Tue Nov 19 09:18:37.380283 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response [Tue Nov 19 09:18:37.380330 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = self.process_exception_by_middleware(e, request) [Tue Nov 19 09:18:37.380388 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response [Tue Nov 19 09:18:37.380435 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = wrapped_callback(request, *callback_args, **callback_kwargs) [Tue Nov 19 09:18:37.380567 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] …