Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Microsoft auth doesn't redirect after successful login
I am integrating Microsoft's login using Django Microsoft Authentication Backend. I have managed to to get a successful response and create a new "Microsoft" user and am able to see it in the admin site if I login to the admin site as a local superuser. When I login using Microsoft, the pop up window to Microsoft opens, authenticates, and it doesn't redirect to anywhere. But, with a local non-Microsoft user, it can successfully redirects to the admin panel. I don't understand why this is so, it doesn't make sense. I have a frontpage constructed that I would like this login page to redirect to after successful login. I have included LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' in the settings.py file but that does not change anything. -
Python selenium send_keys not working on password field
send_keys() works with the username field but not the password field. Here is my code: class PpeLiveTest(LiveServerTestCase): # test that the first cell for the tennessee total row is the correct sum # for quince and allenbrooke for the incentives table def test_sums_incentives_tennessee(self): options = webdriver.FirefoxOptions() options.add_argument("--headless") driver = webdriver.Firefox(options=options) driver.get('https://[redacted]/pr-run-ppe?group=MS%2FTN%2FLA&check_date=05%2F01%2F2022') # login first username_element = driver.find_element_by_id('id_login') username_element.send_keys('[redacted]') password_element = driver.find_element_by_id('id_password') password_element.send_keys(os.environ.get('ADMIN_PASS')) login_button = driver.find_element_by_xpath('/html/body/div/div/div/form/button') login_button.click() I look at driver.page_source in the console when running this test. It's still the login page. username is filled with the [redacted] as expected but the password field is blank. Anyone know why? os.environ.get('ADMIN_PASS') is not blank. password_element is the correct element that we expect -
HTMX does not trigger get on load if it's a radio check
I am working on Django and using htmx I have checkbox input, select tag and radio input both work as expected on page load it sends a request to an endpoint to the server to retrieve certain information which is rendered through a partial template. The problem is only radio deosn't trigger it when the appropriate input value is checked. Here is the radio input. <input id="option_{{ option.id }}" class="form-check-input" type="radio" name="radio_{{ question.id }}" value="{{ option.id }}" {% if question.required %} required {% endif %} {% if question.disable %} disabled {% endif %} {% if option.id == radio_response %} checked {% endif %} hx-get="{% url 'survey:dynamic_loader' %}" hx-trigger="load, change" hx-target="#radio-result-{{question.id}}"/> Is this a normal behaviour for htmx? Or I am doing something wrong. -
How to pass undefined parameters in Serializer DRF?
I have an API in DRF where I want to get information from a non-relational database. The parameters of the API request vary, they can be many or few, and they can change. For this reason, I would like to know how I can pass multiple undefined arguments/parameters to a serializer. # serializers.py class MySerializer(Serializer): foo_1 = IntegerField() foo_2 = CharField() foo_3 = DictField() foo_n = ... ... Instead of this I would like to do this: # serializers.py class MySerializer(Serializer): # have undefined number of parameters # views.py class MyView(APIView): ... def post(self, request): params = requests.data.get('my_params') # dictionary object I'm very new to DRF so I'm not sure how to do it. I found solutions using ModelSerializer, but still I need to define a model, the parameters that I want are undefined in number and datatpye, but the output as a dictionary. -
Factory Boy Iterator generates the wrong order
I use Iterator to create a strict sequence of values. class MyModelFactory(DjangoModelFactory): class Meta: model = MyModel django_get_or_create = ("first_field",) first_field = Iterator(["value_1", "value_2", "value_3", "value_4"]) second_field = Iterator("aaaa", "bbbb", "cccc"]) third_field = Iterator([1, 2, 3, 4]) I expect that result should be next: [ ("value_1", "aaaa", 1), ("value_2", "bbbb", 2), ("value_3", "cccc", 3), ("value_4", "aaaa", 4) ] But the outcome is unpredictable: [ ("value_1", "aaaa", 4), ("value_2", "bbbb", 3), ("value_3", "cccc", 1), ("value_4", "aaaa", 2) ] And when I use this MyModelFactory as a RelatedFactory two times in row, my database raise an error duplicate key value violates unique constraint third_field. Yes third_field must be unique. The question is why does this error occur if I use django_get_or_create? Any ideas? -
Problem with aggregation by annotated fields
I have models: class Publisher(Model): name = TextField() class Author(Model): name = TextField() class Book(Model): publisher = ForeignKey("Publisher") author = ForeignKey("Author") class Magazine(Model): publisher = ForeignKey("Publisher") writer = ForeignKey("Author") I want to know which authors wrote for publishers. My version is this: from django.db.models import TextField, F, Subquery, OuterRef from django.contrib.postgres.aggregates import StringAgg # I use postgres # to lead to the same name books = Book.objects.annotate(author_name=F("author__name")) magazines = Magazine.objects.annotate(author_name=F("writer__name")) books = books.values("publisher_id", "author_name") magazines = magazines.values("publisher_id", "author_name") product = books.union(magazines) # !! here I have a problem with grouping product = product.group_by( "publisher_id" ).annonate( author_names=StringAgg("author_name", ";") ) publishers = Publisher.objects.all().annotate( author_names=Subquery( product.filter(publisher_id=OuterRef("id")).values("author_names")[:1], output_field=TextField() ) ) # I was expecting something like # name | author_names # ------------------------------------------ # Publisher1 | Author1;Author2;Author3 # Publisher2 | Author2 # Publisher3 | Author2;Author3 The problem is that QuerySet has no .group_by() method, instead the .values() method is suggested (product.values("publisher_id").annonate(...)). But this is complicated by the fact that I had previously called .values("publisher_id", "author_name") to bring two different models into the same view. I also tried using .only("publisher_id", "author_name"), but (maybe it's a Django bug) this method can't work together with annotated and normal fields. Is there any way to fix this problem or … -
NoReverseMatch error when filtering from Django ListView ('is not a valid view function or pattern name')
I'm trying to filter the objects from a Django ListView to render them in a template, but I'm getting a 'NoReverseMatch at' error ('Reverse for 'advanced' not found. 'advanced' is not a valid view function or pattern name'). Here are my Model, View, URL, and href: **Model** class Course(models.Model): location = models.ForeignKey(Location, blank=True, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) level = models.CharField(max_length=200) date = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): # establishes canonical url for the Course model return reverse('course_detail', args=[str(self.id)]) **View** class AdvancedListView(ListView): model = Course context_object_name = 'course_list' template_name = 'courses/advanced.html' def get_queryset(self): return Course.objects.filter( level__icontains='Advanced') **URL** from django.urls import path from .views import CourseListView, CourseDetailView, SearchResultsListView, AdvancedListView urlpatterns = [ path('', CourseListView.as_view(), name='course_list'), path('<int:pk>/', CourseDetailView.as_view(), name='course_detail'), path('search/', SearchResultsListView.as_view(), name='search_results'), path('courses/', AdvancedListView.as_view(), name='advanced'), ] **Link** <a class="dropdown-item" href="{% url 'advanced' %}">Advanced</a> Any advice greatly appreciated! -
Calculate the number of deltas between two dates
I want to calculate how many relativedelta() there are between two date objects. My code is below, it's not working though as a relative delata cannot divide a date, but maybe it shows what I'm trying to do. For example, if my relative delta is two weeks relativedelta(weeks=1) and my dates are 2022-05-01 and 2022-05-15 then two of the 1 week deltas will fit into the two dates that are two weeks apart. delta=relativedelta(days= self.cleaned_data['delta_days'], months=self.cleaned_data['delta_months']) no_loops = (self.cleaned_data['to_date'] - self.cleaned_data['from_date']) / delta if no_loops > 36: raise ValidationError('Too many iterations.') -
Django : Updating ForeignKey automatically with 'add' button
Using Python 4.03. I have two models that are connected, with Asset: class Asset(models.Model): Order_Number = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True) Asset_QR = models.CharField(max_length=100, default='') .... more fields below being a child to Order: class Order(models.Model): Order_Number = models.CharField(max_length=100) Customer = models.CharField(max_length=100, default='') Customer_Address = models.CharField(max_length=100, default='') What I'm trying to do is to create a simple "Add" button next to a list of assets that are not attached to any Order yet. I've created a view: def attachassets (request, id): order = Order.objects.get(id=id) #This displays the Order I want to add my assets to assets = Asset.objects.exclude(Order_Number__isnull=False) #This filters to display only Assets that have no Order assigned On my HTML page I display my order info and below it just a simple table which iterates over assets and has and "ADD" button next to them: <table class="table table-hover"> <thead class="thead-dark"> <tr> <th scope="col">Attach</th> <th scope="col">Asset</th> </tr> </thead> <tbody> {%for asset in assets %} <tr> <td> <form action="" method=POST> {% csrf_token %} <button type="submit" class = "btn btn-dark", name="add" value={{order.id}}>Add</button> </td> <td><a class="btn btn-outline-secondary" name="assetid" value={{asset.id}} href='/asset/{{asset.id}}'>{{asset.Asset_QR}} {{asset.Make}} {{asset.Model}} {{asset.Serial_Number}}</a></td> </tr> </form> {% endfor %} </tbody> </table> Then in my Views I tried the following: if request.method == 'POST': x … -
Implimenting a ranking algorithm in Django query
I currently have upvotes and downvotes stored. I am trying to make a ranking algorithm as such ranking = log(upvotes - downvotes) But in doing my query in Django I am using annotate``as such, and am unsure where I would add in the math.log` to the annotate so it ranks it by log? Here is the code defeniciones = Palabra.objects.prefetch_related( 'tag_set' ).filter( nombre__iexact=palabra, aprobada=True ).annotate(total_votes=Count('userUpVotes') - NullIf((Count('userDownVotes')) ,0)).order_by(F('total_votes').desc(nulls_last=True),"total_votes") -
Django CreateView not saving all fields...but UpdateView does
I'm using Django CBV's to allow managers to add and update user information in the front end. When I create a new user, two of the fields are not saved to the database; Django's built in permission groups, and a manytomanyfield that determines what newsfeeds the user can view. The strange thing is, when I update the user using an updateview, it saves just fine. No errors when I submit on the createview, and all o Am I missing something blatantly obvious here? Both templates are laid out the same, both with enctype="multipart/form-data" method="post" . Django 4.0.4 / Allauth Model: class CustomUser(AbstractUser): #auth id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False, primary_key=True) username = models.CharField(max_length = 50, blank=True, null=True, unique=True) email = models.EmailField(gettext_lazy('email address'), unique=True) #Employment info department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=False) job_title = models.CharField(max_length = 50, null=True, blank=False) #Personal Info profile_picture = ProcessedImageField( upload_to='profile_images/', processors=[ResizeToFill(width=1000, height=1000, upscale=True)], format='JPEG', options={'quality': 100}, null=True, blank=True ) # Newsfeeds viewable_newsfeeds = models.ManyToManyField(Department, blank=True, related_name='viewable_newsfeeds') #Permissions department_head = models.OneToOneField(Department, related_name='department_head', on_delete=models.SET_NULL, unique=True, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'job_title'] class Meta: ordering = ['first_name',] verbose_name = "User" verbose_name_plural = "Users" permissions = [ ('manager_dashboard', 'Can view the manager dashboard'), ('manager_content', 'Can view … -
How to get the code returned by Cognito Hosted UI Autentication in Django?
I want to implement the Cognito Hosted UI for some users in my Django application. I have successfully been able to redirect the users to the desired url for authentication using the following: return redirect(https://....amazoncognito.com/oauth2/authorize?client_id=....redirect_uri=localhost). I am able to successfully authenticate and redirect back to my localhost where the url in the browser is localhost/?code=xyz. I do not understand how I can retrieve this code xyz back in python to perform next steps? I see that in the Django Terminal that it reads the required code. This is what the terminal shows: [04/May/2022 16:08:15] "POST /login HTTP/1.1" 302 0 [04/May/2022 12:09:04] "GET /?code=xyz HTTP/1.1" 200 8737 I just do not know how to get this code xyz in my views.py so that I can continue the login. I tried variations of request.GET that did not work. Any help is appreciated!! -
Django export-import admin
I am trying to import a json file to my database with Django export-import extension. but when i try to import i get this error msg "Line number: 1 - 'id' 20, 2, 1, CONTAINER1134, 26.30, 10, 1, 1, 3 Traceback (most recent call last): File "/Users/tiberiuminzat/.local/share/virtualenvs/redrock-planning-system-I02kV_z2/lib/python3.10/site-packages/import_export/resources.py", line 661, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/Users/tiberiuminzat/.local/share/virtualenvs/redrock-planning-system-I02kV_z2/lib/python3.10/site-packages/import_export/resources.py", line 353, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/Users/tiberiuminzat/.local/share/virtualenvs/redrock-planning-system-I02kV_z2/lib/python3.10/site-packages/import_export/resources.py", line 340, in get_instance import_id_fields = [ File "/Users/tiberiuminzat/.local/share/virtualenvs/redrock-planning-system-I02kV_z2/lib/python3.10/site-packages/import_export/resources.py", line 341, in self.fields[f] for f in self.get_import_id_fields() KeyError: 'id'" models.py class Subtask(models.Model): subtaskID = models.IntegerField(primary_key=True, auto_created=True) operationID = models.ForeignKey('Operation', on_delete=models.CASCADE) assignee = models.ForeignKey('Employee', on_delete=models.CASCADE) containerID = models.CharField(max_length=255) containerWeightT = models.DecimalField(max_digits=6, decimal_places=2) loadSeq = models.IntegerField() moveTo = models.ForeignKey('MoveTo', on_delete=models.CASCADE) stow = models.ForeignKey('Stow', on_delete=models.CASCADE) status = models.ForeignKey( 'Status', on_delete=models.CASCADE) resources.py from import_export import resources from redrock.models import Subtask class SubtaskResource(resources.ModelResource): class Meta: model = Subtask import_id_fields = ('subtaskID') admin.py class SubtaskAdmin(ImportExportModelAdmin): list_display = ['subtaskID', 'operationID','assignee', 'containerID', 'containerWeightT', 'loadSeq', 'moveTo', 'stow', 'status'] list_editable = ['containerID', 'containerWeightT', 'loadSeq', 'status','assignee'] list_filter = ['operationID', 'status'] list_per_page = 10 def status(self, operation): return operation.status.status json [{"subtaskID": 20, "operationID": 2, "assignee": 1, "containerID": "CONTAINER1134", "containerWeightT": "26.30", "loadSeq": 10, "moveTo": 1, "stow": 1, "status": 3}] -
Django send full QuerySet in Channels
I am using Django Channels to build a game. It's a super simple multiplayer chance game. After user clicks a button the game starts and the server receives the data via Channels. I do the necessary calculations, database updates etc. Now I want to send data back to the browser. I do a filter query from the database and I would like to send the whole query back. I know I could take out the necessary data one by one and send them separately but I feel like there's a better way but I just can't figure it out. When I would send the QuerySet like in views.py I get a TypeError: Object of type QuerySet is not JSON serializable. Sending the query using list() also gives me an error ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. Is there a way I could send the whole QuerySet with Channels? consumer.py async def send_message(self, event): room_name = event['room_name'] roomObj = cbr.objects.filter(room_name=room_name) cbObj = cb.objects.filter(room=roomObj) #cbObj is what I would like to send await self.send(text_data=json.dumps({ 'cb': cbObj # Gives TypeError })) -
insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id"
I have looked at a bunch of similar posts and none seem to give me the answer I need. When I try to add data to a model via the Django Admin site, it gives me this error: IntegrityError at /admin/api/appuser/ 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)=(2) is not present in table "auth_user". When I looked at my database, the table auth_user did only have one entry with user_id 1. So it does make sense that the error is thrown. However, I am not sure why it is even looking at the auth_user table in the first place because I have another table called api_appuser where my actual users are stored. In this table, there is a user with id 2. So, can anyone help me figure out why this error is being thrown and why admin.py is looking at the auth_user table in the first place? Thanks! Also, I am using Postgres as my database if that matters. Full traceback: Traceback (most recent call last): File "/Users/jhcscomputer1/.local/share/virtualenvs/senior_project-hOu14Mps/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.ForeignKeyViolation: 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)=(2) is not … -
How to add Icons in Django forms creating forms from Models
i am newbie in python, i'm try to create forms from models in django. I need to put icons in the html5 lines i'm using fontawesome and i can put icon if i add the html codeline but i need to bring the variable "fa fa-shower" or "{icon name}" from my forms.py my code in forms.py is: class LoginForm(forms.ModelForm): class Meta: model = User fields = ['username', 'password'] icons = { 'username': 'fa fa-user', 'password': 'fa fa-lock', } labels = { 'username': 'User/Correo: ', 'password': 'Contraseña ', } widgets = { 'username': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.TextInput(attrs={'class': 'form-control'}), 'password': forms.PasswordInput(attrs={'class': 'form-control'}), } class iconModelForm(LoginForm): def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) icons = getattr(self.Meta, 'icons', dict()) for field_name, field in self.fields.items(): if field_name in icons: field.icon = icons[field_name] how can pass the context of two classes from view to html? my views.py is: class LoginLocal(View): def get(self, request): contexto = { 'formLogin': LoginForm(), # 'formIcon': iconModelForm(), } print(contexto) return render(request, 'login_reg_app/login.html', contexto) and how can i read two list in the same for in html? I tried to use ZIP but it showed error. my file login.html is: <form action="{% url 'login_reg_app:login' %}" method="post" > {% csrf_token %} {{ formLogin.non_field_errors }} … -
Django Custom Forms in Formsets using CBV
I want to create a new site and add corresponding publications at the same time. I have to use a custom made form for the "site" due to the large dataset linked to it through the "municipality" foreign key. I have these models: class site(models.Model): sid = models.AutoField(primary_key=True) site_name = models.CharField(max_length=250) site_notes = models.CharField(max_length=2500, blank=True, null=True) municipality = models.ForeignKey('local_administrative_unit', on_delete=models.PROTECT) geom = models.PointField(srid=4326) def __str__(self): return '{}, {} ({})'.format(self.sid, self.site_name, self.municipality) lass cit_site(models.Model): cit_site_id = models.AutoField(primary_key=True) publication = models.ForeignKey('publication', on_delete=models.PROTECT) site = models.ForeignKey('site', on_delete=models.PROTECT) first_page = models.IntegerField(null=True, blank=True) last_page = models.IntegerField(null=True, blank=True) notes = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return '{}: {} - {}'.format(self.publication.pub_id, self.first_page, self.last_page) The site form at the moment just adds a site through a class based view. Because of the large dataset of municipalities, loading the form would take forever and it wouldn't be very handy to actually choose the right municipality (16k+ records in this table atm), so i made this custom form: class NewSiteForm(DynamicFormMixin, forms.Form): def land_choices(form): country = form['country'].value() return models.administrative_level_4.objects.filter(adm_level_5=country) def land_initial(form): country = form['country'].value() return models.administrative_level_4.objects.filter(adm_level_5=country).first() def district_choices(form): land = form['land'].value() return models.administrative_level_3.objects.filter(adm_level_4=land) def district_inital(form): land = form['land'].value() return models.administrative_level_3.objects.filter(adm_level_4=land).first() def town_choices(form): district = form['district'].value() return models.administrative_level_2.objects.filter(adm_level_3=district) def town_initial(form): district = … -
Update other fields from data returned in ajax call using select2
I have a working select2 field which updates based on the results of the ajax call, what i now want to do is up two other fields in my template using some of the data which is returned in the ajax call. The below is the script so far <script> $(document).ready(function () { $('#id_site').select2({ theme: 'bootstrap4', placeholder: "Select a site", ajax: { url: '{% url 'site-view-ajax' %}', dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.site_name }; }) }; } }, minimumInputLength: 3 }); }); </script> What i then want to do is access two additional fields from the returned data and update my template. <script> $(document).ready(function () { $('#id_site').select2({ theme: 'bootstrap4', placeholder: "Select a site", ajax: { url: '{% url 'site-view-ajax' %}', dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.site_name, code: item.site_code, address: item.site_address }; }) }; } }, minimumInputLength: 3 }); }); </script> and then something like the below document.getElementById("id_site_code").value = item.site_code; document.getElementById("id_site_address").value = item.site_address; Im just not sure how i would go about this as i have very limited javascript knowledge. Thanks -
Django Tutorial - TemplateDoesNotExist at /polls/, Can't find the template mentioned when following DJango Tutorial
I have looked at other Stack Overflow Questions similar to this, but they were old like 2010, and didn't help my situation Hello, I was following the Django Tutorial to the header, A shortcut: render() on the site. But when I try to get to the site, it says that the Template doesn't exist when the templates routing. I need the template to be found by the view and rendered to the poll, where it is currently showing the error. I have added the tutorial I followed, image with issue page, folder structure, and views page. If you need anything else, let me know and I will provide the information Site: https://docs.djangoproject.com/en/4.0/intro/tutorial03/ Image: Settings: """ Django settings for django_site project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-na%t!8gq9w!asng#=_oe+r2k&xos3fo^x5vcg&dye(#6@=3(60' # SECURITY WARNING: don't run with debug turned on in … -
how to continue on react port 3000 after OAuth 2.0 callback fired in django port 8000
My application is built by React frontend and Django backend. Although the React part is in the frontend folder inside Django project, I try to make both parts as independent as they can. So basically, Django only server as API provider, and React control the entire frontend. In the dev mode, Django run on localhost with port 8000; React run on port 3000. I have completed CORS setting in my setting.py CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000' ] So basically, I can test both frontend and backend quite independently. All Api fetching also works properly between Django and React. However, in my app, I also need to connect to Spotify API to do something. During the authentication process, I need to provide Redirect url for Spotify authentication callback. The url I register in Spotify is: http://127.0.0.1:8000/api-spotify/callback in my urls.py: from .views import get_auth_callback urlpatterns = [ path('callback', get_auth_callback), ] In view.py: def get_auth_callback(request): code = request.GET.get('code') response = post('https://accounts.spotify.com/api/token', data={ 'code': code, 'redirect_uri': env.str('REDIRECT_URL'), 'grant_type': 'authorization_code', 'client_id': env.str('CLIENT_ID'), 'client_secret': env.str('CLIENT_SECRET') }).json() access_token = response.get('access_token') token_type = response.get('token_type') refresh_token = response.get('refresh_token') expires_in = response.get('expires_in') edit_user_token(request.session.session_key, refresh_token, access_token, expires_in, token_type) return redirect('/') The problem is in the final line: return redirect('/') If I login … -
How do I auto-assign Django ModelForm fields to a CustomUser?
I'm putting a form on the frontend of my website, and I can't figure out how to auto-assign a specific ModelForm field to the currently logged in user. I've created a custom user with email as the unique ID. I can load the page & submit the form fine, but it doesn't save to the logged in user, and I can't see the saved information on the admin. I use a separate model to base my ModelForm off of, and one of the fields is a foreign key that references the email of the CustomUser. I've included my CustomUser Model, a separate model for the ModelForm, the ModelForm itself, and the View. Any help or suggestion is appreciated! See my code below: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length = 100, unique = True) first_name = models.CharField(max_length = 50, verbose_name='first name') last_name = models.CharField(max_length = 50, verbose_name='last name') date_joined = models.DateTimeField(auto_now_add = True, verbose_name='joined') last_login = models.DateTimeField(auto_now = True, verbose_name='last login') is_active = models.BooleanField(default = True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default = False) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQIURED_FIELDS = [] def get_user_email(self): return self.email def get_user_name(self): return str(self.first_name) + str(self.last_name) def has_perm(self, perm, obj = … -
Django form optional field still required error
I have in my model the following fields: field1 = models.CharField(max_length=63, null=True, blank=True) field2 = models.CharField(max_length=255, null=True, blank=True) and in my form, which extends ModelForm, I haved added: field1 = forms.CharField(required=False) field2 = forms.CharField(required=False) class Meta: model = TestForm fields = [ 'another_field', 'field1', 'field2' ] But if I don't fill field1 and field2, I get the following error: TestForm with errors: <ul class="errorlist"><li>__all__<ul class="errorlist nonfield"><li>You must specify either a field1 or a field2</li></ul></li></ul> AFAIK I woudn't even need to set required=False since the model has already set null and blank as true, so what am I missing? Thanks in advance. -
Python Django - intiating and terminating a python process according to user input, how should I approach it?
Let's make sure I am understanding this right first: Essentially, django server (or servers in general) are indefinite python scripts, right? Now some context, I'm building an application with a continuously running sub-process, by default. It is running until it is being told no to anymore, i.e terminating the script. I want to have the option to start and finish this process AND I want to do this via user input from a django server. So when the user decides to intiate the scipt it will continue running even if the user closes the webpage. How might I approach having such design? How will I start the script when the user instructs so, and how will I close it? I was thinking perhaps threading could do the job. As the server runs froever, whenever the user wants to start the sub-process a thread will start and when they want to close the script they will close the thread. However, the subprocess is a python file of its own, and I am not sure how it will work with threading. Or Maybe using a state variable in the user database. Whenever the user changes the input in a website change the … -
AssertionError at /Password_changed_succesfully/ No exception message supplied
I am trying to implement the reset password process in django, it works fine and it change the password, but it raise an error in the end after submiting the new password I don't know why urls.py file: """travel URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('',include('loginpage.urls')), path('signup/',include('signup.urls')), path('homepage/',include('Homepage.urls')), path('password_reset/',auth_views.PasswordResetView.as_view(template_name='loginpage/resetpassword.html'),name='password_reset'), path('password_reset_sent/',auth_views.PasswordResetDoneView.as_view(template_name='loginpage/password_resent_sent.html'),name='password_reset_done'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='loginpage/password_reset_form.html'),name='password_reset_confirm'), path('Password_changed_succesfully/',auth_views.PasswordResetConfirmView.as_view(template_name='loginpage/password_reset_done.html'),name='password_reset_complete') ] resetpassword.html: <!DOCTYPE html> <html> <head> {% load static %} <title>Reset Password</title> <link rel="stylesheet" type="text/css" href="{% static 'reset.css' %}"> <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css" /> </head> <body> <div class="right"><img src="{% static 'images/logo2.png' %}" height="400" width="400"></div> <div class="main"> <input type="checkbox" id="chk" aria-hidden="true"> <div class="resett"> <form method="post"> {% csrf_token %} {{form}} <input type='submit' name=" Send email"> </form> </div> </div>> </body> … -
Django does not create a model instance every single time from Views
I basically have two models, Person and Profiles which have a OneToOne relationship with each other. The Profiles models consists of a set of BooleanFields which indicate whether the Person has social media profiles. #models.py class Person(models.Model): name = models.CharField(max_length=256) address = models.TextField() dob = models.DateField() class Profiles(models.Model): person = models.OneToOneField('Person', on_delete=models.CASCADE, related_name='profiles') fb = models.BooleanField(default=False) twitter = models.BooleanField(default=False) insta = models.BooleanField(default=False) linkedin = models.BooleanField(default=False) Now, as soon as a Person model instance is created, I want to create a corresponding Profiles model instance. Towards this end, in the views.py file, as soon as the form with the Person attributes is created, I instantiate a Profiles class with the person being the just created instance. Like below: #views.py def upload(request): if request.method == 'POST': form = PersonUploadForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() prof = Profiles(person=instance) prof.save() else: context = {'form': form} return render(request, 'template.html', context) else: form = PersonUploadForm() context = {'form': form} return render(request, 'template.html', context) Now the issue, I'm facing is that prof = Profiles(person=instance) and prof.save() don't work 100% of the time. I know this because Person and Profiles models don't have the same number of objects when they theoretically should be the same. I am …