Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Override for delete_selected not working
I created a custom user model (users_user) to be used instead of Django's default auth_user model. When i got to the default Admin site and open the User object, it correctly shows the list of records for my custom user model. But when I delete one of those records, it seems to be referencing the default auth_user model. I get the error: IntegrityError at /admin/users/user/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(3) is not present in table "auth_user". users/models.py from django.db import models from PIL import Image from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) #~~~ CUSTOM USER ~~~ class UserManager(BaseUserManager): def create_user(self, email, username, password=None): print('username in UserManager.create_user(): ' + username) if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, #todo: confirm, is this right? ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, username=username, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, username, password): print('username in UserManager.create_superuser(): ' + username) """ Creates … -
Django slow load table with large data - duplicate query
I'm working with a django example and seem to be getting duplicate queries and slow load time - I see duplicates in the django debug toolbar. The following is the 3 main files in the project. Are there any optimizations to be made on the functions in the model : # views.py class IndexView(ListView): template_name = "myapp/index.html" paginate_by = 100 model = Company <!-- index.html --> ... </thead> <tbody> {% for company in company_list %} <tr> <td>{{ company.name }}</td> <td>{{ company.get_order_count }}</td> <td>{{ company.get_order_sum}}</td> </tr> {% for contact in company.contacts.all %} <tr> <td>&nbsp;</td> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td>Orders: {{ contact.get_order_count }}</td> <td></td> </tr> {% endfor %} {% endfor %} </tbody> <tfoot> ... # models.py class Company(models.Model): name = models.CharField(max_length=100) industry = models.CharField(max_length=100, blank=True) # get all orders associated with this company def get_order_count(self, page_obj): orders = 0 for order in self.orders.all(): orders += 1 return orders def get_order_sum(self): total_sum = 0 for contact in self.contacts.all(): for order in contact.orders.all(): total_sum += order.total return total_sum class Contact(models.Model): company = models.ForeignKey(Company, related_name="contacts", on_delete=models.PROTECT) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def get_order_count(self): orders = 0 for order in self.orders.all(): orders += 1 return orders class Order(models.Model): order_number = models.CharField(max_length=100) company = … -
IntegrityError Django Postgres when deleting
This is the error, I get it when I delete a TaskList, which is related to ChartDay which is related to MemberRemaining all with on_delete CASCADE, If a delete TaskList the Charts related to it should be deleted, same way happens with ChartDay to Chart and MemberRemaining to ChartDay. Why am I getting this error? insert or update on table "chart_memberremaining" violates foreign key constraint "chart_memberremainin_chart_day_id_e25c792b_fk_chart_cha" DETAIL: Key (chart_day_id)=(7) is not present in table "chart_chartday". -
How to solve 401 Unauthorized error in Socket.IO Django framework?
I am trying to get the Socket.IO work with my Django server. Here is my setup: Frontend js: const socket = io.connect('127.0.0.1:8001'); socket.on('connect', () => { console.log('socket id: %s\n', socket.id); }); Django server: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() sio = socketio.Server(async_mode='eventlet', cors_allowed_origins='*', logger=True, engineio_logger=True) @sio.event def connect(sid, environ, auth): print('connect ', sid, auth) static_files = { '/public': './static', } application = socketio.WSGIApp(sio, application, static_files=static_files) eventlet.wsgi.server(eventlet.listen(('', 8001)), application) Dependencies Django==2.2.11 django-cors-headers==3.0.0 eventlet==0.30.0 gunicorn==19.7.1 python-socketio==4.6.1 ... When I run the js, the server will return 401 unauthorized error before reaching the connect function. Frontend: GET http://127.0.0.1/socket.io/?EIO=3&transport=polling&t=NYKlRjO 401 (UNAUTHORIZED) Django server log: (11053) accepted ('127.0.0.1', 34906) 127.0.0.1 - - [02/Apr/2021 15:39:31] "GET /socket.io/?EIO=3&transport=polling&t=NYKlTB8 HTTP/1.1" 401 253 0.002482 But the weird thing is if I commented out the connect event, everything like other events work just fine: # @sio.event # def connect(sid, environ, auth): # print('connect ', sid, auth) Anyone knows why if I set the connect event and the socket suddenly stop working? -
Need to display books by the same author for a bookstore web app
I am working on a bookstore web app and need help displaying books by the same author when a hyperlink of their name is clicked. The problem I am running into is the program is grabbing the id number of the book instead of the author_id and displaying the information for the book with that id. I need it to display all of the books in the database by the same author. models.py class Product(models.Model): # model to create table on database products genre = models.ForeignKey('Genre',related_name='products',on_delete=models.CASCADE) author = models.ForeignKey('Author',related_name='authors',on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='static/media',blank=True) image2 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True) image3 = models.ImageField(upload_to='media/%Y/%m/%d',blank=True) publisher = models.CharField(max_length=100, db_index=True) release_date = models.DateTimeField(null=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_detail',args=[str(self.slug)]) class Author(models.Model): # model to create table on database author first_name = models.CharField(max_length=200, db_index=True) last_name = models.CharField(max_length=200, db_index=True) biography = models.TextField(blank=True) created = models.DateTimeField(auto_now=True) class Meta: ordering = ('-first_name',) index_together = (('id'),) views.py def book_author(request, id=None): item = Product.objects.get(id=id) context = { 'items': Product.objects.all(), 'book_list': Product.objects.all().filter(author_id = id), 'id': item.id, 'name': item.name, 'cover': item.image, 'author': item.author, 'author_id': … -
RuntimeError: Model class himalayadashbords.clients.models.Client doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I"m using cookie cutter and I ve this error with codes: clients/apps.py: from django.apps import AppConfig class ClientConfig(AppConfig): name = 'clients' settings.py: LOCAL_APPS = [ "himalayadashbords.users.apps.UsersConfig", "himalayadashbords.clients.apps.ClientConfig", "himalayadashbords.queries.apps.QueriesConfig", "himalayadashbords.dashboard.apps.DashboardConfig", # Your stuff: custom apps go here ] clients/models.py: from django.db import models class Client(models.Model): name = models.CharField(max_length=50, unique=True) QBO_id = models.CharField(max_length=100) QBO_refreshtoken = models.CharField(max_length=100) fiscalmonth = models.IntegerField(default=1) def __str__(self): return self.name dashboard/views.py: from himalayadashbords.clients.models import Client from himalayadashbords.queries.QBOQueries.qQBOInvRevenues import avNEclients listofcpy = Client.objects.all().only("pk", "name") error debug: File "/Users/xxx/PycharmProjects/cool/himalayadashbords/himalayadashbords/clients/urls.py", line 3, in <module> from .views import ( File "/Users/xxx/PycharmProjects/cool/himalayadashbords/himalayadashbords/clients/views.py", line 8, in <module> from .models import Client File "/Users/xxx/PycharmProjects/cool/himalayadashbords/himalayadashbords/clients/models.py", line 3, in <module> class Client(models.Model): File "/Users/xxx/PycharmProjects/cool/himalayadashbords/venv/lib/python3.8/site-packages/django/db/models/base.py", line 113, in __new__ I've already tried: to change apps.py with name = himalayadashbords.clients and verbose="clients" try to do my query in module client than import it in dashboard but I've same issue -
Django Administration: Delete record from custom user model
I have created a custom user model (users_user) which works for registering new users (creating new custom user records) and logging in. But if I go to the Admin page, and try to delete a user record from there, it seems to be trying to delete records from the default user model (auth_user). I get the error: IntegrityError at /admin/users/user/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(3) is not present in table "auth_user". Is there a way I can keep the standard Django Administration pages (screenshot below), but reference my custom user model instead of the standard auth_user model? users/models.py from django.db import models from PIL import Image from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) #~~~ CUSTOM USER ~~~ class UserManager(BaseUserManager): def create_user(self, email, username, password=None): print('username in UserManager.create_user(): ' + username) if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, #todo: confirm, is this right? ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, username=username, … -
How to access two models in a single view to print their fields using single html file?
I have two models in my django application (Client and Installment). My models.py is given below: models.py from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name def get_absolute_url(self): return reverse('client_details',kwargs={ 'pk' : self.pk}) class Installment(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.installment_month def get_absolute_url(self): return reverse('installment_confirmation') And to show the client details I have a view called 'clientDetailView' and is shown below: view.py class ClientDetailView(DetailView): model = Client model = Installment And the template for this is called 'client_details.html' is also given below: <!DOCTYPE html> {% extends "property_details/base.html" %} {% block content %} <body> <legend class="border-bottom mb-4"><h3>{{ object.name }}</h3></legend> <article class="media content-section"> <div> <p class="text-muted">Client CNIC: {{ object.CNIC }}</p> <p class="text-muted">Date of Birth: {{ object.dob }}</p> <p class="text-muted">Type of Property: {{ object.property_type }}</p> <p class="text-muted">Date of Agreement: {{ object.date_posted|date:"F d, Y" }}</p> </div> </article> <legend class="border-bottom mb-4"><h5>Installment History</h5></legend> <article class="media content-section"> <div> <!--<p class="text-muted">Installment Month: {{ object.installment_month … -
Specifying both 'fields' and 'form_class' is not permitted (Django)
I have created a validator for my UpdateView but I got this error (in title). These are my codes. Forms.py class HotelBookingAdForm(forms.ModelForm): class Meta: model = HotelBookingAd fields = '__all__' def clean_sales_price(self): sales_price = self.cleaned_data["sales_price"] if sales_price > purchase_price: raise forms.ValidationError("Error") print("error") return sales_price Views.py class HotelUpdate(AuthorsAccessMixin,FieldsMixin,FormValidMixin,UpdateView): model = HotelBookingAd form_class = HotelBookingAdForm template_name = "account/article-create-update.html" Models.py class HotelBookingAd(models.Model): purchase_price = models.IntegerField() sales_price = models.IntegerField() after i try to reach HotelUpdate view i got the Error --> Specifying both 'fields' and 'form_class' is not permitted. (in web browser). also i have removed fields from HotelBookingAdForm and got this error in console : Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form HotelBookingAdForm needs updating. Can anybody help me to fix this problem? Thanks! -
Cookies not being store in the browser but it does in Postman
Working with Next.js and Django Rest Framework, I'm authenticating users using JWT. First, when the user successfully logs in to the page, a cookie (which contains the JWT token) is sent to the browser. When the user tries to access a specific page, this cookie is used to validate the petition. This works fine using Postman (when I fetch a protected URL, the server returns what I spect) but I'm having trouble storing the cookie in the browser. Django | login function @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def login(request): ... response = Response() response.set_cookie(key='jwt', value=token, httponly=True, max_age=86400) response.data ={ 'message': 'success', } return response And here is how I'm fetching /api/login Next | Login.js var axios = require('axios'); var FormData = require('form-data'); var data = new FormData(); data.append('email', this.state.email); data.append('password', this.state.password); data.append('X-CSRFToken', csrftoken); data.append('mode', 'same-origin'); data.append('Content-Type', 'application/json'); var config = { method: 'post', credentials: 'include', #I'm probably having issues with this url: 'http://localhost:8000/api/login', data : data }; axios(config) .then(res=> { console.log('success'); #I got loged, but the cookies is not stored }) .catch( error=>{this.setState({isError:true})} ); -
I need help to create sql query
id | game_id | point 1 | 100 | 1 2 | 200 | 1 3 | 200 | 0 4 | 300 | 0 5 | 100 | 1 6 | 100 | 1 7 | 200 | 0 8 | 100 | 1 I need create a sql query and django query for get logs grouped by local game_id and count the points that correspond to the game_id, it should look something like this game_id | point 100 | 4 200 | 1 300 | 0 -
ModelChoiceField javascript onChange arguments
I am new to JavaScript as well as Django. The project has a Students model with multiple fields, and I have implemented a ModelChoiceField form which drops down and allows for selecting a particular record in the Students table. forms.py: class StudentChoiceField(forms.Form): students = forms.ModelChoiceField( queryset=Student.objects.values_list().order_by("last_name"), empty_label="(select student)", widget=forms.Select(attrs={"onChange":'refresh()'}) ) def __init__(self, *args, **kwargs): super(StudentChoiceField, self).__init__(*args, **kwargs) # without the next line label_from_instance does NOT work self.fields['students'].queryset = Student.objects.all().order_by("last_name") self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name) The label_from_instance is overridden, so that the drop-down form displays just two of the fields (there are eleven total in the model). When a student is selected, I want to update some textfields in the page to display the remaining fields of the model. Currently, have implemented a javascript function refresh() which is invoked for the onChange event of the StudentChoiceField form. index.html (all_students_choice is the StudentChoiceField form): {% extends "base.html" %} {% block content %} <body> <script> function refresh(){ var id = document.getElementById("id_students").value; console.log(id); } </script> <div class="container"> <form method=POST action=""> {% csrf_token %} {{ all_students_choice }} </form> </div> </body> {% endblock %} I have confirmed through browser console that the javascript function is getting invoked, and printing the value of … -
Django files not found when served with Apache
I deployed my Django project on a Linux server using Linode. When I run it by the python manage.py runserver command on port 8000 everything looks fine. However, when I use apache2 I get the following error when loading the website: FileNotFoundError at / [Errno 2] No such file or directory: 'research_files/data.xlsx' Request Method: GET Request URL: http://453.33.13.202/ Django Version: 3.1.5 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'research_files/data.xlsx' In /etc/apache2/sites-available I've created a django_project.conf file which has the following instructions: Alias /research_files/ /home/alexa/django_project/research_files/ <Directory /home/alexa/django_project/django_project/research_files> Require all granted </Directory> <Directory /home/alexa/django_project/django_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/alexa/django_project/django_project/wsgi.py> WSGIDaemonProcess django_app python-path=/home/alexa/django_project python-home=/home/alexa/django_project/venv WSGIProcessGroup django_app Then I've enabled that file by running sudo a2ensite django_project and also given access to the folder by running: sudo chown :www-data django_project/research_files sudo chmod 664 django_project/research_files What may be causing this error? -
Django static files referencing
I'm trying to link some pictures to my Django app from the static folder, but instead it creates a new static folder inside the templates directory. My HTML: {% load static %} <!DOCTYPE html> {% extends 'milk_app/base.html' %} {% load staticfiles %} {% block title_block %} Homepage {% endblock %} {% block body_block %} <!-- Home page for Hosts --> {% if user.userprofile.account == "Host" %} <div class="container"> <div class="row"> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" src="{% static 'images/listing-property.jpg' %}"></a> <h4>Create a new listing</h4> </div> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" src="{% static 'images/your-properties.jpg' %}"></a> <h4>Show your rented properties</h4> </div> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" src="{% static 'images/scroll-others.jpg' %}"></a> <h4>Scroll other properties</h4> </div> </div> </div> <!-- Home page for Tenants (not the beer) --> {% elif user.userprofile.account == 'Tenant' %} <!-- Home page for not logged users --> {% else %} <br><br> <section > <div> </div> </section> {% endif %} {% endblock %} My folder looks like this: 1. APP_APP 2. ACTUALAPP 3. STATIC * images - the actual images.jpgs 4. TEMPLATES * creating a new **{% static 'images** folder - creating a new image here So my VS Code is creating a new file somewhere I don't want … -
EOF occurred in violation of protocol (_ssl.c:1125) on python:3.8-slim-buster
I recently updated a django api from 2.2 to 3.1. I updated the dockerfile and related bash files like django-cookiecutter did https://github.com/pydanny/cookiecutter-django/commit/b22045bcd4ebf563ccdcf226fb389a6bb71e2654#diff-1872e6a6f0bbcb27f2eda185ac89eed05eb7a402b298e58bcbef29bf039c2c13 The upgrade mostly went well except now in production we cannot send email. I have a minimal management command I run in production to test email settings from django.conf import settings from django.core.mail import send_mail from django.core.management.base import BaseCommand class Command(BaseCommand): """ Sends an email to the provided addresses. """ help = "Sends an email to the provided addresses." def add_arguments(self, parser): parser.add_argument("emails", nargs="+") def handle(self, *args, **options): self.stdout.write(f"send_email from: {settings.EMAIL_FROM_FIELD}") for email in options["emails"]: try: send_mail( "expert-system test email", "a simple email", settings.EMAIL_FROM_FIELD, [email], ) except BaseException as e: self.stdout.write(f"Problem sending email: {e}") This returns $ python manage.py send_email harry@test.com send_email from: test@test.com Problem sending email: EOF occurred in violation of protocol (_ssl.c:1125) Another stackoverflow suggested testing if tls 1.1 is supported. $ python -c "from urllib.request import urlopen ; print(urlopen('https://www.howsmyssl.com/a/check').read())" b'{"given_cipher_suites":["TLS_AES_256_GCM_SHA384","TLS_CHACHA20_POLY1305_SHA256","TLS_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256","TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256","TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","TLS_DHE_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA","TLS_DHE_RSA_WITH_AES_128_CBC_SHA","TLS_RSA_WITH_AES_256_GCM_SHA384","TLS_RSA_WITH_AES_128_GCM_SHA256","TLS_RSA_WITH_AES_256_CBC_SHA256","TLS_RSA_WITH_AES_128_CBC_SHA256","TLS_RSA_WITH_AES_256_CBC_SHA","TLS_RSA_WITH_AES_128_CBC_SHA","TLS_EMPTY_RENEGOTIATION_INFO_SCSV"],"ephemeral_keys_supported":true,"session_ticket_supported":true,"tls_compression_supported":false,"unknown_cipher_suite_supported":false,"beast_vuln":false,"able_to_detect_n_minus_one_splitting":false,"insecure_cipher_suites":{},"tls_version":"TLS 1.3","rating":"Probably Okay"}' How do I get email to send on production? -
Django select_related has no effect
The query below should return the most liked posts of the week. As the select_related() method should populate .post attributes but the query returns a list of dicts instead of model instances. Model class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) Query likes = Like.objects.select_related().values('post').annotate( year=ExtractYear('created'), week=ExtractWeek('created'), yearweek=Concat('year', Value(''), 'week'), likes=Count('yearweek'), ).order_by('-likes').values('post', 'likes')[:10] Output <QuerySet [{'post': 2, 'likes': 1}, {'post': 3, 'likes': 1}]> I get AttributeError: 'dict' object has no attribute 'post' when doing likes[0].post -
Django-invitations email template
I'm using django-invitations to manage user invitation. I can't find where I should put the template files email_invite_message.txt and email_invite_subject.txt Here they talk about Override email_invite_message.txt in django-invitations/invitations/templates/invitations/email/. You can do this by creating the file in the same directory path in your project. or Yeah, if this isn't clear, you can create an .html file in your project at {projectroot}/{app}/templates/invitations/email/email_invite_message.html and it will override the default template. But the first one didn't work for me and I can't figure out what {app} should be. -
ValueError at / dictionary update sequence element #0 has length 1; 2 is required
My goal is simply to be able to use django-oscar templates to form the basis of web pages in my webapp. For some reason I am having no end of issues. This is only the latest error message. I have been struggling with this for days! When I resolve one issue, another shows up. I made a minimal git repo for this problem: https://github.com/mslinn/django_oscar_problem The README shows the error message I currently get in the web browser and all the files. I tried to ensure that I had the simplest possible project that shows the problem. The problem appeared after I modified a template I made to use Oscar's layout.html. # /templates/welcome.html {% extends 'oscar/layout.html' %} ... etc ... # main/urls.py from django.urls import include, path from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home, 'home'), path('admin/', admin.site.urls, 'admin'), path('hello/', views.hello, 'hello'), path('', include(apps.get_app_config('oscar').urls[0])), ] # main/views.py from django.shortcuts import render def home(request): return render(request, "welcome.html", {}) The error message in the web browser is: ValueError at / dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1.6 Exception Type: ValueError Exception … -
Django USERNAME_FIELD does not take effect in a Custom User class and gives UNIQUE constraint failed error
I am using a custom user model: from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) # My CustomUser class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __repr__(self): return self.email Based on my understanding of the documentation of USERNAME_FIELD, I thought I won't have to explicitly deal with username field at all, however, that is not the case. The interactions in the Django shell are as follows (after a fresh migration and new database): In [15]: from django.contrib.auth import get_user_model In [16]: user = get_user_model() In [17]: user.objects.create(email='dave@gmail.com', password='123456789ABC') IntegrityError: UNIQUE constraint failed: users_customuser.email However, if I add a username field, e.g. user.objects.create(username='dave', email='dave@gmail.com', password='123456789ABC'), then everything seems to be fine. My question is then, … -
How two different applications should get served using one single apache2 virtualhost configuration
Just for assumption here testsite.com which is my php application and testsite.com/project is python application I have following settings in my apache site config file /etc/apache2/sites-available/site.conf <VirtualHost *:443> ServerAdmin webmaster@testsite.com DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> <VirtualHost *:443> ServerAdmin webmaster@testsite.com DocumentRoot /var/www/html/test-project <Directory /var/www/html/test-project/test-project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess test python-path=/var/www/html/test-project/test-project python-home=/var/www/html/test-project WSGIProcessGroup test WSGIScriptAlias / /var/www/html/test-project/test-project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Looking at above config, I just want any url with testsite.com/ will get served from first virtualhost which is my php application and its working and whenever only this specific testsite.com/project url hits then it should get served from second virtualhost which is my python application. So inorder to get this url testsite.com/project served from second virtualhost it has to get bypass from first virtualhost. Please suggest how do I do that ? What should I do in first virtualhost so that it wil get bypassed to second. NOTE: This is not related with url rewriting so please do not suggest anything rewriting rule or anything regarding that. -
Unable to do migrations using django and docker
I am using Django with docker-compose. I got the following error : Error : column mytable_user.name does not exist LINE 1: ..."mytable_user"."date", "mytable_user"."updated", "mytable_... Here is my entrypoint.sh : #!/bin/sh python3 manage.py makemigrations mytable python3 manage.py migrate exec "$@" I don't know how to solve that ... I tried that : docker exec -it id_container python manage.py makemigrations mytable I got that : No changes detected in app 'mytable' And then I tried that : docker exec -it id_container python manage.py migrate But I got that : No migrations to apply. I thought to remove the migrations folder but I am using docker so it isdifficult to do that my workdir is /usr/src/web But when I try to go to this folder I get an error message ... And I always get this message : Error : column mytable_user.name does not exist LINE 1: ..."mytable_user"."date", "mytable_user"."updated", "mytable_... Could you help me please ? Thank you very much ! -
Bootstrap columns filled with hyperlinked images
I am working on a web app that allows you to rent/be a tenant of some certain property. If logged in as a user I want the home page to show 3 links: 1) to his current listings, 2) create a listing and 3) to search other host's listings. I want it to look something similar to this, which is basically somewhere in the middle part of the page vertically and also horizontally: Example of the finish product I'm using python extension django and have already stored whether the user is authenticated and also whether he's authenticated as a tenant or a renter. E.g.: {% if user.userprofile.account == "Host" %} would be a conditional to access the host profile's in my home.html. For now I have the code: {% if user.userprofile.account == "Host" %} <div class="container"> <div class="row"> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" url{% static "images/listing-property.jpg" %}></a> <h4>Create a new listing</h4> </div> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" url{% static "images/your-properties.jpg" %}></a> <h4>Show your rented properties</h4> </div> <div class="home_hover_pictures col-4"> <a href="home.php"><img class="img-responsive" url{% static "images/scroll-others.jpg" %}></a> <h4>Scroll other properties</h4> </div> </div> </div> <!-- Home page for Tenants (not the beer) --> {% elif user.userprofile.account == 'Tenant' %} <!-- … -
Compare object with string in django template
I have two models which I want to output on a template. But only if the parent class object matches to the child class object. {% for market in markets %} {% if object.market|slugify == market.market %} >>> DO SOMETHING <<< {% endif %} {% endfor %} The problem is when I use slugify on the Object it's giving me a string which starts with a small letter but market.market outputs a string with a capital letter. Do someone know a solid solution for that? -
ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build c90ad64e-2c2f-4ad0-a250-160de6f315df status: FAILURE
I am trying to deploy my Django application to gcloud and I keep getting this error, any ideas what this means? File upload done. Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build c90ad64e-2c2f-4ad0-a250-160de6f315df status: FAILURE Error ID: c84b3231 Error type: UNKNOWN -
How to retrieve a json without the use of database?
I want to scrape a website using python and send as json the information that I got to my flutter application without saving it to the database. I don't want to use the Django Restframework database. I want to send a string to the backend and trigger a function that scrapes a certain website and sends back a json to the client. Without using the database.