Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Old url is still searched after POST request
I am fairly new to Django and now at my wit's end with the following issue. I have changed the url name from 'odata' to 'database' and the app properly redirects to the url http://127.0.0.1:8000/database/. However while being at http://127.0.0.1:8000/database/ and making the POST request using ajax, the app freezes and on looking in the browser's developer tools I see the error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/odata/ . . . The current path, odata/, didn't match any of these. Why the old name is still being searched? I have made changes in the following files and codes: my_app/url.py urlpatterns = [ path('', views.view1, name = "view1"), path('database/', views.view2, name = "view2"), #old name was odata/ ] myreq.js function submit_training() { $.ajax({ url: '/database/', //earlier- /odata/ data: $('form#db_settings').serialize(), method: 'POST', ... } When I revert the changes to 'odata' everything works as expected. I am not sure what I am missing here. I apologize for not providing more or exact codes, as I am not supposed to disclose details on the project. However, I can still furnish more information, if required. Your time and help is much appreciated!! -
White blank page when I deploy my (React.js & Django) app to Heroku
I'm beginner and the project works perfectly locally , but when I deploy on Heroku I get a blank page. package.json (I tried adding "homepage": "." but it didn't work to me even after rebuild again ): { "name": "frontend", "homepage": "aroundtheword.herokuapp.com/", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.2", "@testing-library/react": "^12.1.4", "@testing-library/user-event": "^13.5.0", "axios": "^0.26.1", "react": "^17.0.2", "react-dom": "^17.0.2", "react-router-dom": "^6.2.2", "react-scripts": "^5.0.0", "uuid": "^8.3.2", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "postinstall": "npm run build" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "engines": { "node": "16.13.0", "npm": "8.1.0" } } index.html (public folder): <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the … -
How to Redirect URLs Dynamically
Can someone guide me please how to approach this concept with .htaccess, HTML, JavaScript, Django and DB (I don't know whether database is necessary or not)? Concept Design -
Using Django For Loop in Drop Down Menu
I'm trying to iterate through a list of recommendations previously entered by the user and make each recommendation an item in a drop down list. Image of the Code I'm using Image of the Results I'm getting -
ValueError: Canot asign "<django.contrib.auth.models.AnonymousUser object at 0x..40>": "Members.user" must be a "User" instance. [2..7] "POST /api/
I'm trying to register a user and have the email part go into the user name from the Members model, but I'm getting the above error. kindly assist. In auth_user username Equals [blablabla]@gmail.. in brackets I'm trying to add the same to the Members user, for a ForeignKey relationship. To make user equal to blablabla Serializers class RegisterSerializer(serializers.ModelSerializer): password1 = serializers.CharField(required=True) password2 = serializers.CharField(required=True) user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Members fields = ('first_name', 'last_name', 'user', 'email', 'photo', 'gender', 'password1', 'password2') def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError("A user is already registered with this email address.") return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def get_cleaned_data(self): return { 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), }, { 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'photo': self.validated_data.get('photo', ''), 'gender': self.validated_data.get('gender', ''), 'email': self.validated_data.get('email', ''), 'user': self.validated_data.get('user', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data, data_for_members = self.get_cleaned_data() Members.objects.create(**data_for_members) adapter.save_user(request, user, self) setup_user_email(request, user, []) user.save() return user class LoginSerializer(RestAuthLoginSerializer): username = None Models class Members(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') gender_choices = (('F', … -
'QuerySet' object has no attribute 'comments'
while runnig http://127.0.0.1:8000/blogapp/blogdata/53/ i get error AttributeError at /blogapp/blogdata/53/ 'QuerySet' object has no attribute 'comments' and it says expected error location is views.py line 42 which is comments=blogmodel.comments.all() models.py class Blogmodel(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,blank=True,null=True) title=models.CharField(max_length=200) Newpost=models.TextField(max_length=1000) summary=models.TextField(max_length=50,blank=True) created_date=models.DateTimeField(auto_now_add=True) published_date=models.DateTimeField(auto_now=True) def __str__(self): return f'{self.title},{self.Newpost},{self.published_date},{self.created_date}' class commentmodel(models.Model): blogmodel=models.ForeignKey(Blogmodel,related_name='comments' ,on_delete=models.CASCADE,blank=True,null=True) comment=models.CharField(max_length=200) active=models.BooleanField(default=True) def __str__(self): return f'{self.comment},{self.blogmodel.title}' views.py def blogretrieve(request): blogmodel=Blogmodel.objects.all().order_by('-published_date') context={'blogmodel':blogmodel,} return render(request,'blogapp/blogretrieve.html',context) def blog(request,pk): blogmodel=Blogmodel.objects.filter(id=pk) #comments = y.comments.filter(active=True) comments=blogmodel.comments.all() #line 42 context={'blogmodel':blogmodel,'comments':comments} return render(request,'blogapp/blogpk.html',context) urls.py app_name='blogapp' urlpatterns=[ path('',views.home,name='home'), path('createblog/',views.blogview,name='blogview'), path('blog/',views.blogretrieve,name='blog'), path('signup/',views.signupview,name='signup'), path('login/',views.loginview,name='login'), path('logout/',views.logoutview,name='logout'), path('author/<str:pk>/',views.authorview,name='author'), path('blogdata/<str:pk>/',views.blog,name='blogdata'), -
DjangoRestFramework: Assign CustomUser failed
Good evening, inside my djano-application I've created a custom user... class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email ...and added the following code snippet into settings.py: AUTH_USER_MODEL = 'app_something.CustomUser' My Question: how can I add it into the following - let's say - put request: ... elif request.method == 'PUT': serializer = SomethingSerializer(qs, data=request.data) if serializer.is_valid(): serializer.save(user_created=request.user) # --> line that causes the error return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ... Right now I'm trying to add the request.user, which fails with the error something_user_created" must be a "CustomUser" instance. My first idea was to add the CustomUser like this, but I dont't know how to get the active user inside my view: from app_something.models import CustomUser customuser = CustomUser.objects.get(id=???) ... serializer.save(user_created=customuser) ... Does anyone know what I'm doing wrong here? Thanks for you help and have a great day! -
error code H10 while deploying django app on heroku
hi i am trying to deploy my django app to heroku but it gives me this error: ** note " the build was successful " enter image description here this is another photo: enter image description here the error code: 2022-03-20T17:01:35.874001+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=beta-stega.herokuapp.com request_id=37d48eef-1019-4eb1-93a5-50d4c8db7f6b fwd="46.248.201.72" dyno=web.1 connect=8ms service=634ms status=503 bytes=0 protocol=https 2022-03-20T17:01:35.874312+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=beta-stega.herokuapp.com request_id=7054bc05-06f4-43c5-bdea-8b49a610054d fwd="46.248.201.72" dyno=web.1 connect=0ms service=236ms status=503 bytes=0 another error code (i think that): 2022-03-20T17:01:49.757829+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=dbe2cac6-8715-4525-a05a-0c88bb3c8815 fwd="46.248.201.72" dyno=web.1 connect=5000ms service=53ms status=503 bytes=0 protocol=https 2022-03-20T17:02:04.006106+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=ae1a7cae-51b4-461b-9ce6-b83b4966e78a fwd="46.248.201.72" dyno= connect= service= status=503 bytes= protocol=https 2022-03-20T17:02:04.577385+00:00 heroku[router]: at=error w desc="App crashed" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=e00b7566-3ccb-4a04-bdf5-8b814e6874bb fwd="46.248.201.72" dyno= connect= service= status=503 bytes= protocol=https website error image : enter image description here build log image : enter image description here ** note " the work fine on local host " can anyone help :) -
/opt/alt/python39/bin/lswsgi: No such file or directory
I have a shared Cpanel host with Litespeed web server. I want to deploy a django application on it. After creating Python application inside the Cpanel where I have not deployed the application on the host I try loading the web site, and instead of displaying django version I face 503 Unavailable!! Also inside the "stderr.log" file there is following error. /usr/local/lsws/fcgi-bin/lswsgi_wrapper: line 9: /opt/alt/python39/bin/lswsgi: No such file or directory -
how to fetch data from a list of dictionary using django
I am trying to develop a dictionary(using django) that contains a voice for pronunciation. everything goes fine but I cannot relate the audio with the word using the following query. Model.py class Warehouse(models.Model): word = models.CharField(max_length=200, blank=True) type = models.CharField(max_length=200, blank=True) gender = models.CharField(max_length=200, blank=True) meaning = models.TextField(max_length=2000, blank=True) synonyms = models.CharField(max_length=200, blank=True) antonyms = models.CharField(max_length=200, blank=True) usage = models.TextField(max_length=2000, blank=True) class Audio(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) audio_file = models.FileField(upload_to='audio') def __str__(self): return self.warehouse.word def delete_media(self): os.remove(path=MEDIA_ROOT + '/' + str(self.audio_file)) query.py def get_words_warehouse_matching(search_sting): try: dictionary_object = Warehouse.objects.filter(Q(word__icontains = search_sting)|Q(type__icontains=search_sting) | Q(gender__icontains=search_sting)|Q(synonyms__icontains=search_sting)|Q(antonyms__icontains=search_sting) words_list = [] for words in dictionary_object.iterator(): word_dictionary = {'id':words.id, 'word': words.word, 'meaning': words.meaning, 'synonyms': words.synonyms,'antonyms': words.antonyms} words_list.append(word_dictionary) return words_list views.py def search(request): context = {} warehouse={} if request.method == 'POST': context['data'] = get_words_by_matching(request.POST['searchString']) context['warehouse'] = get_words_warehouse_matching(request.POST['searchString']) voice = Audio.objects.filter(warehouse_id = warehouse.id) context['audio'] = voice return render(request, 'dictionary/word.html', context) I need to display the related audio file in the template so that I need to equate warehouse_id to Warehouse.id. How can I fetch the id from get_words_warehouse_matching (dictionary) so that I could use filter(warehouse_id = warehouse.id) in views. Or if there are any other better options, suggestions would be highly appreciated. Thanks in advance. -
No module named '_tkinter : on deploying to heroku
Am trying to deploy a Django React application on heroku but get error ModuleNotFoundError: No module named '_tkinter'. The application is running absolutely fine in local. But, after deploying in Heroku, I am getting the below error. remote: Traceback (most recent call last): remote: File "/app/manage.py", line 22, in <module> remote: main() remote: File "/app/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate remote: app_config.import_models() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 300, in import_models remote: self.models_module = import_module(models_module_name) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 850, in exec_module remote: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed remote: File "/app/portfolioApi/models.py", line 1, in <module> remote: from turtle import title remote: File "/app/.heroku/python/lib/python3.9/turtle.py", line 107, in <module> remote: import tkinter as TK remote: File "/app/.heroku/python/lib/python3.9/tkinter/__init__.py", line 37, in <module> remote: … -
How to track which user is creating object for a model and how to show the object details only to that user in django
I am doing an online classroom project in Django where I created a model named create_course which is accessible by teachers. Now I am trying to design this as the teacher who creates a class only he can see this after login another teacher shouldn't see his classes and how to add students into that particular class I created the course model class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) here if I use "the created_by" field in forms it appears to be a drop-down menu where every user is showing but I want to automatically save the user who creates the object views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): form.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) forms.py from django import forms from .models import course class add_course(forms.ModelForm): class Meta: model = course fields = ('course_name', 'course_id', 'course_sec', 'classroom_id') -
Hello, I want to send the information of a JSON to different databases, the json that I must receive has the following format(Python, Django) [closed]
{ "Table 1": { "field1":"...", "field2":"..." }, "table2": { "field1":"...", "field2":"..." } } -
Can i styling django login views?
I trying using django login views form django.contrib.auth.views, but I'm confused while trying to style it, is there any solution for that? from django.contrib.auth import views as auth_views path('accounts/login/', auth_views.LoginView.as_view()), -
How to use is_active in class based LoginView?
I am using default User model and I want check whether the user is active or not before they log in... How can I do that? -
Reverse foreign key relation in django serializers
Can I save data in django in a reverse foreign key relation. Suppose I have models, class Author(models.Model): author_id = models.SlugField(default=None, blank=True) author_name = models.CharField(max_length=200) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) article_title = models.CharField(max_length=200) content = models.CharField(max_length=200) Suppose I want to save all articles with their author data what type of serializer should I use. I am receiving data in this form: article_data =[ { "title":"ome title", "content":"content", "author":{ "author_id":"2", "author_name":"some name", } }, { "title":"ome title", "content":"content", "author":{ "author_id":"2", "author_name":"some name", } } ] How should I write my serializer to save such data. I dont want to write my logic views file. I dont want to loop over all my articles and then save article and author separately using two serialzer. What I want is calling a single serializer and passing the entire list to it: saveArticleAndAuthor(article_data, many=True) the serialzier must save author data to author table and rest of the data to article table. -
how to use font awesome icon as file upload input field for django template as bootstrap?
I am using bootstrap as the template. The form is designed as the font awesome icon will be the file upload field in the design. Is there any way to do it? I have no idea about that. I am sharing the template code here. If anyone can help me, I will be grateful. Thanks. <form method="POST" action="{% url '' %}"> {% csrf_token %} <div class="icons"> <div class="row"> <div class="col-4"> <a href="#"> <i class="fa fa-picture-o" aria-hidden="true"></i> <p>Gallery</p> </a> </div> <div class="col-4"> <a href="#"> <i class="fa fa-camera" aria-hidden="true"></i> <p>Camera</p> </a> </div> <div class="col-4"> <a class="" href="#" > <i class="fa fa-microphone" aria-hidden="true"></i> <p>Audio</p> </a> </div> </div> </div> <div class="mb-3"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="8" placeholder="Type your question here" name="description" ></textarea> </div> <button type="submit" class="btn">Submit</button> </form> -
Please any one out there how i can get pass this issue i encountered this issue most times in heroku when i push new code instead of auto migration
Operations to perform: Apply all migrations: admin, auth, authentication, contenttypes, ekzweb, sessions Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. please anyone out there how can i get pass this issue -
How to send email to admin in Django?
I'm building a web application that needs to send a notification to the admin when there is a low quantity of items in-store. Like if I have 10 pens, and someone recently buys 5 pens from my web application and I want to send a notification to admin if the quantity of pens is less than 5 or equal to 5 to notify him/her. Thanks ^^ -
Passing a variable vs a hard-coded string is not working on query search using Django shortcuts
I'm in the process of learning how to use Django. My goal is to grab an object (one hero and one villain) from the database using the names, (not id), passed in the URL as search params. I am successfully grabbing the values from the query params, however, when I try to pass the variable "hero" into the Django shortcut, (get_object_or_404(Super,name=hero)), I get a 'not found'. It works fine if I manually type out the string I'm searching for(get_object_or_404(Super,name="Bat Man")). Any ideas why this is and how I can make my query search dynamic by name? @api_view(['GET', 'POST']) def supers_list(request): type = request.query_params.get('type') hero = request.query_params.get('hero') villain = request.query_params.get('villain') if request.method == 'GET': supers = Super.objects.all() if type: supers = supers.filter(super_type_id__type = type) serializer = SuperSerializer(supers, many=True) return Response(serializer.data) elif hero and villain: # print(hero) result is "Bat Man" hero_found = get_object_or_404(Super,name=hero) # hero_found = get_object_or_404(Super,name="Bat Man") print('=====', hero_found) return Response('hello') else: heros = supers.filter(super_type_id__type = 'hero') villains = supers.filter(super_type_id__type = 'villain') heros = SuperSerializer(heros, many=True) villains = SuperSerializer(villains, many=True) result = {'heros':heros.data, 'villains':villains.data} return Response(result) -
Django form request method is always GET
This is the html code: <form method='POST'>{% csrf_token %} {{ form.as_p }} <input type='submit' value='save'/> </form> This is the path in url.py: path('student/create/', student_create_view, name='student-create') This is my code in views.py: def student_create_view(request): form = StudentForm(request.POST or None) if form.is_valid(): form.save() form = StudentForm context = { 'form': form } return render(request, "personnel/student_create.html", context) I also tried action attribute and adding or removing "/" to the end of the path. -
django UserPassesTestMixin with parameter
Here's working version with user_passes_test. But I would like to replace position > 1 with parameter. I found that, it's possible to do with UserPassesTestMixin. But I don't know how. Can anyone help? def position_check(user): position = 0 if user.is_anonymous else user_control.objects.values( 'position__rank' ).get( user = user.id ) return True if position > 1 else False @user_passes_test(position_check, login_url='loginPage') def index(request): pass @user_passes_test(position_check, login_url='loginPage') def exportReview(request): pass I was try: class PositionCheck(self): position = 0 if user.is_anonymous else user_control.objects.values( 'position__rank' ).get( user = self.request.user.id ) return True if position > (replace with parameter) else False class Review(PositionCheck, View): def index(request): pass def exportReview(request): pass -
Django - display Httpresponse in template
This is what I have in views This a function in javascript I get this message when I run the project However the responses are displayed in a blank page like this how do I get the httpsresponse to display in the same page in the chat window and not in a different page I'm completely new to Django and javascript . It would be of great help if anyone can help. Thanks in advance. -
Django-debug-toolbar not showing
I am using django 4.0.3 and django-debug-toolbar 3.2.4. For some reason, the toolbar is not showing on my server.I tried many ways but none of them worked for me. I will be very grateful for any help settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news.apps.NewsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] WSGI_APPLICATION = 'mysite.wsgi.application' # debug_toolbar moved here. if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] INTERNAL_IPS = ['127.0.0.1', ] # this is the main reason for not showing up the toolbar import mimetypes mimetypes.add_type("application/javascript", ".js", True) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } urls.py if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Add hyperlinks from an array to elements of a table Django
I have a csv file with 3 columns. I want to display this table in a html but every element of the third column should have a hyperlink loaded from a python array in views.py. Currently, I am loading the table using pandas. My views.py: def passparam(request): data = pd.read_csv (r'/home/darkbee/django3-password-generator/media/test.csv') html_table = data.to_html(index=False) arra_containing_links["#link1","#link1",............."#link1","#link80"] context = {'loaded_data': html_table} return render(request, 'generator/password.html',context ) My password.html: {{loaded_data | safe}} Any help is very much appreciated <3