Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I get NoReverseMatch at /signup/ after filling my signup form
I've tried using redirect, reverse, reverse_lazy, all gives the same error: NoReverseMatch at /signup/ from django.shortcuts import redirect class SignUp(FormView): template_name = 'blogApi/tenant_registration.html' form_class = ClientForm def get(self, request, *args, **kwargs): form = ClientForm() context = {'form': form} return render(request, 'blogApi/tenant_registration.html', context) def form_valid(self, form): name = form.cleaned_data['name'] Client.objects.create(name=name, schema_name=name, domain_url=name + ".localhost") return redirect('') URL.py file: from django.urls import path, include from .views import SignUp, signup urlpatterns = [ path('signup/', SignUp.as_view(), name="sign_up"), path('home/', include('blogApi.urls'), name=''), ] -
add sections/cluster from users end in html via choices or any other approach
Suppose im saving a url from a texbox given by user the URL is submitted by user and its saved to my models and now what i wanna do is let the user add different sections/clusters such as technology,sports etc from his end suppose where he inputs the URL there itself he can define that cluster/section and save that particular URL to the particular section/cluster he made or selected in the option is the section/cluster was already there! could anyone help or give me a small example for the same? what would be a better approach do it with django choices or some other way? TIA. -
Add jquery to django
I can't add jquery to django app. What I did wrong? Button click didn't have any results. My code base.html {% load static %} <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> ... {% block content %} {% endblock %} <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script> </body> </html> main_list.html {% extends 'blog/base.html' %} {% block content %} <div> <h1> Button </h1> <a class="likebutton" id="like" data-catid="AAA" href="#">Like</a> </div> <script type="text/javascript"> $("#like").click(function(){ alert('Test Ajax'); }); </script> {% endblock %} -
I want to make the file upload successful
Excuse me, but there are two things I want to achieve. ・I want to make the file upload successful ・I want to store different types of media files in different folders. Currently, the files cannot be uploaded to one folder before storing the files in different folders. I filled in the form and sent it, but the error message "This field is required." was displayed above the form in index.html. The following images are in the "media/documents" folder installed under the project directory. Below is the index.html. {% load static %} <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" type="text/css" href="{% static 'uploader/css/style.css' %}"> <title>Document</title> </head> <body> <div> <p>YoutubeUploader</p> {% for field in form %} {{ field.errors }} {% endfor %} <form method="post" action="{% url 'uploader:result' %}" enctype="multipart/form-data"> {% csrf_token %} <p>タイトル: <input type="text" name="title"></p> <p>説明: <textarea class="description" name="説明" rows="5" cols="50"></textarea></p> <p>タグ: <textarea class="description" name="説明" rows="5" cols="50"></textarea></p> <p>カテゴリ: <select name="category"> <option>映画とアニメ</option> <option>自転車と乗り物</option> <option>音楽</option> <option>ペットと動物</option> <option>スポーツ</option> <option>旅行とイベント</option> <option>ゲーム</option> <option selected>ブログ</option> <option>コメディ</option> <option>エンターテインメント</option> <option>ニュースと政治</option> <option>ハウツーとスタイル</option> <option>教育</option> <option>化学と技術</option> <option>非営利団体と社会活動</option> </select> </p> <p>client_secret(JSON): <input type="file" name="certification_file"></p> <p>movieFile: <input type="file" name="movie_file"></p> <button type="submit">send</button> </form> </div> </body> </html> Below is the forms.py from django import forms from .models … -
How can I fetch data continually from database in Django
I want to set a listener for my PostgreSQL database using Django that fetchs data whenever a child is added. Something like OnChildAdded for Firebase. Any suggestions? -
Edit button is not working - Django & Ajax
I hope you are well. I am new to django & ajax. I am trying to create a CRUD page/form and have followed the example on GitHub https://github.com/sureshmelvinsigera/Django-Ajax-Example. However when I try to update record and click on update button the record doesn’t update at all. Python Version: 3.8.2 Django Version: 3.0.6 Below is the code of CRUD application: model.py from django.db import models class BookModel(models.Model): title = models.CharField(max_length=50) publisher = models.CharField(max_length=50) author = models.CharField(max_length=30, blank=True) price = models.DecimalField(max_digits=5, decimal_places=2) pages = models.IntegerField(blank=True, null=True) *views.py from django.shortcuts import render from apps.bookadmin.models import BookModel from apps.bookadmin.form import BookModelForm from django.http import JsonResponse from django.forms.models import model_to_dict def bookadmin_update_book(request, id): if request.method == 'POST' and request.is_ajax(): try: book_object = model_to_dict(BookModel.objects.get(pk=id)) return JsonResponse({'error': False, 'data': book_object}) except BookModel.DoesNotExist: return JsonResponse({'status': 'Fail', 'msg': 'Object does not exist'}) return JsonResponse({'status': 'Fail', 'msg': 'Object does not exist'}) index.html <div class="container"> <div class="jumbotron"> <h1 class="display-4">Django Ajax CRUD</h1> <p class="lead">CRUD operations form basics for database operations at the backend. Conventional Django apps result in a page reload after HTTP methods such as 'POST' and 'GET'. </p> <hr class="my-4"> <p>To overcome this and to implementing more immersive User experience we can use Ajax along with JQuery for posting data … -
Draft posts: custom manager extracts published posts only, but in the admin site I need all posts
Django 3.0.8 class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(draft=False) class Post(models.Model): published = PublishedManager() ... Problem In the admin site drafts are not visible now. It seems reasonable: Post.published.all() <QuerySet []> But how can I show all posts in the admin? -
How to create a page to show that user had reach the call API limit with django python
So I am making an project that call user API from github and after 60 times I will get this error: And I want if user got that error I want it return a page like this: How can I do that ? -
Can any one have a solution of my problem i am trying to run django server in ubuntu 20.04 but failed to run
I have created env variable and installed python3 after that install django server successfully but i am getting error and unable to received any port nor ip from the server. my concern is failed to run the django server. Error code is below env) (base) developer@MCA:~/django-apps/project/myapp$ python manage.py runserver Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x7fdb26e420d0> Traceback (most recent call last): File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "/home/developer/django-apps/env/lib/python3.8/site-packages/django/contrib/admin/filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File … -
Advanced Python for web development
I have learned Python with Django, now I am able to write backend API for websites like hotel reservation, OAuth 2 integration, cloning of Instagram etc. Most courses in online learning medias (Udemy/Lynda ) are for beginners . I wish to become an advanced Python developer, can anybody advise me the right track? I wanted to develop websites' back ends that handle high traffic with better performance (multi threading/multiprocessing). -
foreign key mismatch - "Comment" referencing "Chellenge"
class Chellenge(models.Model): sno = models.AutoField(primary_key=True, default="1",null=False) chellengeName = models.CharField(max_length=50, blank=False, null=False) chellengeDesc = models.TextField(max_length=1000, blank=True, null=True) class Comment(models.Model): sno = models.AutoField(primary_key=True, default="1") user_id = models.ForeignKey(User, on_delete=models.CASCADE) message = models.TextField() chellenge_id = models.ForeignKey( Chellenge, to_field='sno', on_delete=models.CASCADE) # This one works exact time of current location parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) date_comment = models.DateTimeField(default=now) why i getting the error django.db.utils.OperationalError: foreign key mismatch - "Comment" referencing "Chellenge" at the time of migrate? how to solve?? -
how i can publish my project on Google I am getting error
I have made a project on the Django and it is complete but how I can publish it on a webserver I am trying to publish on google but when I install google cloud SDK and try to transfer the project in it then I am unable to edit it on py charm -
Getting PermissionError: [Errno 13] Permission denied While doing ./manage.py collecstatic
I am getting PermissionError: [Errno 13] Permission denied: while I am running collectstatic command. Previously I was used s3 for static files, but I don't want to use that. I was switching back to Django's Native static handler. I reverted the settings and removed STATICFILES_STORAGE. But now I started getting PermissionError. I even changed static folders permissions to 777 but that didn't help. I tried creating a new project But in that project, collectstatic command is working fine. I also took a clone of the same project at 2 different locations on my system but it was also not working. The static folder owner is also correct. drwxr-xr-x 6 rohit.chopra domain users 4096 Jul 4 13:24 static/ drwxr-xr-x 2 rohit.chopra domain users 4096 Jul 4 13:22 templates/ Setting.py # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, 'static'), # ] # STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) # STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'medicine.storage_backends.MediaStorage' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I have commented the previous settings. Can you guys please help me resolve this issue. -
Ajax call to change icons
I created below button <button id="wishbtn" data-slug='{{ list.slug }}'><i class="far fa-heart"></i></button> which calls an Ajax call. $(document).on('click', '#wishbtn', function (e) { let el = $(this); $.ajax({ type: 'GET', url: "{% url 'listing:wishlist' %}", data: { title_slug: el.attr("data-slug"), }, success: function () { alert('added to wishlist'); } }) }); How do I change the class of i tag to fas fa-heart once the button is clicked. I tried using this keyword in success function to change its class $(this).classList.replace('far', 'fas') but it didn't work. I tried using e.target.getElementsByTagName('i')[0].classList.replace('far', 'fas') and again no hope. Can you help me please, thank you. -
custom validation error for two fields unique together django
i want to write my own validation error , for two fields unique together class MyModel(models.Model): name = models.CharField(max_length=20) second_field = models.CharField(max_length=10) #others class Meta: unique_together = ('name','second_field') and my forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' error_messages= {#how to write my own validation error whenever `name and second_field` are unique together }: how to write my own validation error whenever name and second_field are unique together? i need to raise some error if both fields were unique together ?thanks for replying -
Problems upgrading to oscar 2
I am trying to upgrade from oscar 1.6.7 to 2.0 I have a few forked apps and have followed the instructions [here][1]. i.e. renaming config.py to apps.py etc. I get, however, an error and the apps don't seem to be loading correctly. Any ideas on how to approach debugging this? Thanks! Below the full exception stack trace: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/oscar/core/loading.py", line 228, in get_model return apps.get_model(app_label, model_name) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 193, in get_model self.check_models_ready() File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 132, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked … -
Inline in Django Admin in Children Class
I have a Mentor Class which has Many to Many relation with Matrimony Profile model: class Mentor(BaseModel): profile = models.ManyToManyField(MatrimonyProfile) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=17, null=True, unique=True) email = models.EmailField(null=True, blank=True) class Meta: ordering = ["name"] db_table = "mentor" def __str__(self): return f"{self.name}" in admin.py i have MentorInline like this: class MentorInline(admin.TabularInline): model = Mentor extra = 1 can_delete = True verbose_name = "Mentor" verbose_name_plural = "Mentors" I want to display this inline in children class of Matrimony profile i.e. Male, Female but I get this error: ERRORS: <class 'vmb.matrimony.admin.MentorInline'>: (admin.E202) 'matrimony.Mentor' has no ForeignKey to 'matrimony.Female'. <class 'vmb.matrimony.admin.MentorInline'>: (admin.E202) 'matrimony.Mentor' has no ForeignKey to 'matrimony.Male'. Need some help here -
How to use Ajax in Django for like button
I want to Ajax feature for the like button in my blog. I have implemented like feature first, it was working as expected(reloads page after clicking like button). Then, i want to implement Ajax so the page should not reload after clicking like button. But, it is not working as expected. views.py: def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('id') post_obj = get_object_or_404(Post, id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() if request.is_ajax(): post = Post.objects.all() context={ 'post': post } html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) Jquery in base.html: <script src="https://code.jquery.com/jquery-3.1.1.min.js"> <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); console.log("hello") var pk = $(this).attr('value'); $.ajax({ type : 'POST', url : {% url 'like-post' %}, data : {'id' : pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType : 'json', success : function(response){ $('#like-section').html(response['form']) console.log($('#like-section').html(response['form'])); }, error : function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> like_section.html: <form action="{% url 'like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value="{{ post.id }}"> {% if user not in post.liked.all %} <button id="like" class="btn btn-outline-info mb-4" type="submit">Like</button> {% else %} <button … -
Polymorphic model get foreign key directly in django
For example, I have a model A which has a foreign key point to model B like this: class A(Base): b = models.ForeignKey(to=B, related_name='Bs') Then when I get objects with Base.objects.all(), then Django fetch every B for each A in the result. How can I change this behavior? -
success_url doesn't redirect to redirect page
Please help me out. My success_url doesn't redirect to the redirect page specified. I've tried using HttpResponseRedirect, reverse_lazy, and reverse. All gives the same issue. Views: class SignUp(FormView): template_name = 'blogApi/tenant_registration.html' form_class = ClientForm success_url = HttpResponseRedirect("home") def get(self, request, *args, **kwargs): form = ClientForm() context = {'form': form} return render(request, 'blogApi/tenant_registration.html', context) def post(self, request, *args, **kwargs): form = ClientForm(data=request.POST) if form.is_valid(): name = form.cleaned_data['name'] Client.objects.create(name=name, schema_name=name, domain_url=name + ".localhost") # return render(request, 'blogApi/tenant_registration.html', {'form': form}) return render(request, 'blogApi/tenant_registration.html', {'form': form}) urls urlpatterns = [ path('signup/', SignUp.as_view(), name="sign_up"), path('home/', include(router.urls), name='home'), path("register", signup, name="register") ] html page: <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Create Account"> </form> -
AWS Elastic Bean Stack EB Extension Configuration for Django Application Deployment
On deploying the Django app to AWS Elastic Beanstalk, we can use the following EB extension configuration for simplified deployment. This is the latest compilation of all the notes that is followed on aws docs and other sites. On Local Machine, get AWS EB CLI Then init eb, and follow the step with proper settings. eb init create eb env eb create deploy deploying create a folder .ebextension and with file django.config, then write everything as once for application settings, migration using mysql , collect static for production level ./ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: mysite.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static packages: yum: python3-devel: [] mariadb-devel: [] container_commands: 01_collectstatic: command: "source /var/app/venv/staging-LQM1lest/bin/activate && python manage.py collectstatic --noinput" 02_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && python manage.py migrate --noinput" leader_only: true /var/app/venv/staging-LQM1lest/bin/activate This is to activate the virtual environment on EBS Now deploy to your env eb deploy This will deploy and run migration and collect static files -
Is it a good idea to build a job search engine using Django & Apache Solr & React.js (for mobile apps)?
I'm an absolute beginner in python & programming so... be gentle 📷 I want to build a job search engine using: A. For BackEnd: Django (for secured login, optimized urls, ORM etc, clean & organized working environments) Apache Solr (for the job postings because I need a very fast search tool as I expect to be, HOPEFULLY, very many simultaneous search requests from a lot of simultaneous users), PostgreSQL (for storing CV's, as I don't expect CV's database to face very many simultaneous searches, also for storing metadata and other data that is not heavily searched for) B. For FrontEnd: HTML 5, CSS3, Bootstrap 4,JavaScript, React.js to build MobileApps for Ios and Android smartphones Now... thing is that, besides other questions, I have little if any ideea how to connect Django and Apache Solr... there little if any documentation... so, I really need all the help you may spare... any advice & help is welcome ! For those who have experience working with Django & Apache Solr: is it worth it? Does it suit a very fast & reliable multiple simultaneous concurrent searches with a lot of users searching for the same job posting in the same time? Because I … -
initdb: error: could not create directory "./PostgreSQL": Permission denied
It is my first time setting up a database (postgresql 12) on my windows 8.1 It's been 4 days of struggling to find a solution from many related questions in this field but not successful to find the answer (whether I didn't understand them or they didn't work in my case). So, here, I will explain, step by step, what I did and what errors I got in each phase (They may not affect each other but I mention all the errors): When I installed PostgreSQL, at the end of the process I got this error: "Failed to load SQL modules into the database cluster" I reinstalled twice it but it seemed to pop up every time. Here, in this post, I found somebody who faced the same problem, but I didn't technically understand what is the solution, unfortunately: Failed to load sql modules into the database cluster during PostgreSQL Installation. thus, I just skipped it and everything seemed okay. Then I set the PATH in advanced system settings-->Environment variables (in both user variables and system variables boxes) like this: ";C:\Program Files\PostgreSQL\12\bin;C:\Program Files\PostgreSQL\12\lib" After this step, I opened a terminal using ctrl+R and entered cmd.exe then entered these codes: > … -
download image from sql server to local machine using django
i have a table in sql server filestorage with columns : storageid: unique identifier BinaryData: image i need to download this binarydata which will form an image/ppt/etc.. to my local system using django. How do i do it? -
for loop in resources.html doesn't work returns "test" only
for loop in resources.html doesn't work returns "test" only. I think the for loop cannot retrieve data from the database. recources.html <ol> {% for x in ac %) <li> <a href="/projectname/{{ course.id }}/"> {{ x.coursename }} </a></li> {% endfor %} </ol> <p> test </p> views.py def Courses(request): ac= Allcourses.object.all() template = loader.get_template('/projectname/resources.html') context = { 'ac':ac,} return HttpResponse(template.render(context, request)) urls.py urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path('resources',views.Resources.as_view(),name= 'resources'), path('resources/<int:course_id>/',views.detail, name = 'detail'), ] models.py class Allcourses(models.Model): coursename=models.CharField(max_length=200) instructorname=models.CharField(max_length=200) def __str__(self): return self.coursename class details(models.Model): course=models.ForeignKey(Allcourses, on_delete=models.CASCADE) selfpaced=models.CharField(max_length=500) intructor_lead=models.CharField(max_length=500) def __str__(self): return self.selfpaced