Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my django table not being found during testing?
I am trying to unit test a model that has an abstract model embedded in it but the table can't be found. I have tried deleted migrations and the db and after making new migrations, am still getting the same result. I have also tried the following command: py manage.py migrate --run-syncdb error Traceback (most recent call last): File "C:\main_venvs\prompted\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\main_venvs\prompted\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: boards_board models.py from django.db import models from .behaviors import PermalinkAble class Board(PermalinkAble, models.Model): short_name = models.CharField( max_length=3, unique=True ) long_name = models.CharField( max_length=24, unique=True ) info = models.TextField( max_length=300 ) url_name = 'board' def __repr__(self): return self.short_name @property def slug_source(self): return self.short_name behaviors.py from django.db import models from django.contrib.auth.models import User class PermalinkAble(models.Model): slug = models.SlugField() class Meta: abstract = True test_models.py from django.test import TestCase from prompted.boards.models import Board class BoardTestCase(TestCase): @classmethod def setUpTestData(cls) -> None: Board.objects.create( id=1, short_name='nope', long_name='what the nope', info='what the actual nope', ) test_board = Board.objects.get(id=1) -
Google map widget in Django admin
I have a model with a location field like so: from django.contrib.gis.db import models as gis_models class Facility(models.Model): location = gis_models.PointField(srid=4326, verbose_name=_('location'), null=True, blank=True) I want the user to be able to set a location using a map in django admin. I have added the below code in my django admin: from django.contrib.gis.db import models as gis_models from mapwidgets.widgets import GooglePointFieldWidget @admin.register(Facility) class FacilityAdmin(admin.ModelAdmin): formfield_overrides = { gis_models: {'widget': GooglePointFieldWidget}, } at the end I have added the following setting to my settings.py: MAP_WIDGETS = { "GooglePointFieldWidget": ( ("zoom", 12), ("mapCenterLocation", [ 50.8157, 9.1846]), ), "GOOGLE_MAP_API_KEY": env('GOOGLE_MAP_API_KEY') } I am using postgis image as my database and the following is my requirements.txt: asgiref==3.5.2 async-timeout==4.0.2 branca==0.5.0 certifi==2022.9.24 chardet==5.0.0 charset-normalizer==2.1.1 click==8.1.3 colorama==0.4.6 Deprecated==1.2.13 Django==4.1.2 django-crispy-forms==1.14.0 django-environ==0.9.0 django-map-widgets==0.4.0 django-rq==2.5.1 folium==0.13.0 idna==3.4 Jinja2==3.1.2 lml==0.1.0 MarkupSafe==2.1.1 numpy==1.23.4 packaging==21.3 pandas==1.5.1 Pillow==9.2.0 postgis==1.0.4 psycopg2==2.9.4 pyexcel==0.7.0 pyexcel-io==0.6.6 pyparsing==3.0.9 python-dateutil==2.8.2 pytz==2022.5 redis==4.3.4 requests==2.28.1 rq==1.11.1 six==1.16.0 sqlparse==0.4.3 texttable==1.6.4 tzdata==2022.5 urllib3==1.26.12 wrapt==1.14.1 The map appears in django admin, but as it turns out, it doesn't read the settings. Also the styling of the map is just unacceptable. Is there any way it could be fixed? Right now this is what I'm getting in my django admin panel: -
Escaping html in admin list display, tinymce
Cannot find anyhere. My list display (content) shows html tags after installing tinymce editor. Do I need to find admin panel html template? -
designed django cart shopping
My shopping cart is designed in such a way that the user must be logged in. How can I design the shopping cart with these two conditions that it must be stored in the database and not in the session and that the user does not need to login to add the product to the shopping cart? my model : class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return self.user.username my view : def cart_detail(request): cart = Cart.objects.filter(user_id=request.user.id) return render(request, 'cart/cart.html', {'cart': cart, }) -
I have a few categories and I would like to list the products per category
I have a few categories and I would like to list the products per category in the format below (categories is an FK to products): Category 1 bunch of products .... Category N bunch of products I have tried many ways but so far I only get the categories but not the products to show in my HTML. I m new in django cant find the solution in models.py: from django.utils import timezone from distutils.command.upload import upload from email.policy import default from django.db import models from django.contrib.auth.models import User # Create your models here. class Main_Category(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class Sub_Category(models.Model): main_category=models.ForeignKey(Main_Category,on_delete=models.CASCADE) name=models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): Status=('publish','publish'),('draft','draft') product_id=models.AutoField name=models.CharField(max_length=50) category=models.ForeignKey(Main_Category,on_delete=models.CASCADE,null=True,default="") sub_category=models.ForeignKey(Sub_Category,on_delete=models.CASCADE,null=True,default="") price=models.IntegerField(default=0) des=models.CharField(max_length=2000) status=models.CharField(choices=Status,max_length=200) delivery=models.IntegerField(null=True) date=models.DateTimeField() image=models.ImageField(upload_to="shop/images",default="Status") slug=models.CharField(max_length=150) def __str__(self): return self.name @property def get_products(self): return Product.objects.filter(categories__title=self.name) class Orders(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) amount=models.CharField(max_length=55) Order_id=models.AutoField(primary_key=True) name=models.CharField(max_length=55) email=models.CharField(max_length=30) address=models.CharField(max_length=200) phone=models.CharField(max_length=15) city=models.CharField(max_length=20) state=models.CharField(max_length=20) zip_code=models.CharField(max_length=10) date=models.DateTimeField(default=timezone.now) def __str__(self): return self.user.username class OrderItem(models.Model): order=models.ForeignKey(Orders,on_delete=models.CASCADE) product=models.CharField(max_length=200) image=models.ImageField(upload_to="shop/images/cust_image") quantity=models.CharField(max_length=20) price=models.CharField(max_length=15) total=models.CharField(max_length=1000) def __str__(self): return self.order.user.username Views.py from django.shortcuts import redirect, render from .models import Main_Category, Product,Sub_Category,Orders,OrderItem from django.core.paginator import Paginator from django.contrib.auth.decorators import login_required from cart.cart import Cart from django.contrib.auth.models import User,auth from django.contrib import messages # Create your views here. def index(request): allproduct=Product.objects.all() … -
Migrate DB on Railway: ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value
I want to migrate my db to Railway Postgres. I put my DATABASE_URL as a env variable in prod.env file: DATABASE_URL='postgresql://postgres:(my password here)F@containers-us-west-97.railway.app:6902/railway' Here how I import it in my prod settings file: DATABASE_URL = os.getenv("DATABASE_URL") DATABASES = { "default": dj_database_url.config(default=DATABASE_URL, conn_max_age=1800), } When I try to migrate the db: ./manage.py migrate --settings=app.settings.prod I get an error: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check the settings documentation for more details. I used the same approach when I migrated my DB to Heroku, and it worked well. How can I resolve this? -
How to run sphinx-autobuild on the server in a django project
I am trying to install the code documentation on the Sphinx server. (https://pypi.org/project/sphinx-autobuild/). The problem is that the sphinx-autobuild command should be run from the folder where sphinx (docs) is installed, provided that the virtual environment (venv) is enabled.I have a django project running on gunicorn and I need a command to run from the docs sphinx-autobuild folder together with the launch via gunicorn. A bash script was created that runs a command and a service to run the script, but it does not work because when the script is run, it does not see the raised virtual environment. It turns out gunicorn raises the site, but this is not enough for the script to work. Maybe I don't understand something and because of this I can't figure out how to implement it. -
How to host multiple django apps with nginx proxy and redirect by subdomain?
I create proxy container with docker and generate ssl certificates to my domain with jwilder/nginx-proxy. It's works, but now tried redirect my django apps by subdomain and every request return 502 bad gateway. I'm a noob to this. I need help to know what I'm doing wrong. This is my docker-compose nginx-proxy: version: '3' services: nginx-proxy: image: jwilder/nginx-proxy restart: always ports: - "80:80" - "443:443" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - certs:/etc/nginx/certs:ro - vhostd:/etc/nginx/vhost.d - html:/usr/share/nginx/html labels: - com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion restart: always environment: - NGINX_PROXY_CONTAINER=nginx-proxy volumes: - certs:/etc/nginx/certs:rw - vhostd:/etc/nginx/vhost.d - html:/usr/share/nginx/html - /var/run/docker.sock:/var/run/docker.sock:ro www: image: nginx restart: always expose: - "80" volumes: - /Users/kbs/git/peladonerd/varios/1/www:/usr/share/nginx/html:ro environment: - VIRTUAL_HOST=pablokbs.com,www.pablokbs.com - LETSENCRYPT_HOST=pablokbs.com,www.pablokbs.com - LETSENCRYPT_EMAIL=pablo@pablokbs.com depends_on: - nginx-proxy - letsencrypt volumes: certs: html: vhostd: and this is docker-compose django app (bak_web is app to redirect by subdomain): version: "3" services: core_api: build: context: . env_file: .env container_name: "bak-api" ports: - 8181:8181 volumes: - ./BAK_API:/bak_api - ./bak:/bak_api command: uvicorn bak.asgi:app --host 0.0.0.0 --port 8181 bak_web: build: context: . expose: - "80" env_file: .env container_name: "bak-web" volumes: - static:/bak_web/static - .:/bak_web - ./bak_chatbot:/app nginx-bak-web: image: nginx restart: always expose: - "80" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static:/bak_web/static environment: - VIRTUAL_HOST=bakzion.duckdns.org - LETSENCRYPT_HOST=bakzion.duckdns.org - LETSENCRYPT_EMAIL=omar.cravioto.p@gmail.com depends_on: - … -
Django: Question regarding queries over a junction table/intermediary model
my question concerns the many-to-many section of the django models docs: It is mentioned there that by using an intermediary model it is possible to query on the intermediary model's attributes like so: Person.objects.filter( group__name='The Beatles', membership__date_joined__gt=date(1961,1,1)) However for the other many-to-many model (Group) a similar query results in a FieldError: # which groups have a person name containing 'Paul'? Group.objects.filter(person__name__contains="Paul") Queries that reference the junction table explicity do work: Person.objects.filter(membership__group__name__contains="The Beatles") Group.objects.filter(membership__person__name__contains="Paul") Shouldn't Group therefore have access to Person via the junction model? -
how to create two table objects by one viewset django rest framework
Hi i am trying to save objects in reviews table from posts table filtered by type="R" i think i should override def create but i don't know how. please help me thanks. my posts table my reviews table this is my post model class Post(models.Model): """Model definition for Post.""" class Meta: db_table = 'posts' verbose_name = 'Post' verbose_name_plural = 'Posts' POST_TYPE = ( ('R', 'review'), ('C', 'clubpost'), ('A', 'advertisement'), ) title = models.CharField( max_length=20, null=False, verbose_name='제목' ) content = models.TextField( max_length=2000, null=False, verbose_name='내용' ) author = models.ForeignKey( User, on_delete=models.CASCADE, null=False, verbose_name='글쓴이', ) type = models.CharField( max_length=5, choices=POST_TYPE, null=True, verbose_name='글 종류', ) created_at = models.DateTimeField( auto_now_add=True, verbose_name='생성 일시', ) updated_at = models.DateTimeField( auto_now=True, verbose_name='수정 일시', ) review model class Review(models.Model): class Meta: db_table = 'reviews' verbose_name = 'Review' verbose_name_plural = 'Reviews' post = models.OneToOneField( Post, on_delete=models.CASCADE, related_name="review", ) post serializer class PostSerializer(ModelSerializer): author = UserAbstractSerializer(read_only=True) class Meta: model = Post fields = [ 'id', 'title', 'content', 'author', 'type', 'created_at', 'updated_at' ] extra_kwargs = { 'title': { 'error_messages': { 'required': '제목을 입력해주세요.', } }, 'content': { 'error_messages': { 'required': '내용을 입력해주세요.', } } } review serializer class ReviewSerializer(ModelSerializer): post_id = PostSerializer(read_only=True) class Meta: model = Post fields = [ 'id', 'post_id', ] … -
django rest framework nested categories
it is written in nested categories to categorize products. When we were working with Django itself, to display the nested categories in the navbar section, we used to display both the main and nested categories with the four loop twice. My question is that now that I want to write the code in django rest framework to display the nested categories, in addition to the code below, do I have to do anything else? In fact, the issue that is bothering me is how the nested category is called and displayed by the front-end programmer? my model : class Category(models.Model): name = models.CharField(max_length=200, null=True, blank=True) sub_category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='sub') sub_cat = models.BooleanField(default=False) slug = models.SlugField(allow_unicode=True, unique=True, null=True, blank=True) class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True) category = models.ManyToManyField(Category, blank=True, related_name='cat_product') unit_price = models.IntegerField() my url : path('category/', views.CategoryListApi.as_view()), path('category/<slug:slug>/', views.CategoryProductsApi.as_view()), my view: class CategoryListApi(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer class CategoryProductsApi(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): products = Product.objects.filter(category__slug=self.kwargs['slug']) return products my serializer: class ProductSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() class Meta: model = Product fields = '__all__' def get_category(self, obj): return [cat.name for cat in obj.category.all()] class CategorySerializer(serializers.ModelSerializer): sub_category = serializers.SlugRelatedField(read_only=True, slug_field='name') class Meta: model = Category fields = … -
Trying to make a search/filter dropdown with select2 and ajax. my self defined is_ajax(request) function not working?
I am making a django project where there is a search/filter dropdown for a form. I am using select2 and ajax. It isn't working, and when I try to debug with print statements, it seems that the is_ajax(request) function is not returning true. I know the is_ajax() function was deprecated in JQuery, which is why I defined it myself. However, mine doesn't seem to work either. Here is the portion my view that filters objects: @login_required def job_application_create(request): form = JobApplicationForm() if is_ajax(request): print('TESTING TESTING TESTING TESTING TESTING TESTING TESTING TESTING ') term = request.GET.get('term') companies = Company.objects.filter(name__icontains=term) response_content = list(companies.values()) return JsonResponse(response_content, safe=False) and here is the is_ajax(request) definition: def is_ajax(request): return request.headers.get('x-requested-with') == 'XMLHttpRequest' Here is the JS in the page that has my form: <script> $(document).ready(function () { $('#id_company').select2({ ajax: { url: "{% url 'homepage' %}", dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.name}; }) }; } }, minimumInputLength: 1 }); }); </script> -
Django Login Access with token
I am developing a Django project, I have created an API in the same project since other tools should be able to use functions from this project. This method is not working and I need someone who has done a similar thing to assist with a more refined and secured method or point out where am doing wrong. When a user is registered, I create an access token ( md5 has ) for this user and store it in a model, each token has a user foreign key. class AuthToken(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) token = models.TextField() created_date = models.DateField(auto_now_add=True) created_time = models.TimeField(auto_now=True) status = models.IntegerField(default=0) in the API, I have added a function to authenticate the user with the token. When the view to authenticate the user is invoked, what I do is. Check if the token exists. Get the user ( AuthToken.user.username ) Get user password ( AuthToken.user.password) Authenticate these details with Django authenticate I understand this will definitely fail since the password fetched from AuthToken.user.password with be an encrypted one, and passing the encrypted password to Django for authentication will encrypt that and compare again. Below is my API authentication view if module == 'auth': # authentication … -
Postgresql ignoring default value on bulk import
I have a postgres DB running in a docker container. I am trying to bulk import a csv full of postcodes. This is a Django project. As they all refer to the same state - "NSW". That column doesn't exist in the CSV. My Model (This is django) has the following definition for the State column: state = models.CharField(max_length=200, default="NSW", null=False, blank=False) But when I try and execute I get the following error: postgres=# \COPY datacollector_localities(name, postcode) FROM '/postcodes-nsw.csv' DELIMITER ',' CSV HEADER; ERROR: null value in column "state" of relation "datacollector_localities" violates not-null constraint DETAIL: Failing row contains (5, Condobolin, 2877, null). CONTEXT: COPY datacollector_localities, line 2: "Condobolin,2877" I assumed the leaving state out of the column_names list would make postgres use the default. What am I doing wrong? -
Is it possible to add a subquery table to a django queryset?
I am working on a query similar to the one below; I want to create this as a Django queryset for further filtering. select distinct on (id) id, title, weight from (select *, 3 + ts_rank_cd(to_tsvector(title), to_tsquery('sales'), 32) as weight from courses where to_tsvector(title) @@ to_tsquery('sales') union all select *, 2 + similarity(title, 'sales') as weight from courses where title % 'sales') as union_table order by id, weight desc I tried creating it as raw method, but that doesn't allow chaining additional filters and the extra method with the tables argument doesn't allow subqueries. Is there any solution other than using the raw SQL? -
Django - Connection refused mysql on ubuntu subsystem windows 10
I'm using xaamp for MySQL DB and I run my server on both cmd and ubuntu subsystem but my ubuntu says django.db.utils.OperationalError: (2003, 'Can't connect to MySQL server on '127.0.0.1' (111 "Connection refused")') -
How do I load django user data into user edit form in permission escalation safe environment
I am trying to create a profile edit form in django for Users in a way that they cannot set themselves as superuser or staff. This is my first learning project in django and so far I have followed https://docs.djangoproject.com/en/4.1/topics/forms/ to set everything up. in views.py @login_required def edit_profile(request): user = request.user if request.method == 'POST': form = edit_profile_form(request.POST) if form.is_valid(): if user.is_authenticated: try: user.first_name = form.cleaned_data['firstname'] user.last_name = form.cleaned_data['lastname'] user.email = form.cleaned_data['email'] user.username = form.cleaned_data['username'] user.save() except Exception as e: return HttpResponse(e) return render(request, 'index.html') else: #Get data ready for form data = {'firstname': user.first_name, 'lastname': user.last_name, 'email': user.email, 'username': user.username} form = edit_profile_form(data) return render(request, 'edit_profile.html', {'form': form} ) in forms.py from django import forms class edit_profile_form(forms.Form): firstname = forms.CharField(label='First name', max_length=100,) lastname = forms.CharField(label='Last name', max_length=100) email = forms.EmailField(label='Email', max_length=100) username = forms.CharField(label='Username', max_length=150) def __init__(self, *args, **kwargs): data = kwargs.get('data', None) super(edit_profile_form, self).__init__(*args, **kwargs) if data: self.fields['firstname'].initial = data['firstname'] self.fields['lastname'].initial = data['lastname'] self.fields['email'].initial = data['email'] self.fields['username'].initial = data['username'] in edit_profile.html {% extends 'base.html' %}{% load static %} {% block content %} <link href="{% static 'css/edit_profile.css' %}" rel="stylesheet" /> <main class="profile"> <form method='POST'> {% csrf_token %} <h1> Profile editor </h1> {{ form }} <input type='submit' value='Submit' class='btn … -
uploaded images not displayed in Django
I'm developping a django app but recently, I faced a challenge of images files uploaded in django admin that are not being displayed on pages, I tried every solution given here on the platform but none of it gave me a solution, plz does someone can help with this issue because it is been a while working on without a result. These are my models class House(models.Model): image_house = models.ImageField(upload_to='Images/', default='Images/house.png') # Cars property model class Car(models.Model): image_car = models.ImageField(upload_to='Images/', blank=True, default='Images/car.png') # Fields property model class Land(models.Model): image_land = models.ImageField(upload_to='Images/', blank=True, default='Images/land.png' ) and I set this in settings.py STATIC_URL = '/static/' # Media root and urls MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And that' how I called the uploded picture from the model in Index.html <img src="{{ house.image.url }}" class="card-img-top" alt="..."> in my project urls I added urlpatterns = [ path('admin/', admin.site.urls), path('', include('realest_app.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) -
Reason given for failure: CSRF token from POST incorrect.?
Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token from POST incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. please solve this? Reason given for … -
How do I use my coding skills for the greater good?
I am 17 year old African kid who knows HTML,CSS,JS(from freecodecamp) and currently learning django for making fullstack applications. I have no idea of what projects to make of them that will help my society and community. After solving the problem I want to write an essay about it when I apply to colleges and universities. something doable and takes few months to fully launch, since I am a senior I don't have much time in my hand. Please be specific don't give me only catagories. Ideas I got from my friends,family and internet: website for non-profit banking system government system school club websites -
Fixing "missing 1 required positional argument: 'id'" error when sending data from Django Form using Ajax
I have a Django Form where users inserts numeric values. I am sending the Ajax to a url but I keep receiving: TypeError: addlog() missing 1 required positional argument: 'id' I have tried to add the id in the url I got: Reverse for 'addlog' with arguments '(2,)' not found. 1 pattern(s) tried: ['workout/addlog/\\Z'] Here is the views: def addlog(request, id): workout = get_object_or_404(Workout, id=id) url = request.META.get('HTTP_REFERER') active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id) if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == 'POST': form = LogForm(request.POST) if form.is_valid(): data = Log() data.log_workout = request.POST.get('log_workout') data.save() context = { 'log_workout': data.log_workout, 'id': workout.id, } html = render_to_string('my_gym/log_form.html', context, request=request) return JsonResponse({'form': html}) else: print("The errors in addlog:",form.errors.as_data()) else: print("What happened??") return HttpResponseRedirect(url) Here is the form: <form class="review-form" action="{% url 'my_gym:addlog' object.id %}" method="post"> {% csrf_token %} </form> Here is the script: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click','#submitlog', function(event){ event.preventDefault(); var log_workout = $('#id_log_workout').val(); $.ajax({ type:'POST', url:'{% url 'my_gym:addlog' object.id %}', data:{'log_workout' : log_workout, csrfmiddlewaretoken':'{{csrf_token}}'}, dataType:'json', success:function(response){ $('#log_form').html(response['form']), console.log($('#log_form').html(response['form','div'])); }, error:function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> Here is the url: path('workout/addlog/<int:id>', addlog, name='addlog'), My question How can I fix this error knowing that I tried changing the workout.id to object.id still same error. -
CSRF Failed | CSRF cookie not set
I'm using class based views to render a template. In that same class, I also have a post request to allow for the submission of a form. However, when I submit the form, I get the CSRF cookie not set error. I did use the {% csrf_token %} but still doesn't work. Here is my code: class SignIn(View): def get(self, request): # email = request.POST['email'] # password = request.POST['password'] template = loader.get_template('signin.html') logging.info(request) return HttpResponse(template.render()) def post(self, request): email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] template = loader.get_template('signin.html') logging.info(request.__dict__) logging.info(password1) logging.info(email) if User.objects.filter(email=email).exists(): messages.info(request, 'E-mail Exists!') return redirect('signup') elif password1 != password2: messages.info(request, 'PASSWORD DOESNT MATCH') return redirect('signup') new_user = User.objects.create_user(email, email, password1) return HttpResponse(template.render()) This is my template: <html> <div> <p> Signup </p> <form method = "POST" action="/signup"> {% csrf_token %} username: <br/> <input type="text" name="email" /> <br/> Password: <br/> <input type="password" name="password1" /> <br/> confirm Password: <br/> <input type="password" name="password2" /> <br/> <input class ="btn btn-primary" type="submit" value= "signup" /> <br/> </form> </div> </html> My urls.py: from django import views from django.urls import path from .views import SignUp, SignIn, Index urlpatterns = [ path('', Index.as_view(), name='Index'), path('signup', SignUp.as_view(), name='SignUp'), path('signin/', SignIn.as_view(), name='SignIn') ] -
Django : FieldError at /editstu/121
Error : Cannot resolve keyword 'id' into field. Choices are: Age, Course_ID, DoB, Grade, Student_ID, Student_Name My function in views.py def Editstu(request,id): editstuobj = Student.objects.get(id=id) return render(request, 'editstu.html',{'Student':editstuobj}) My urls.py urlpatterns = [ path("admin/", admin.site.urls), path('',views.showStudent), path('InsertStudent',views.InsertStudent,name="InsertStudent"), path('Insertcour',views.InsertCourse,name="InsertCourse"), path('editstu/<int:id>',views.Editstu,name="Editstu"), path('editcour/<int:id>',views.Editcour,name="Editcour"), # path('Update/<int:id>',views.updateemp,name="updateemp"), path('Deletestu/<int:id>',views.Deletestu,name="Deletestu"), path('Deletecourse/<int:id>',views.Deletecourse,name="Deletecourse"), ] My Index.html <td><a href="editstu/{{result.Student_ID}}">Edit</a></td> <td><a href="Deletestu/{{result.Student_ID}}" onclick="return confirm ('Are you sure to delete the record?')">Delete</a></td> I checked the function if it is declared properly but no luck. I'm new to Django. It says error is 'id' but it should be fine. Please help if anyone can. -
'node with name "rabbit" is already running on host' even after killing the processes
Whenever I try to run a rabbit server, it meets me with this error: ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" I've read that I should kill the processes of rabbit by using rabbitmqctl stop But I still get the error, What else can I do I am on windows 10 Here is my full error 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> BOOT FAILED 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> =========== 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> BOOT FAILED =========== ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> supervisor: {local,rabbit_prelaunch_sup} 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> errorContext: start_error 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> reason: {duplicate_node_name,"rabbit","DESKTOP-BKRTA3R"} 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> offender: [{pid,undefined}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {id,prelaunch}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {mfargs,{rabbit_prelaunch,run_prelaunch_first_phase,[]}}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {restart_type,transient}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {significant,false}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {shutdown,5000}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {child_type,worker}] 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> crasher: 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> initial call: application_master:init/4 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> pid: <0.129.0> 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> registered_name: [] 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> exception exit: {{shutdown, 2022-11-11 16:46:04.017000-08:00 [error] … -
Python Django: getting data from modal gives <built-in function id> error
I'm trying to get a value from a modal, that gets the value using jQuery from a list. Let's explain. I have a list of objects in an HTML page using a for loop, and in each row, there is a delete button. This delete button launches a confirmation Modal. To get the id of the row and use it in the Modal, I use jQuery: {% for a in objects %} [...] <td><button type="button" class="delete-button" data-name="{{ a.id }}" data-bs-toggle="modal" data-bs-target="#deleteModal">Delete</button></td> [...] {% endfor %} [...] <div class="modal fade" id="deleteModal"> [...] <form action="{% url 'delete_object' %}" method="post"> {% csrf_token %} <input type="hidden" name="object_id" name="object_field" /> <button type="submit">Delete</button> [...] <script> $('.delete-button').click(function() { $('#object_id').html($(this).data('name')) }) </script> Without explaining the urls.py part, let's get straight to the view, which is quite simple: def cancel_request(request): _id = request.POST.get("object_id") obj = Object.objects.get(id=id) obj.status = "Annulé" obj.save() return redirect("home") When I run the modal, I make sure I can see the id value getting in the modal, but when I try to put it in an input, I cannot see it anymore. If I put it in an h5 tag for example: <h5 class="modal-title" id="request_id" name="requestid_kw"></h5>, it shows on the modal, but still does not get …