Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django same function data not showing after page render
I am creating university management system using django. I have created faculty(teacher) registration form. For that, in my views.py def faculty_registration(request): data = {} form = FacultyRegisterForm() activetab = 'list' if request.method == 'POST': activetab = 'add' form = FacultyRegisterForm(request.POST) if form.is_valid(): userdata = User() if User.objects.filter(username=request.POST.get('email')).exists(): messages.error(request, f"This email already exists.") return redirect('/faculty/faculty_registration') else: userdatafirst_name = request.POST.get("first_name") userdata.username = request.POST.get('email') userdata.email = request.POST.get('email') try: fac_ID = Faculty.objects.last().id except: fac_ID = 0 LastInsertId = fac_ID+1 print('after_id',LastInsertId) password = User.objects.make_random_password() faculty_pw = password+str(LastInsertId) print("pass",faculty_pw) userdata.password = make_password(faculty_pw) print( "teacher_pasword",userdata.password) userdata.save() fac = Faculty() fac.faculty_college_id = request.POST.get("faculty_college") fac.faculty_programme_id = request.POST.get('faculty_programme') fac.salutation = request.POST.get("salutation") fac.first_name = request.POST.get("first_name") fac.middle_name = request.POST.get("middle_name") fac.last_name = request.POST.get("last_name") fac.phone = request.POST.get("phone") fac.email = request.POST.get("email") fac.address = request.POST.get('address') fac.department = request.POST.get('department') fac.highest_qualification = request.POST.get("highest_qualification") fac.years_of_experience = request.POST.get('years_of_experience') fac.previous_institute = request.POST.get('previous_institute') # fac.documents = request.POST.get("documents") if 'documents' in request.FILES: filename = request.FILES['documents'] if str(filename).lower().split('.')[-1] == 'pdf': if int(len(request.FILES['documents'].read())) < (3 * 1024 * 1024): fac.documents = request.FILES['documents'] else: messages.warning(request, "please upload a pdf within 3 mb") navshow = 'add' return redirect('faculty_registration') else: messages.warning(request, "please upload a pdf") navshow = 'add' return redirect('faculty_registration') fac.photo = request.FILES.get('photo', 'faculty_picture/def.png') fac.created_by_id = request.user.id fac.user_id = userdata.id fac.save() assign_role(userdata, 'teacher') html_content = render_to_string("email_template.html",{'title':'Kindly Note your … -
Retrive data from Database
1- am making a sample project for my learning I have a html code and how to retrieve data's from database through this code in Django Blood Group O+ O- A+ A- B+ B- AB+ AB- 2- after press search i need to display a selected blood groups results in that / new page 3- my views.py code as follows def search(request): return render(request,'search.html') and in database table name = home_index_bgs column names as follows NAME FATHERS NAME GROUP GENDER DONATED any one can help with this problem for this, its only for educational purpose not for any kind of project -
How can I get the records (of a specific model) of both request.user and a specific user?
I am not very professional in django rest... I wrote a blog with django rest framework and There is no problem when I want to get all the records related to the Article model or get a specific article, for example But what I want to do is to send an user id(or an user name) to the view when I click on the user's name. and as a result display all the records of the Article model related to the request.user and all the records of the Article model related to the user whose name was clicked. In fact, I want to click on the name of each user, in addition to getting the Articles of that user, the Articles related to the request.user will also be taken This is what I have done so far... #models.py class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField author = models.ForeignKey(User , on_delete = models.CASCADE) content = models.TextField(null = True) publish = models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) status = models.BooleanField(default = False) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) pic = models.ImageField(upload_to="img", blank=True, null=True) def __str__(self): return self.user.username … -
Related object does not exists in django only admin login
showing RelatedObjectDoesNotExist in Django only when admin login all others can log in make changes and works fine. I am doing an crud application with user interface -
Django Summernote icons dont appear
I am working on a MAC and Windows for this issue. Summer note will not display icons in chrome or edge on either Mac or windows and deployed or locally. Everything works fine in safari and on my iPhone. I migrated and collected the static files and they showed up in my s3 bucket. Seems like everything is set up correctly since it does work. settings.py INSTALLED_APPS = [ 'django_summernote', ] SUMMERNOTE_THEME = 'bs5' SUMMERNOTE_CONFIG = { 'summernote': { 'width': '100%', } } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/', include('django_summernote.urls')), ] forms.py from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget class CreateVenueForm(ModelForm): class Meta: model = Venue fields = ('name', 'address', 'city', 'state', 'zip', 'description',) widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Gived your venue a title'}), 'address': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Number and Street name'}), 'city': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'city'}), 'state': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Give your event a title'}), 'zip': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Zip'}), 'description': SummernoteWidget(), } template <div class="row"> <div class="col">{{form.description.label}}<br/>{{form.description|safe}}</div> </div> -
Implement adding an image from gallery to favourites, which is displayed on a separate page// DJANGO/JS
Essentially I am creating a web gallery with Django/JS for a project, however the project needs to feature CRUD functionality. Currently I have a functioning modal when an image in the gallary is clicked, along with an "Add to Favourites" button when the user is logged in. I am struggling to come up with a way to append these images dynamically to the favourites HTML page. I am unsure whether this is easier done with JS or Django. Here is my current JS code: $(function() { $('.myImg').each(function() { $(this).click(function() { $('#myModal').css('display', 'block') $('#imgModal').attr('src', this.src) $('.navbar').css('display', 'none') }) /* Favourite image functionality */ var favouriteImages = [] imgSrc = $(this).attr('src', this.src); $('#favourites-btn').click(function () { favouriteImages.push(imgSrc) }) }) $('.close').each(function() { $(this).click(function() { $('#myModal').css('display', 'none') $('.navbar').css('display', 'flex') }) }) }) favouriteImages.forEach(function() { $('#favourites-gal').append(<img class='myImg'/>) }) At the bottom, with the favouriteImages.forEach function, I dont know how to include the src of the specific image that is being appended after clicking the Add to Favorites button. For reference: In the actual gallary of images the code structure of the HTML is: <div class="gal"> <img class="myImg" src="{% static 'img/artsy-gallery/artsy1.webp' %}" alt=""> <img class="myImg" src="{% static 'img/artsy-gallery/artsy2.webp' %}" alt=""> <img class="myImg" src="{% static 'img/artsy-gallery/artsy3.webp' %}" alt=""> … -
MYSQL Database Copy Using Python/Django
I need to create a copy of the database in my MySQL Server using Django Application After a little research, i found mysqldump as the better approach backup_file_path = f"/tmp/{src_database_name}_backup.sql" backup_db_command = f"mysqldump -h {SQL_DB_HOST} -P 3306 -u {SQL_DB_USER} -p{SQL_DB_PASSWORD} {src_database_name} > {backup_file_path}" print(backup_db_command) # TODO: remove with os.popen(backup_db_command, "r") as p: r = p.read() print(f"Backup Output: {r}") restore_command = f"mysql -u root -p{SQL_DB_PASSWORD} {dest_database_name} < {backup_file_path}" with os.popen(restore_command, "r") as p: r = p.read() print(f"Restore Output: {r}") My Queries: Any issues with this approach Any better approaches to do a copy of DB using Either python or Django ORM -
how to properly apply createview?
I have two models, author and book where the book is related to author, now I don't know how to add books to a specific author that I'm working with and redirect the user back to the detailview of that author, I'm also using inlineformset_factory.enter image description here I want to redirect the user to the detailview of the selected author, I also tried overriding the get_absolute_url in the models but it gives me error stating that there are no url to redirect to, I already checked the url names and I'm using the right one.enter image description here -
Serve TailwindCSS with django_plotly_dash
I have a Dash app in Django being served via django-plotly-dash and I'm using Tailwind for the styling across the site. Tailwind seems to be working everywhere except for the Dash app, where it is kind of working, but seems to be overwritten by the Bootstrap at some points. I can see the Tailwind styling without any issues if I run the Dash app on its own, but not when embedded in Django. Here's the view inside Django (and the code for this basic example): And here it is (with garish colors to see the difference) while running Dash and Tailwind without Django: Some of the Tailwind styling is being applied, such as the container mx-auto bit of the Dash layout, but others (e.g. coloring) are being dropped. Here's the code for the Dash app, which is split into layout.py, callbacks.py, and dashboard.py: layout.py: from dash import dcc, html layout = html.Div( className="bg-green-100 container mx-auto my-auto px-15 py-5", children=[ html.Div( className="bg-red-100 py-5", children=[ dcc.Dropdown( id="symbol-input", options=[ {"label": "Apple", "value": "AAPL"}, {"label": "Tesla", "value": "TSLA"}, {"label": "Meta", "value": "META"}, {"label": "Amazon", "value": "AMZN"} ], searchable=True, value="AAPL", ) ]), html.Div( className="max-w-full shadow-2xl rounded-lg border-3", id="price-chart" ) ] ) callbacks.py: from dash import … -
How can I serialize a Many to Many field with added data in Django Rest Framework, without extra keys in the response?
I am using Django 3.2 and Django Rest Framework 3.14. I have Users that should be able to follow other Users, like on a social networking site. When serializing a full User, I would like to get a list of those following Users, as well as additional data, such as the follow datetime. However, I would like the response to stay "flat", like this: { "username":"admin", "followers":[ { "username":"testuser", --additional user fields-- "follow_date":"2023-02-08 01:00:02" }, --additional followers-- ], --additional user fields-- } I can only seem to go "through" my join model using an extra serializer, and end up with this: { "username":"admin", "followers":[ { "user":{ "username":"testuser", --additional user fields-- }, "follow_date":"2023-02-08 01:00:02" }, --additional followers-- ], --additional user fields-- } Note how there is an additional user key "user":{ "username":"testuser", --additional user fields-- }, I don't want that there! My model looks something like this: class Follower(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, related_name="followers") follower = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, related_name="following") follow_date = models.DateTimeField(auto_now_add=True) My serializers look like this (extra fields trimmed for brevity): class UserSnippetSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class FollowerSerializer(serializers.ModelSerializer): user = UserSnippetSerializer(source='follower') class Meta: model = Follower fields = ['user', 'follow_date'] class FullUserSerializer(serializers.ModelSerializer): followers = FollowerSerializer(source='user.followers', … -
Django Many to Many Field Set in Model Save Method
I am trying to override the save method in a model with logic to update a couple of many to many fields. Using print statements I can see values updating as expected but the values are not persisted after save. In the below model the change_access_flag is changing as expected with a signal, the prints are executing with the appropriate values, but the allowed_departments and allowed_communities fields are not updating with the printed values. Model class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(null=True, blank=True, max_length=50) payroll_id = models.CharField(null=True, max_length=20) position = models.ForeignKey(Position, null=True, on_delete=models.SET_NULL) primary_community = models.ForeignKey(Community, null=True, on_delete=models.CASCADE, related_name="primary_community") region = models.CharField(max_length=2, choices=RegionChoices.choices, blank=True, null=True) allowed_communities = models.ManyToManyField(Community, blank=True, related_name="allowed_community") allowed_departments = models.ManyToManyField(Department, blank=True) access_change_flag = models.BooleanField(default=False) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Meta: verbose_name_plural = "People" ordering = ['position__position_code', 'user__last_name', 'full_name'] def save(self, *args, **kwargs): #Set Full Name field if self.user.last_name: self.full_name = f'{self.user.first_name} {self.user.last_name}' super().save(*args, **kwargs) #Change flag set in signals, set for events that require updating access settings if self.access_change_flag: self.access_change_flag = False #Allowed community access access_level = self.position.location_access_level self.allowed_communities.clear() if access_level == 'R': if self.primary_community.community_name == '#': region = self.region else: region = self.primary_community.region if region is not None: communities = Community.objects.filter(region=region) self.allowed_communities.set(communities) self.allowed_communities.add(self.primary_community) … -
Django Forbidden (CSRF token missing.)
I am facing a problem to submit a text in Django. When I click Insert, the message Forbidden (CSRF token missing.): appears. Can somebody help me? I put the CSRF token in the html file, but still no working. I do not know if the csrf is in the wrong part of the code or not. csrf_token %} load crispy_forms_tags %} Modal Header --> Show gabarit × Modal body --> {{commande}} if formset %} Variables endif %} <div id="modal" style="display:none;"> <div id="variables-container"></div> <button class="mb-2 btn btn-outline-secondary mr-2" id="insert-button" type="button" onclick="closeModal()">Insérer <div id='result'></div> </div> </div> </div> <script> function openModal() { var inputText = document.getElementById("input-text").value; var variableNames = inputText.match(/{(.*?)}/g); var variablesContainer = document.getElementById("variables-container"); variablesContainer.innerHTML = ""; for (var i = 0; i < variableNames.length; i++) { var variableName = variableNames[i].slice(1, -1); variablesContainer.innerHTML += "" + variableName + ":"; } document.getElementById("modal").style.display = "block"; } function closeModal() { var inputText = document.getElementById("input-text").value; var variableNames = inputText.match(/{(.*?)}/g); for (var i = 0; i < variableNames.length; i++) { var variableName = variableNames[i].slice(1, -1); var variableValue = document.getElementById("variable-"+ variableName).value; inputText = inputText.replace(variableNames[i], variableValue); } document.getElementById("input-text").value = inputText; document.getElementById("modal").style.display = "none"; document.getElementById("variables-button").style.display = "none"; var xhr = new XMLHttpRequest(); xhr.open("POST", "{% url 'gabarits:save-variables-text' %}", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange … -
Getting Bad Request from POST to DailyWc Model with a ForeignKey to Projects
I'm making a writing app using Django backend and Vue 2 frontend. I have two models— DailyWc and Project. Every day, when the user goes to the site, a new day is created for them to store text (DailyWc handles this). I wanted it to be possible for the user to also assign the text to a Project, with the default being "Unassigned." So, Project is associated with multiple dailywcs. There's a button on my site that the user can press to save their progress for the day. This is where my trouble comes in— I can't make post or update calls because I'm getting Bad Request. My understanding is that I should be able to just pass in the associated project id to make this work, but I think the DailyWc model as it is now is expecting a whole Project object with related fields. My models: # Create your models here. class Project(models.Model): name = models.CharField(max_length=255, default="Unassigned") start_date = models.DateField("today's date", default=datetime.date.today) end_date = models.DateField("end date", default=datetime.date.today) word_count_goal = models.PositiveIntegerField(default=0) def __str__(self) -> str: return f'The Project {self.name} started on {self.start_date} and will end on {self.end_date} with a goal of {self.word_count_goal} and an id of {self.id}.' class DailyWc(models.Model): … -
The current path didn’t match any of these. Django Project/ Learning_Log
I am studying working with Django from a book Python Crash Course by Eric Matthes. I follow all recommendations and write code one-to-one like in a book, but i have encountered such a problem. I cant go to detailed topic page from a topics link, but manually i can. Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ users/ [name='index'] topics/ [name='topics'] topics/<int:topic_id>/ [name='topic'] new_topic/ [name='new_topic'] new_entry/<int:topic_id>/ [name='new_entry'] edit_entry/<int:entry_id>/ [name='edit_entry'] The current path, topics/% url 'learning_logs:topic' topic.id %, didn’t match any of these. So, my code is presented below. I really don't understand what i do wrong. My url patterns: from django.urls import path, re_path from . import views app_name = 'learning_logs' urlpatterns = [ # Home page path('', views.index, name='index'), # Page with the list of all topics path('topics/', views.topics, name='topics'), # Page with detailed topic information path('topics/<int:topic_id>/', views.topic, name='topic'), ] topics templates {% extends "learning_logs\base.html" %} {% block content %} <p> Topics</p> {% if topics %} <ul> {% for topic in topics %} <li> <a href="% url 'learning_logs:topic' topic.id %">{{ topic }}</a> </li> {% endfor %} </ul> {% else %} <p>No topics have been added yet.</p> {% endif %} <a href="{% url … -
How can I use Visual Studio Code to debug Django with an IP address defined by myself? (By that I would test my app on an android phone)
I'm aware that when I set up my server with python manage.py runserver [my custom IP address] I can choose what IP and port will be chosen. But when I use VScode in debug mode I don't know where I can define the server other than 127.0.0.0.1:8000. Having 127.0.0.0.1:8000 I can access the page just by my pc (win 10). I need to change the address, because I'm unable to open my page on my android phone (for testing with this debugger), but I don't know where and how. -
Check either someone has clicked a post or not within the template django
I have this model struture: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=1200, blank=True) class PostLike(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Template for post in posts ... # want to check here, something like: if post.userliked write something endif ... endfor Now what I want is to check either the current loggedin user has liked the post or not within the django template. I have tried, post.postlike_set but of course that won't work because it's for all the likes, is there anyway that I can check if the current loggedin user has liked the post or not. Please help! -
Django Messages - Debug Tag Messages Not Showing On Template
I am going through the docs for Django Messages and have set up a basic form with some error messages and a debug message. The error messages are appearing but the debug one is not. I am not sure why the debug one is not and would appreciate some guidance. I did check the settings file and all 4 lines outlined in the docs are already included. views.py def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successfull.") return redirect("messages_test:homepage") messages.error(request, "Unsuccessful registration. Invalid information.") messages.error(request, "Unsuccessful registration. Invalid information again.") messages.debug(request, "Debug message") form = NewUserForm() return render(request=request, template_name="messages_test/register.html", context={"register_form":form}) register.html {% load static %} <link rel="stylesheet" href="{% static 'messages_test/style.css' %}"> {% load crispy_forms_tags %} <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form|crispy }} <button class="btn btn-primary" type="submit">Register</button> </form> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <p class="text-center">If you already have an account, <a href="/login">Login</a> instead.</p> </div> -
How to make sign-up in django with one-to-one model?
model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=100) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() view def register(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) print(user_form) print(profile_form) print("에혀") if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) profile = profile_form.save(commit=False) profile.user = user profile.user.set_password(user_form.cleaned_data['password']) profile.user.department = request.POST['department'] user.save() profile.save() print(request) return render(request, 'index.html', {'new_user':user}) else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'register.html', {'form':user_form}) form class UserForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['department'] urls.py urlpatterns = [ path('', IndexView.as_view(), name='index'), path('register/', views.register, name='register'), .... template {% extends "base.html" %} <div class="container my-3"> <form method="post" action=""> {% csrf_token %} <div class="mb-3"> <label for="username">ID</label> <input type="text" class="form-control" name="username" id="username" value="{{ form.username.value|default_if_none:'' }}"> </div> <div class="mb-3"> <label for="password">PASSWORD</label> <input type="password" class="form-control" name="password" id="password" value="{{ form.password.value|default_if_none:'' }}"> </div> <div class="mb-3"> <label for="password2">PASSWORD_CONFIRM</label> <input type="password" class="form-control" name="password2" id="password2" value="{{ form.password2.value|default_if_none:'' }}"> </div> <div class="mb-3"> <label for="email">EMAIL</label> <input type="text" class="form-control" name="email" id="email" value="{{ form.email.value|default_if_none:'' }}"> </div> <div class="mb-3"> <label for="email">DEPARTMENT</label> <input type="text" class="form-control" name="department" id="department" value="{{ form.department.value|default_if_none:'' }}"> </div> <button … -
how can I use `return HttpResponseRedirect(reverse("some-path", args=[slug]))` with user_agent?
I'm looking for a way to use (in the views.py) return HttpResponseRedirect(reverse("some-path", args=[slug])) where I can define to which template a user will be redirected according to the device. The problem is related to the Class-based view with the get and post methods. In my post function I have this unsolved problem in my return statement. I couldn't find an answer anywhere: what's the best approach for this situation? The problem is that redirection uses just url.py and I don't know where and how can I write the if statement about the devices, like in normal view function: if user_agent.is_pc: return render( request, 'dev/registration-success_pc_tablet.html', { 'my_email': my_email }) elif user_agent.is_mobile: return render( request, 'dev/registration-success_mobile.html', { 'my_email': my_email }) elif user_agent.is_tablet: return render( request, 'dev/registration-success_pc_tablet.html', { 'my_email': my_email }) I have set my MIDDLEWARE, INSTALLED_APPS for user_agent. The problem is just with this particular case that I described in my question. -
How delete a model instance and the instance from the OneToOne relation
I have these two models in django rest: class CustomUser(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) class Teacher(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) How can I delete the CustomUser instance related when deleting a Teacher instance? I tried this code but it gives this error "maximum recursion depth exceeded while calling a Python object" @receiver(pre_delete, sender=Teacher) def delete_user(sender, instance, **kwargs): instance.user.delete() -
Django & Form with SelectMultiple: null value in column x of relation y violates not-null constraint
I am facing the following error when trying to save the project after filling the form where i am choosing multiple tags for this project: null value in column "tag_id" of relation "project_tags" violates not-null constraint DETAIL: Failing row contains (10263, 10262, null). --> project_tags(id, project_id, tag_id) The db model is simple: I have projects, and each project has tag(s). All is defined by the following models: class Project(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() class Meta: managed = False db_table = 'project' def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class ProjectTag(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30) class Meta: managed = False db_table = 'project_tag' def __str__(self): return self.name class ProjectTags(models.Model): id = models.AutoField(primary_key=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) tag = models.ManyToManyField(ProjectTag) class Meta: managed = False db_table = 'project_tags' View is following: @login_required def add_project(request): submitted = False if request.method == "POST": form1 = ProjectForm(request.POST) form2 = ProjectTagsForm(request.POST) if form1.is_valid() and form2.is_valid(): form1_part = form1.save(commit=False) form1_part.client = request.user form1_part.save() project_id = Project.objects.get(id=form1_part.id) form2_part = form2.save(commit=False) form2_part.project = project_id form2_part.save() return HttpResponseRedirect('/project/new?submitted=True') else: form1 = ProjectForm form2 = ProjectTagsForm if 'submitted' in request.GET: submitted = True context = {'form1':form1 ,'form2':form2 ,'submitted':submitted } return render(request, … -
django auth with otp and phone number without password
I want user login without password, just by sending an SMS to the user's phone number and entering the code. I used sessions to transfer user inputs and I just don't know if this is correct or if there is a better way for this. Thank you for helping me. This is my code: # models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.core.validators import RegexValidator class MyAccountManager(BaseUserManager): def create_superuser(self,username, email, phone_number,password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True') user = self.create_user(username,email, phone_number, password, **other_fields) user.set_password(password) user.save() return user def create_user(self, username, email, phone_number,password,**other_fields): if not email: raise ValueError('') email = self.normalize_email(email) if password is not None: user = self.model(username=username,email=email, phone_number=phone_number,password=password, **other_fields) user.save() else: user = self.model(username=username,email=email, phone_number=phone_number, password=password,**other_fields) user.set_unusable_password() user.save() return user class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=150,unique=True) phone_number = models.CharField(max_length=17, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['email', 'username'] # views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth import authenticate, login, get_user_model from .forms import … -
Can't handle with Django Model related objects for Analysis-tracking App
I'm trying to make a web app that allows to add patients and add then track their medical analyses. Example Trying to make models for it... Could you advise me: what is the strategy if my next purpose is to make form that allows to fill in all lines from analysis group. Should I move in this way? (So next will be problems with orm queries) I tried to deal with next solution but maybe u will take a professional look at this? Really appreciate patient/models.py: class PatientGender(models.Model): gender = models.CharField(max_length=16) def __str__(self): return f"{self.gender}" # Create your models here. class Patient(models.Model): hist_number = models.IntegerField(unique=True, verbose_name='Номер истории болезни') last_name = models.CharField(max_length=32, verbose_name='Фамилия') first_name = models.CharField(max_length=32, verbose_name='Имя') second_name = models.CharField(max_length=32, verbose_name='Отчество') birth_date = models.DateField(verbose_name='Дата рождения') date_time = models.DateField(auto_now_add=True, verbose_name='Время поступления в ОРиТ') sex = models.ForeignKey(PatientGender, verbose_name='Пол', on_delete=models.CASCADE, default=1) seat = models.PositiveSmallIntegerField(verbose_name='Палата', blank=True, null=True) description = models.TextField(blank=True, verbose_name='Палата') is_Active = models.BooleanField(verbose_name='Находится на лечении', default=True) def __str__(self): return f"{self.hist_number}: {self.last_name} {self.first_name} {self.second_name}" analysis/models.py: class AnalyzesGroup(models.Model): name = models.CharField(max_length=256, verbose_name='Группа исследований') description = models.TextField(blank=True, verbose_name='Примечание') class Meta: verbose_name = 'Группа анализов' verbose_name_plural = 'Группы анализов' def __str__(self): return f"{self.name}" class AnalysisType(models.Model): name = models.CharField(max_length=256, verbose_name='Исследование') measurement = models.CharField(max_length=10, verbose_name='Единицы измерения') ref_min = models.FloatField(verbose_name='Мин. реф. … -
Limit instantiations of class with particular value to one - django
I have two classes in a django app, project and plan The project class has an is_global boolean field, as does the plan class. The plan also has a foreign key to the project class (projects have multiple plans). I am trying to accomplish the following: for both projects and plans, there should only ever be one instance of each where is_global = true. The global plan should belong to the global project. Is it possible to enforce this logic with django models? -
EventConsumer() missing 2 required positional arguments: 'receive' and 'send', while using AsyncWebSocketConsumer
The problem is, that i dont understand why it asks me for 2 positional arguments here, and i didnt see any other problem like this. There were suggestions to update 'channels' library, or to really add that 'send' and 'receive' functions into my Consumers class. But neither of that has any impact on my code. I have tried different variations of routing, setting up asgi, or configuring Docker-compose and nginc.config file. But still nothing helps. The idea is that i just want My WebSocket to be sending me events which are saved to events from POST, or which is about to be saved. Here is my consumers.py: from channels.generic.websocket import AsyncWebsocketConsumer from .models import ( WorkingMode, CarParkItem, Events ) import json class EventConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("events", self.channel_name) print("Connected to events") async def disconnect(self, close_code): await self.channel_layer.group_discard("events", self.channel_name) print("Disconnected from events") async def receive(self, text_data): text_data_json = json.loads(text_data) cam_id = text_data_json['cam_id'] vehicle_plate = text_data_json['vehicle_plate'] is_recognition = text_data_json['is_recognition'] is_confirmation = text_data_json['is_confirmation'] working_mode = WorkingMode.objects.get(pk=cam_id) event_code = None if working_mode.pass_mode == 'closed': event_code = 1009 else: car_park_item = CarParkItem.objects.filter(vehicle_plate=vehicle_plate).first() if car_park_item: event_code = 1008 else: if is_recognition and is_confirmation: event_code = 1007 elif is_recognition and not is_confirmation: event_code = …