Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Run Django Website with different mod_wsgi than default
I have an Apache2 server hosting multiple Django websites. All except one use Django 3.8, using a mod_wsgi compiled on Python 3.7. The outlier (let's call it SiteX) uses Django 4.0, which requires Python 3.8+. I want SiteX to use a virtual environment with these newer versions of Python and Django, while the other sites keep using their default versions. For SiteX, I've created a virtual environment venv in its directory. But from what I understand, the current mod_wsgi installed is not compatible with its version of Python, so specifying WSGIPythonHome in the conf file won't do anything. the current mod_wsgi (4.7/python 3.7) is loaded in /etc/apache2/mods-available/wsgi.load with the line LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so I've tried creating a new mod_wsgi, this time using the Python module mod_wsgi, which I've installed in venv. In the .conf file for a group of Django sites (that include SiteX) I tried specifying this unique version of the mod_wsgi above the <VirtualHost> block with the line: LoadModule wsgi_module "/var/www/html/app/SiteX/venv/lib/python3.9/site-packages/mod_wsgi/server/mod_wsgi-py39.cpython-39-x86_64-linux-gnu.so" but running $ apachectl configtest says: module wsgi_module is already loaded, skipping. I found a solution for multiple mod_wsgi's using WSGIDaemonProcess but the solution's .conf looks slightly different that mine. Below is a snippet of the relevant … -
Django filter by category
i want to see specific category wise post, i created category app and blog app.i want show top 5 or 10 post in home.html.that's why i need 4 specific category. but i can't filter(category) from post model.i cant access category because i created it another app.. i want to filter by category. model.py for category class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null=True) category_name = models.CharField(max_length=50,unique=True) slug = models.SlugField(allow_unicode=True,max_length=100,unique=True) description =models.TextField(max_length=300,blank=True) cat_image = models.ImageField(upload_to = 'photo/categories',blank = True) created_at = models.DateTimeField(auto_now_add=True) model.py for blog class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(allow_unicode=True, unique=True, max_length=250, null=True, blank=True) subtitle = models.CharField(max_length=255, blank=True) heder_image = models.ImageField(null=False,blank=True,upload_to="images/") heder_image_url = models.CharField(null=True,blank=True,max_length=200) heder_image_Under_line = models.TextField(null=True,default="image") # author = models.ForeignKey(Profile, on_delete=models.PROTECT) author = models.ForeignKey(User, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now= True) created_on = models.DateTimeField(auto_now_add=True) body = RichTextField(max_length=100000) status = models.IntegerField(choices=STATUS, default=0) meta_description = models.TextField(max_length=300, blank=True,default='') category = models.ForeignKey(Category,on_delete= models.CASCADE) views.py def home(request): category = Category.objects.all().filter(parent=None) post_by_category = Post.objects.filter(published=True).order_by('-created_on')#filter by category name slider = Post.objects.filter(slider=True).order_by('-created_on') context = { 'category':category, 'post_by_category':post_by_category, 'slider':slider, 'counter':Counter, } return render(request,'home.html',context) -
How to save JavaScript sessionStorage to django
I have an Sdk to call which returns an applicationID that I need to store in my django application so that if the user is approved can then move to the next page. I trying to save in JS sessionStorage than pass the data to another html page where I'm using ajax to pass it to my django views, the problem is that I need to have this data unique for the user that is logged in. How can I link this data to the current user logged in and so on? const widget = window.getidWebSdk.init({ apiUrl: '', sdkKey: '', containerId: "targetContainer", flowName: '', onComplete: (data) => { console.log(JSON.stringify(data)) let appId = data; console.log(data) sessionStorage.setItem("appId", JSON.stringify(appId)) window.location.href = "/kycsubmit"; return; }, onFail: ({ code, message}) => { console.log("something went wrong: " + message )}, }); second html page let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = application.applicationId $.ajax({ type: "GET", dataType: "json", url: `api/application/${kycStatus}`, headers: { 'Content-Type': 'application/json', 'X-API-Key': '', }, success: function(data) { document.getElementById("test").innerHTML = data.overallResult.status document.getElementById("test-1").innerHTML = application.applicationId console.log(data.overallResult.status) } }) -
Accessing items in a list through template tags in Django template tags
Template tag screenshot and possible solution options First time, posting to stack-overflow. Please excuse if formatting is not ideal. html <tbody> {% for list in todolist %} <tr> <td> <a href="{% url 'todo_detail' list.pk %}">{{ list.name }}</a> </td> <td> {{ list.items.all|length }} </td> <td> {% comment %}need this to be allCompleted[list.id - 1] #allCompleted.0 works. allCompleted[0] or allCompleted['0'] does not.{% endcomment %} {% if allCompleted == True %} {{ allCompleted|getindex:list.id }} Yes {% else %} No {% endif %} </td> </tr> {% endfor %} </tbody> Views.py: class TodoListListView(ListView): model = TodoList context_object_name = "todolist" template_name = "todos/list.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) allCompletedList = [] for list in TodoList.objects.all(): allCompleted = True for item in list.items.all(): if item.is_completed == False: allCompleted = False allCompletedList.append(allCompleted) context['allCompleted'] = allCompletedList print ('context: ', context) return context Models.py class TodoList(models.Model): name = models.CharField(max_length=100, blank=False) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class TodoItem(models.Model): task = models.CharField(max_length=100) due_date = models.DateTimeField(null=True, blank=True) is_completed = models.BooleanField(default=False) list = models.ForeignKey("Todolist", related_name="items", on_delete=models.CASCADE) def __str__(self): return self.task When printing context: I get 'allCompleted': [False, True] This is accurate as I have some items in housing chores not completed but I triple checked to make sure all my coding … -
Django ORM group list of values by date
I'm attempting to perform a group by on a date field, and return values matching that date in a single query. There seem to be many related questions here but they all are aggregating based upon a Count. Given I have a model like this: class Book(models.Model): name = models.CharField(max_length=300) pubdate = models.DateField() I would like to run an ORM query which returns distinct name values for pubdate. How can I get a result which looks like { '2022-05-04': ['John', 'Sara', 'Bill'], '2022-05-06': ['Sara', 'Kevin', 'Sally'] ... } -
use functions from another file inside of a class
I have a file, called tst_pro_ac.py. It contains many classes, with many methods inside of these classes. The classes are part of test cases used by Django, to do unit tests. Exemple of a class inside tst_pro_ac.py class LoginRequiredActiveCheck(TestCase): """Login Required for project_active Page""" def test_status_code_200(self): """project_active Response status 200""" self.assertEqual(self.response.status_code, 200) Some of these methods are used many times, hence redundant. The idea is to put these methods in a separate file like comm_function.py and call them when needed. I've created the file comm_function.py and put the often used functions inside def test_status_code_200(self): """project_active Response status 200""" self.assertEqual(self.response.status_code, 200) Yet, when I call them in my new file like this from comm_function import test_status_code_200 class LoginRequiredActiveCheck(TestCase): """Login Required for project_active Page""" test_status_code_200() Yet, when I run the test through a python manage.py test stuff.tests.some_tests.tests_pro_active I have the following error raise AttributeError(item) AttributeError: assertEqual Not sure if my understanding of the class is correct and if something doable in Django. PS: If the question is not appropriate, let me know, I will delete it. -
How to pass config setting in Django and keep module decoupled?
In a Python Django project, I have a module with a class (let's say SomeDataStore) that abstracts file storage behaviour and requires a config setting with the correct path (different for development, prod, ...) Currently, I've done it like this: # settings.py RELEVANT_PATH = os.environ.get("DJANGO_RELEVANT_PATH", "/some/default") ... # datastore.py from django.conf import settings class SomeDataStore: def list_files(self): p = Path(settings.RELEVANT_PATH) files = p.glob("*.csv") return files ... # views.py from datastatus import SomeDataStore def show_files(request): files = SomeDataStore().get_files() ... Goal: I'd like to decouple the datastore.py module completely from django, so that it can easily be used standalone. That would mean to get rid of the django.conf.settings usage in datastore.py One obvious way to do it would be to provide the path as an init parameter to the DataStore class. # datastore.py class SomeDataStore: def __init__(self, path) -> None: self.path=path ... However, I use this DataStore in many Django views, and that would require me to always specify the path when instantiating the class, e.g. like so # views.py from datastatus import SomeDataStore def show_files(request): files = SomeDataStore(settings.RELEVANT_PATH).get_files() ... def show_something_else(request): somethings = SomeDataStore(settings.RELEVANT_PATH).get_something_else() ... I'd like to avoid the need in each instantiation to always specify the config setting for … -
Is Asp.net Core Inspired by Django framework and are they the same
I have now understood the Asp.net Core Framework and it seems just like how Django works. I feel asp.net core is greatly inspired by django. They are literally the same. Are they internally also the same? Are the developers of Django behind the development of asp.net core? -
Custom Login Setup django-microsoft-auth Django
I am using django-microsoft-auth in my Django project. I followed this guide. Now, I'm able to log in through Microsoft account(address: http://localhost:8000/admin ) but I don't know how to add a view that will say "Login using Microsoft" and how to link that view with Microsoft authentication page. It will be great if someone can tell me how to do this. You can see this picture. Here Microsoft button is automatically added for login. How to set up a button like this on the home page? -
Django: How to autogenerate a random 6 digit string
I would like to generate a unique 6 digit code each time a user clicks "generate code". Error AttributeError at /subjects/ 'Manager' object has no attribute 'make_random_password' i have added the templates, models and views used for it. ps. Still a beginner in django Views.py class SubjectView(TemplateView): template_name='subjects.html' # context='subjects' random_number = Subject.objects.make_random_password(length=10, allowed_chars='123456789') while Subject.objects.filter(attendcode__temp_password=random_number): random_number = Subject.objects.make_random_password(length=10, allowed_chars='123456789') def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['Attendance code']=Subject.objects.all() context['subjects'] =Subject .objects.all() context['students']=Student.objects.all() context['attendace_code']=Subject.objects.get("attendance_code") obj = CourseRegistration.objects.filter(subject_code__gt=0) no_students=obj.count() # no_students=CourseRegistration.objects.all().count() context['no_students']=no_students return context def get_success_url(self): print(self.kwargs['slug']) return reverse('subject', args=(self.kwargs['slug'],)) Template {% for subject in subjects %} <tbody class="list" style="text-transform:capitalize;"> <tr> <th scope="row"> <div class="media align-items-center"> <a href="#" class="avatar rounded-circle mr-3"> {% if subject.thumbnail %} <img alt="Logo" src="{{subject.thumbnail.url}}"> {% endif %} </a> <div class="media-body"> <span class="name mb-0 text-sm">{{subject.subject_name}}</span> </div> </div> </th> <td class="budget"> {{subject.subject_code}} </td> <td> <div class="d-flex align-items-center"> <span class="completion mr-2">{{no_students}}</span> </div> </td> <td> <div class="d-flex align-items-center"> <span class="completion mr-2">{{attendace_code}}</span> </div> </td> </tr> </tbody> {% endfor %} Models.py class Subject(models.Model): subject_name=models.CharField(max_length=1000,unique=True) subject_code=models.CharField(max_length=7,primary_key=True) lecturer_ID=models.ForeignKey(Lecturer, related_name="subj1_FK",on_delete=models.PROTECT) thumbnail=models.ImageField(blank=True,null=True,upload_to=get_thumbnail) -
automate file upload in django
I want to monitor a folder (which receives new csv file weekly)and add that file to my django model . The purpose simply is to automize upload procedure , any help would be appreciated from django.db import models class FilesAdmin(models.Model): adminupload=models.FileField(upload_to='media') title=models.CharField(max_length=50) def __str__(self): return self.title -
Django Ajax sending value to View function. No errors but no reception either
I have a table and at the end of each row a button that gets the ID and should send it to a View function. Once the view function gets the ID it should send more values just below the table, so staying on the same page. The issue is that while developer tools in Firefox seems to show that the value has been POSTED, I am not getting any confirmation from the view function that is supposed to receive it. I am not getting errors either, and the console.log(data) does show the correct ID $(document).ready(function(){ // open document ready $('.botontest').on('click',function(){ // opening click function var name = $(this).val() alert(name); $.ajax({ // opening ajax obviously url:'{% url 'makingqueries' %}', type:'POST', data:{'name':name, csrfmiddlewaretoken: '{{csrf_token}}'},// closes data field datatype:'text' }); // closing ajax group console.log(name); }); // closing the click function });// closing document ready The View function is simplified because I first wanted to see if it gets anything: def makingqueries(request): if request.method == 'POST': print("got posted id") And the URL is: path('dashboard', views.makingqueries, name='makingqueries'), -
NameError: name 'Bscs' is not defined
enter image description here[please help me, I'm new to making table for database and I don't know how to fix this][2] -
React Django URL Not Found
I'm building a Twitter clone with Django and React. Up until now, I have set up the login and tweet creation, and they work fine. For the Like button, this is my implementation: React: const handleLike = (id)=>{ let posts_list = posts const post_indx = posts_list.findIndex((post=> post.id==id)) posts_list[post_indx].likes++ axios({ method: 'post', headers: { 'Content-Type': 'application/json' }, url: 'http://127.0.0.1:8000/api/tweets/action/', data: { id: post_indx, action:"like" } }).then(function(response){ setPosts(posts_list) // console.log(this.state.posts) } ) } Django URLs: urlpatterns = [ path('admin/', admin.site.urls), path('', home_view), path('api/tweets/', include('tweets.urls')), path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] Tweets App URLs: urlpatterns = [ path('', tweet_list_view), path('<int:tweet_id>/', tweet_detail_view), path('create/', tweet_create_view), path('<int:tweet_id>/delete/', tweet_delete_view), path('action/', tweet_action_view), ] now I know the create tweet works perfectly fine, but the action URL gets the error: Not Found: /api/tweets/action/ Is the problem something other than routing?