Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django create a models.ManyToMany and models.ForeignKey to the same table
All, I'm trying to configure my Django models.py file to include 2 tables with a ManyToMany and a ForeignKey link between the 2. The current configuration with only one entry works fine: Current models.py file: from django.db import models class CustTeamMembers(models.Model): member_first_name = models.CharField(max_length = 100) member_last_name = models.CharField(max_length = 100) member_email = models.EmailField(unique=True) member_phone = models.CharField(max_length = 25, blank=True) class Meta(object): ordering = ['member_last_name'] def __str__(self): return self.member_first_name + ' ' + self.member_last_name class CustTeamName(models.Model): cust_name = models.CharField(max_length = 100) cust_members = models.ManyToManyField(CustTeamMembers, blank=True) cust_meet = models.CharField(max_length = 40, blank=True) cust_status = models.TextField(blank=True) def __str__(self): return self.cust_name def get_members(self): return ", ".join([str(p) for p in self.cust_members.all()]) I would like to add another field above the "cust_members" entry. The reason for this is I have teams with multiple members and one of them is the lead for the team. I tried the following, but it failed: Alternate models.py file: from django.db import models class CustTeamMembers(models.Model): member_first_name = models.CharField(max_length = 100) member_last_name = models.CharField(max_length = 100) member_email = models.EmailField(unique=True) member_phone = models.CharField(max_length = 25, blank=True) class Meta(object): ordering = ['member_last_name'] def __str__(self): return self.member_first_name + ' ' + self.member_last_name class CustTeamName(models.Model): cust_name = models.CharField(max_length = 100) cust_lead = models.ForeignKey(CustTeamMembers, on_delete=models.CASCADE, blank=True) … -
Fetch data in many-many relationship in a single row
These are my models Team Table class Team(CommonModel): ****Other Fields**** name = models.CharField() game = models.ManyToManyField(Game, through='Team_Game') Mapper Table class Team_Game(CommonModel): game = models.ForeignKey(Game, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) status = models.SmallIntegerField(default=1) class Meta: db_table = 'team_game' Game Table class Game(CommonModel): name = models.CharField(max_length=128, blank=False, null=False, unique=True) status = models.SmallIntegerField(default=1) I want to retrieve team with id 1 and game associated with it Expected data: team.name, other_team_cols, [game_id1, game_id2] Query: team_data = Team.objects.filter(id=1).values('id', 'name', 'game__name') Output: [ { "id": "1", "name": 'abc', "game__name": "game1" }, { "_packageID": "1", "name": "def", "game__name": "game2" } ] Expected Output: { "id": "1", "name": 'abc', "game__name": ["gam1", "gam2"] } -
Is this possible that we use procedures to insert data but create two models and serializers ?DRF PYTHON
Is this possible that we use procedures to insert data but create two models and serializers . to validate the data because the procedure get fields from two tables? DJANGO REST FRAMEWORK PYTHON -
How to call a function by loading a string in Django?
I'm new to Django and I'm testing, In case I have my posts.html templete and I wanted to load all posts in a summarized form on the page, however one side would load the posts with even id and the other with odd id. I did a function in views.py and wanted to load all posts in posts.html. def posted(request): posts = Album.objects.all() for post in posts: if post % 2 == 0: return render(request, """<div class="container marketing "> <div class="row mb-2 " > <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ post.title }}</strong> <h3 class="mb-0">{{ post.author.get_full_name }}</h3> <div class="mb-1 text-muted">{{ post.created_at|date:'d, M Y'}}</div> <p class="card-text mb-auto">{{ post.summary|safe }}</p> <a href="/post/{{ post.pk }}" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img class="bd-placeholder-img" width="200" height="250" src="{{post.image.url}}" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/></img> </div> </div> </div>""",) return render(request, """<div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-success">Design</strong> <h3 class="mb-0">Post title</h3> <div class="mb-1 text-muted">Nov 11</div> <p class="mb-auto">This is a wider card with supporting text below as a natural lead-in to additional … -
My Django Webblog project is not deploying on heroku
When I am trying to push my Django project on Heroku, each time it's showing this "failed to push some refs to .. " (check my provided screenshot). Even i have created a .gitignore file but even its not working. Here is the screenshot of problems -
Get django model correctly
I am trying to get the value of my model and get the values using a for loop but it gives me this I want it to print Gazou Gazou Gazou Gazou Gazou Gazou [<Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>] My views.py def watchlist(request): if request.method=='POST': name = User.objects.get(username=request.user.username) title = request.POST['title'] print(name) listing = Listing.objects.get(title=title) all_titles = Watchlist.objects.filter(name=name) print(all_titles) print(title) msg = "You already have this on your watchlist" a = [] for item in all_titles: a.append(item) print(a) if title in a: return HttpResponseRedirect(reverse("index")) else: watchlist = Watchlist.objects.create(taitle=title, name=name, title=listing) return HttpResponseRedirect(reverse("index")) else: user = request.user watchlist = Watchlist.objects.filter(name=user) return render(request, "auctions/watchlist.html", { "watchlist": watchlist }) My models.py class Watchlist(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE, null=True) taitle = models.CharField(max_length=100, null=True) title = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.taitle}" I am using django 1.11.29 and python 3.8.5 -
Is there a way to use a Django registered BaseSetting in a models save function?
I am overriding a model's save function to query Google's Geocoding API for the corresponding latitude/longitude coordinates to an address and save them to the model. I have registered a BaseSetting in Django admin with my API keys, and would like to access this registered setting inside my models.py to avoid hard-coding an API key. Handling it in the view is not an option given I would like to minimize the number of API calls. Here's some demo code: class DropoffLocationPage(models.Model): templates = "locations/dropoff_location_page.html" dropoff_address = models.CharField(max_length=40, blank=False, null=False) dropoff_city = models.CharField(max_length=40, blank=False, null=False) dropoff_state = models.CharField(max_length=2, blank=False, null=False) dropoff_zip = models.CharField(max_length=5, blank=False, null=False) dropoff_unit_number = models.CharField(max_length=10, blank=True) dropoff_latitude = models.CharField(max_length=25, blank=True) dropoff_longitude = models.CharField(max_length=25, blank=True) def get_coordinates(address): .... return response['results'][0]['geometry']['location'] def save(self, *args, **kwargs): address = str(self) location = get_coordinates(address) self.dropoff_latitude = location['lat'] self.dropoff_longitude = location['lng'] super(DropoffLocationPage, self).save() def __str__(self): return (self.dropoff_address + " " + self.dropoff_city + ", " + self.dropoff_state + " " + self.dropoff_zip + " " + self.dropoff_unit_number) @register_setting class GoogleAPISetting(BaseSetting): maps_api_key = models.CharField( max_length=255, help_text="Your Google Maps API Key" ) -
How to extend query table for reviews of people I follow with user details
I'm trying to create a Django project, and currently I have three models in use: the standard Django User, Review and Follow, given below: class Review(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text_content = models.TextField(max_length=300) movie_rating = models.IntegerField() class Follow(models.Model): following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="following") follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") What I want to get as a result is given user as a input, get all the reviews of people I follow. I used the following command Review.objects.filter(author__following__follower=user), and it gives me the user_id, text_content and movie_rating, but I'm not sure how to extend this table to add some things from the User model, such as first_name and last_name. -
How to set mode in AES using Django?
I created g-suite signup using Django it's yesterday working fine. but today I will check it throwing error(TypeError: new() missing 1 required positional argument: 'mode'). How to fix this issue. I tried many ways. but it's not working. a.py class rftoken token=models.chearfield() def pad(key): return key+ (BLOCK_SIZE - len(key) % BLOCK_SIZE) * PADDING def aes(self): p = AES.new(settings.COOKIE_SALT) return base64.b64encode(p.encrypt(rftoken.pad(str(self.id)))).decode() if rft: redirect.set_cookie('rtok', rtok.aes(), max_age=10 * 10 * 20 * 200) return redirect When I run the g-suite login code it's throwing this error Error TypeError: new() missing 1 required positional argument: 'mode' -
Celery fails to start using systemd
I am trying to daemonize my celery/redis workers on Ubuntu 18.04 and I get this error message: (archive) mark@t-rex:~/python-projects/archive$ sudo systemctl status celery ● celery.service - Celery Service Loaded: loaded (/etc/systemd/system/celery.service; enabled; vendor preset: enabled) Active: inactive (dead) (archive) mark@t-rex:~/python-projects/archive$ sudo systemctl start celery Job for celery.service failed because the control process exited with error code. See "systemctl status celery.service" and "journalctl -xe" for details. (archive) mark@t-rex:~/python-projects/archive$ journalctl -xe -- Subject: Process /bin/sh could not be executed -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- The process /bin/sh could not be executed and failed. -- -- The error number returned by this process is 3. Dec 17 10:24:39 t-rex systemd[1]: celery.service: Control process exited, code=exited status=217 Dec 17 10:24:39 t-rex systemd[1]: celery.service: Failed with result 'exit-code'. Dec 17 10:24:39 t-rex systemd[1]: Failed to start Celery Service. -- Subject: Unit celery.service has failed -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- Unit celery.service has failed. -- -- The result is RESULT. Dec 17 10:24:39 t-rex systemd[1]: celery.service: Service hold-off time over, scheduling restart. Dec 17 10:24:39 t-rex systemd[1]: celery.service: Scheduled restart job, restart counter is at 5. -- Subject: Automatic restarting of a unit has been scheduled -- Defined-By: systemd -- … -
How can I optimize the speed of this algorithm? Django and Javascript
I am new to Javascript and have decent experience with Django. I built a charting platform for my company to track metrics -- it started as a hobby project to learn Javascript but evolved into something more. The site loads and displays data correctly, but it is unbelievably slow on mobile. All of the calculations are being done on the client-side is JS. There are a lot of metrics to calculate, so the thought process was "Send the client all the Django queries in Object format, and process them there in order to not slow down the server." I also did not want to have a huge block of code processing each metric on the server (am I wrong to do this?). Some questions here: In general, where should I process the data, server-side or client-side? How can I optimize this code? I run 3 queries, and I need to find the number of hits for each metric on every day (page views, opt-ins, and scheduled calls). For example, I want to display a chart showing the number of page views over a month period with the x-axis being the date, and the y-axis being count. In order to do … -
Sending message and notification using Django channels
I am trying to implement a messaging system with live notification so that when a user is chatting with userA and userB messages the user it will update the chat messages live and it will update the user's contact list. I have two consumers, one is ChatConsumer, and another one is the UserChatNotificationConsumer which the latter is a connection for each user and server to a notification to them. And every user channel has a unique id (channel name). inside my ChatConsumer, I have a new_message() function which sends a new message from one user to another user in a private chat. After creating a message object in the new_message() function, I have two methods one which sends the message and another which sends the notification: def new_message(self, data): #create the message and other stuff. await self.send_chat_message_notification_user2(content) await self.send_chat_message(content) And my method for sending a notification to user is: async def send_chat_message_notification_user2(self, message): layer = get_channel_layer() await selg.channel_layer.group_send( self.user2_notification_layer, { 'type':'chat_message', 'message':message } ) Which self.user2_notification_layer is a string id of the second user in the chat notification channel. My issue is that the sockets are being connected successfully and I can see the CONNECT and HANDSHAKE process. however, after … -
need help using django-include-by-ajax
so i tried to use django-include-by-ajax to load the page's main content first and then load the sidebar and navigation stuff when it's ready. i followed the instructions here: https://github.com/archatas/django-include-by-ajax but it didn't work, the page dosen't load until everything is ready (which takes some time because of multiple APIs) and the side bar dosen't even work template: {% extends 'base.html' %} {% load static %} {% load include_by_ajax_tags %} {% block content %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="{% static 'app_name\css\style.css' %}"> {% include_by_ajax "app_name/templates/sidebar.html" %} <div id="content" class="p-4 p-md-5 pt-5"> <div class="row"> <div class="col-1" id="col1"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"> {% if pages.has_previous %} <a class="page-link" href="?page={{ pages.next_page_number }}" aria-label="Next"> <span aria-hidden="true"><img src="{% static 'app_name/images/back.png' %}" width="50" height="50"></span></a> {% endif %} </li> </ul> </nav> </div> <div class="col-1" id="col2"> {% for url in urllist %} <img src='{{ url }}' width="800" height="800"/> {% endfor %} </div> <div class="col-1" id="col3"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"> {% if pages.has_next %} <a class="page-link" href="?page={{ pages.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true"><img src="{% static 'app_name/images/forward.png' %}" width="50" height="50"></span></a> {% endif %} </li> </ul> </nav> </div> </div> </div> <script src="{% static … -
Django - "Foreign key constraint is incorrectly formed"
I'm trying to add a new model to my database, but every time i create it, i get the following error: "Foreign key constraint is incorrectly formed" This happens both if i try from MySQL and Django. Here are my models: class MainApiKeys(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) key_name = models.CharField(max_length=20) public_key = models.CharField(max_length=100, blank=True, null=True) secret = models.CharField(max_length=100, blank=True, null=True) def save(self): # ALL the signature super(MainApiKeys, self).save() class Selected_key(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) used = models.ForeignKey(MainApiKeys, on_delete=models.DO_NOTHING) def save(self): # ALL the signature super(Selected_key, self).save() If i create the same table from MySQL i'll still get the error CREATE TABLE main_selected_key( user_id INT NOT NULL, used INT NOT NULL, FOREIGN KEY (user_id) REFERENCES auth_user(id) ON DELETE CASCADE, FOREIGN KEY (used) REFERENCES main_api_keys(id) ON DELETE CASCADE) The problem is not with the Foreign Key to User, i'm sure it's the second second key because if i remove that one my code will run just fine. What am i doing wrong here? -
Error django " MultiValueDictKeyError at /employeeUpdate/ 'id' " affter I edit data
Error django " MultiValueDictKeyError at /employeeUpdate/ 'id' " affter I edit data. Here my code in views.py def employeeUpdate(request): id = request.POST['id'] emp_username = request.POST['emp_username'] emp_password = request.POST['emp_password'] emp_identification_code = request.POST['emp_identification_code'] content = employee.objects.get(pk = id) content.emp_username = emp_username content.emp_password = emp_password content.emp_identification_code = emp_identification_code if(employee.objects.filter(emp_username=emp_username)): messages.success(request, 'Username already exists') return redirect("/employeeUpdate") elif(employee.objects.filter(emp_identification_code=emp_identification_code)): messages.success(request, 'Identification already exists') return redirect("/employeeUpdate") else: content.save() messages.success(request, 'Update already !!!') return redirect("/employeeBoard") -
Django Models How to
So I'm new to Django and I'm trying to develop a timecard. Employees need to allocate their time to a client's project whether billable or unbillable. They would have to log in, choose to which clients project they worked on, enter time worked and log out. -
form missing 1 required positional argument: 'request'
i have used same code for forms in previous apps but this time it doesnt seem to work, migrations have been done and i have been at this for a day and cant find a good solution of why this form isnt working. def gst_form(request): if request.method == 'POST': form = gst_form(request.POST) if form.is_valid(): form.save() return redirect("/") else: return HttpResponse("Details Invalid") else: form = gst_form() context= {'form':form} return render(request, 'main/form.html', context) -
Why does Django accept email addresses as valid URLs and how can they be rejected?
To my surprise, the following lines pass for a value that is an email address, such as test@example.org: url = 'test@example.org' URLValidator()(url) field = URLField() field.clean(url) Where I would have expected a ValidationError to be raised. Why are email addresses considered valid URLs? And what can I do to accept only domain-like strings other than making my own regex? -
Django displaying images from media file instead of database
How do I display images from media file instead of database? Specifically I want it to load images uploaded by users from media_cdn. I feel like only the views.py require changes but I'm not sure if other areas should be changed as well. Here are my Django codes settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR,"static")] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media_cdn') views.py def imgdownload(request): allimages = ImagefieldModel.objects.all() return render(request, 'main/show.html',{'images': allimages}) urls.py urlpatterns = [ .... .... path("show/", views.imgdownload, name="imgdownload"), .... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class ImagefieldModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "media") class Meta: db_table = "imageupload" show.html {% extends "main/header.html" %} {% load static %} {% block content %} <head> <title>Django Display Images</title> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Title</th> <th>Image</th> </tr> </thead> <tbody> {% for img in images %} <tr> <td>{{img.title}}</td> <td><img src="/{{ BASIC_DIR }}/{{img.img}}" width="120"/></td> </tr> {% endfor %} </tbody> </table> </div> </body> {% endblock %} Any help is much appreciated. -
How to solve page not found error in Django?
I have a list of multiple projects on my page, and each project have a contact use button, if a user click on contact us page then it will open a popup form, and I am doing this using Ajax. But whenever i click on the button it displays page not found in Network(After debug). Please let me know How I can solve thsi issue. Here is my urls.py file... re_path('ajax/datadis/<int:pk>/$', views.dataview, name='dataview'), here is my views.py file... def dataview(request, id): template_name = 'page/ajax/popup.html' return render(request, template_name) here is my index.html file code... <ul class="product-rating"> <button title="Enquire for {{i.name}}" id="id_{{i.id}}" class="btn btn-primary btn-sm" onclick="projectDetail({{i.id}})" data-url="{% url 'appname:projectview' i.id %}">Contact Us</button> </ul> here is my Ajax Code...Which open the Popup Form... </script> function projectDetail(id){ var html = ''; var modalDiv = $("#modalData"); $.ajax({ url: "{% url 'appname:dataview' %}"+id, type:"GET", dataType:"HTML", success: function(res) { modalDiv.html(res); $("#exampleModal").modal("show"); } }); } </script> here is my popup model code... <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" id="modalData"> <p>{{i.name}}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> … -
React Native Apollo + Django: Network Request Failed
I'm very new to programming and couldn't understand how my react native expo app isn't fetching data from my Django server (which is running). How can I resolve this? I've got graphene-django running at the back. Here's my App.js Network Error: Network Request Failed PS. I definitely need more practice on this. Thanks for the help. import React, { Component } from 'react' import { StyleSheet, Text, View } from 'react-native' import { ApolloClient, HttpLink, InMemoryCache } from 'apollo-boost' import { ApolloProvider, gql, useQuery } from '@apollo/client' const client = new ApolloClient({ link: new HttpLink({ uri: 'http://(local-ip-address):8000/graphql' }), cache: new InMemoryCache(), }) const todoQuery = gql` query fetchTodo { todos { rank title content } } `; const TodoComponent = () => { const { loading, error, data } = useQuery(todoQuery); if (loading) return "Loading..."; if (error) return `Error! ${error.message}`; return ( <ul> {data.todos.title.map((title) => ( <li>{title}</li> ))} </ul> ); }; export default class App extends Component { render() { return ( <ApolloProvider client={client}> <View style={styles.container}> <Text style={styles.welcome}>Welcome to React Native!</Text> <Text> <TodoComponent style={styles.welcome}/> </Text> </View> </ApolloProvider> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: … -
Errno 5 Input/output error linked with context_processor
I try to deploy my django app My home page is OK but when I try to loggin, I got an error as mentionned by django debugtoolbar, error is link with variable I declare in my context_processor but, I did not change this files and it works on preprod server moreover, there is a "s" variable in local vars I did not understand and don't where is declare I suspect a "CTRL+s" that did not apply but??? I look for in context_processor and could not find it where this variable can come from to be referenced in local vars djangodebugtoolbar? def data_context_processor(request): site_selectionne = None liste_abreviations_sites = '' language = None pays = [] user_site = [] user_site_type = [] sites = [] user_allowed_to_randomize = False allowed_to_randomize = False user_can_randomize = False can_randomize = False stock_alert = {} stock_confort = {} patients = [] # patients randomized that can be re-allocated # liste des abréviation des sites issue du models Site sous forme de chaine de caractères # pour utilisation dans fonction JS (transmis via data-site dans l'élément navbar-brand du menu _nav.html) for s in Site.objects.all().order_by('sit_ide'): liste_abreviations_sites = liste_abreviations_sites+','+s.sit_abr if request.user.is_authenticated: # site de l'utilisateur connecté user_site = Site.objects.get(profile__user = … -
User directory path for AbstractBaseUser inheritance
I want to upload the avatar to user.id/filename. But I have a problem with this, when I run the migrate Command, I get the following error Problem -
Creating multiple types users in django rest framework, got an unexpected keyword argument 'last_login'
I am trying to learn Django, and I am creating various cases just to exercise and hopefully learn something new. Suppose that I am trying to create different users and assign different permissions latter, but first lets try to create them first. I was researching last night and it is a common problem and many differnt implementations. Most common that I have seen is with student, teacher, admin. My case is similar, but instead of teacher it is Staff as staff member. Staff inherits from User, which itself inherits from AbstractBaseUser. Below is my code for each class, model and serializer. User mode: class User(AbstractBaseUser): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(db_index=True, unique=True) username = models.CharField(max_length=40, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name','username'] objects = UserManager() ## And user manager: class UserManager(BaseUserManager): def get_by_natural_key(self, email): return self.get(email=email) Model: class Staff(User): qualification = models.CharField(db_index=True, max_length=255) department = models.CharField(db_index=True, max_length=10) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'department','username'] objects = StaffManager() def __str__(self): return self.first_name Staff Model Manager: class StaffManager(BaseUserManager): def create_staff(self, first_name, last_name, email, qualification, department, password=None): if email is None: raise TypeError('Users must have an email address.') staff = Staff(first_name=first_name, last_name=last_name, … -
How to automatically link the users table to another table once a user gets registered in django
I am trying to create an e-commerce website, in which I have used the functionality of the Django authentication to allow users to register and login. However, in the registration form, I take the information from 2 tables at once, like this... In my models.py... class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobileNumber = models.CharField(max_length=13) address = models.ForeignKey(Shipping, on_delete=models.DO_NOTHING, default=False) guest = models.BooleanField(default=False) class Shipping(models.Model): addressLine1 = models.CharField(max_length=100) addressLine2 = models.CharField(max_length=100) city = models.CharField(max_length=40) postalCode = models.CharField(max_length=5) landmark = models.CharField(blank=True, max_length=80) And my forms.py... from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile from store.models import Shipping class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() mobile_number = forms.CharField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'mobile_number', 'email', 'password1', 'password2'] class AddressRegisterForm(forms.ModelForm): class Meta: model = Shipping fields = ['addressLine1', 'addressLine2', 'city', 'postalCode', 'landmark'] And finally my signals.py... from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() My information get stored in the relevant tables, however there seems to be no effect on the …