Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Use a String as ForeignKey
I have a quick conceptual question that I would like to solve. I have a model that upon saving an instance of that model, saves the id as an md5 hash (ex. '11db608cba69c0a09b4d5abde2553b56'). Saving this model works fine, but now I am trying to save additional information by creating a new model that references this model as a foreign key. Upon saving that additional model I get the following error: invalid literal for int() with base 10: '11db608cba69c0a09b4d5abde2553b56'. Doing some searching I found a nice stack post that answers what I believe to be happening. It said that by default, a ForeignKey field is of type integer. Therefore whatever value is referenced by it must be an integer. I would like to be able to define a model that uses a str-based foreign key (or anything that will allow it to except the md5 hash). Is that solution possible? The only other thing I could think of doing is generating an integer based on the md5 and using that as a reference, but it seems like an unnecessary step. I also found some other posts that referenced GenericForeignKey. I'm having a bit of trouble wrapping my head around it, but … -
How to implement Giphy into blog post comments in Django?
I would like to offer the option to insert Gifs via the Giphy API into blog post comments for my readers. I have a plain vanilla comment form + model like so: forms.py # Blog Post Comment Form class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'text',) models.py # Comment Model class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=True) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text Now I am stuck when it comes to the basic concept of how I could implement the Giphy API into the form/model instances. My idea is to make an async Ajax call to the Giphy API endpoint once the user entered a search term. Then the API would return a bunch of gifs and the user selects one. I guess that the Django Textfield isn't capable for this purpose. Now how to insert the selected gif into the comment and save it to the database? -
Serve files using nginx in django for logged in users
I'd like Django to serve some media files (e.g. user-uploaded files) only for logged-in users only. Can someone please provide me with some resource or help. I found the below link but I am new to Nginx, Django and require to set this up in urgent basis. Serving protected files NGINX and Django -
AWS Elastic Beanstalk failed to install Python package using requirements.txt - Firebase-Admin
I have searched similar questions, but no answers solve my problem. I am trying to install firebase-admin using pip. Everything works well locally, but when I push to aws elastic beanstalk it gives me the error below When I remove firebase-admin and its dependencies everything works fine. I think it may specifically have an error with grpcio being installed but not completely sure, and firebase needs it installed to work. Some answers say that firebase-admin is dynamic and aws else does not support that. I am wondering if there is a solution to this problem so I can install firebase. Thank you 2020-06-21 04:13:35 INFO Environment update is starting. 2020-06-21 04:13:40 INFO Deploying new version to instance(s). 2020-06-21 04:13:51 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2020-06-21 04:13:55 ERROR [Instance: i-06c2884999a9d6064] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2020-06-21 04:13:55 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. -
<News:somethinng>" needs to have a value for field "id" before this many-to-many relationship can be used
Here from my template I am getting the list of strings with getlist in a view. I want to assign these list in my ManyToMany field.I am getting the selected multiple list in my view and it is also creating the reporter object from these list which is fine. Now I want to assign these only selected multiple options in my many to many field. How can I do it here? I get this error while saving the form "<News:somethinng>" needs to have a value for field "id" before this many-to-many relationship can be used. views class NewsCreateVView(View): template_name = 'add_news.html' def get(self, request): form = CreateNewsForm() return render(request, self.template_name, {'form': form}) def post(self, request, **kwargs): form = CreateNewsForm(request.POST) reporters = request.POST.getlist('reporter') if form.is_valid(): news = form.save(commit=False) for reporter in reporters: obj = Reporter.objects.create(name=reporter) news.reporter.add(obj.pk) news.save() return redirect('list_news') models class Reporter(models.Model): name = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) class News(models.Model): title = models.CharField(max_length=255) reporter = models.ManyToManyField(Reporter, related_name='reporters') template <select class="form-control" name="reporter" multiple="multiple"> -
Cannot assign "'nimaaram'": "Food.user" must be a "User" instance in Django
I have a Food Model just like this: class Food(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=155,default='') colorie = models.BigIntegerField(default=0) carbohidrat = models.IntegerField(default=0) cholestrol = models.IntegerField(default=0) fat = models.IntegerField(default=0) fiber = models.IntegerField(default=0) protein = models.IntegerField(default=0) saturatedfat = models.IntegerField(default=0) def __str__(self): return self.name and i have food form just like this: class addFood(forms.Form): name = forms.CharField(max_length=40,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام غذا'})) colorie = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'میزان انرژی بر حسب کیلو کالری'})) carbohidrat = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'میزان کربوهیدرات بر حسب گرم'})) cholestrol = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'میزان کلسترول بر حسب میلی گرم'})) fat = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'میزان چربی بر حسب گرم'})) fiber = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'میزان فیبر بر حسب گرم'})) protein = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'میزان پروتئین بر حسب گرم'})) saturatedfat = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'میزان چربی اشباع شده بر حسب گرم'})) def save(self,request): data = self.cleaned_data food = Food(user=request.user.username,name=data['name'],colorie=data['colorie'],carbohidrat=data['carbohidrat'],cholestrol=data['cholestrol'],fat=data['fat'],fiber=data['fiber'],protein=data['protein'],saturatedfat=data['saturatedfat']) food.save() class Meta: model = Food and Views.py: @login_required def addfood(request): if request.method == 'POST': form = addFood(request.POST) if form.is_valid(): form.save(request) return redirect('food:index') else: form = addFood() return render(request,'addfood.html',{'form':form}) when i fill out form and press submit django give me 'Cannot assign "'nimaaram'": "Food.user" must be a "User" instance' error. what should i do to fix it? tip : request.user.username in food form is "'nimaaram'" how i can save my form in another way? i need user in food model fill out automatically(username) -
django ckeditor set with different s3 bucket
I'm implementing ckeditor with my django app, the problem I have is: Django-ckeditor doesn't work with s3 buckets that are not public. I need the s3 bucket to be private to prevent abuse. My thoughts are setting the django-ckeditor upload to a different s3 bucket and setting it as public. I want to know if that is possible as that isn't documented by django-ckeditor. If I set the s3 bucket to be public, will people be able to upload files outside my sites (does setting it public ignores CORS settings)? If the above thought is incorrect, is there an alternative way of doing it without affecting my main media storage?, or an alternative package for rich text editor. Thanks in advance. -
Use entire set of views in two different URL confs in Django
I'm building a web app that displays TV Shows and Episodes. All my urls are geared towards TV Shows being the top level concept: mysite.com/tv-show-name/episode-name mysite.com/tv-show-name/episode-name/cast mysite.com/tv-show-name/episode-name/reviews I've gotten interest from Networks for consolidated pages with their shows as subdirectories mysite.com/network-name/tv-show-name/episode-name mysite.com/network-name/tv-show-name/episode-name/cast mysite.com/network-name/tv-show-name/episode-name/reviews I'll need to support both, and obviously I dont want to repeat all my non-network URL confs. Is there a simple way to do this? -
Why am I getting this django connection aborted error
I am getting the following error only for 10 digit phonenumber entries. Program works fine for 9 or less digits. Could this be a memory overflow issue? If so, How can I increase the allocated memory by a factor of 3? Thanks. [21/Jun/2020 11:49:56] "POST /? HTTP/1.1" 200 414816 the request <WSGIRequest: POST '/'> in funct phonenumber retrieved = 1234567890 just a test of list(phonenumber): ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] isDigit true for 1234567890 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 64996) [21/Jun/2020 11:50:02] "GET /? HTTP/1.1" 200 1464 Traceback (most recent call last): File "d:\python\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "d:\python\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "d:\python\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\dougl\Envs\my_django_environment\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\dougl\Envs\my_django_environment\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "d:\python\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
Error when loading pinax message template
I installed pinax-messages to my project and I'm getting an error when I try to load one of the templates: {# This template intentionally left blank to satisfy test suites. Your project should always provide a site_base.html itself. #} I installed the message templates from pinax-templates to the following project directory but it doesn't seem like it's recognizing it: testproject\eventsapp\templates\pinax\messages This folder contains files base.html as well as others such as inbox.html. Where do I need to install these files? Thanks! -
Django model attribute and database field with different name in model
I have a database table called Person contains following columns: Id, first_name, last_name, So is there any way to assign different name to table fields in django model. like this class Person(models.Model): firstname = models.CharField(max_length = 30) lastname = models.CharField(max_length = 30) firstname instead of first_name and lastname instead of last_name -
Controlling duplicate entries with Django
Django offers the possibility to use the * exists * function which returns a boolean a = Predicates.objects.filter(predicate = predicate).exists() print (a) True I need to occupy the ID (PK) of that record if it exists so I use get try: return Predicates.objects.get(predicate = predicate) except Predicates.DoesNotExist as errorNoExiste: return None That code in a function exists = self.search_predicate (predicate) now on reaching the conditional if exists is None: if or if you enter and proceed to save, which produces a Duplicate Entry in the model the attribute is obviously unique. Any ideas as I said I need the ID of the record if there is to make another record and why this ID is your FK (instance). -
Django Rest Framework : get_queryset returns 'detail': 'Not found'
Hi I have API which needs to perform Join table with subquery and return queryset. When I print queryset , it prints a queryset with one object in it, but returns 404 'detail' : 'Not Found' error. I get the customer id in URL, I have to query Customer table to get the corresponding address_id and send the address details of the address_id from Address table. Below are the models class Customer(models.Model): customer_id = models.AutoField(primary_key = True, auto_created = True) first_name = models.CharField(max_length = 45) last_name = models.CharField(max_length = 45) address_id = models.ForeignKey('Address', db_column = 'address_id', on_delete = models.CASCADE) class Address(models.Model): address_id = models.AutoField(primary_key = True) district = models.CharField(max_length = 20 ) postal_code = models.CharField(max_length = 10 , blank=True) phone = models.CharField(max_length = 20) Below is the view class AddressDetail(generics.RetrieveUpdateDestroyAPIView): lookup_url_kwarg = "customer_id" serializer_class = AddressSerializer def get_queryset(self): cust_id = self.kwargs['customer_id'] customer_addr_id = Customer.objects.filter(customer_id = cust_id) return Address.objects.filter(address_id__in=customer_addr_id.values('address_id')) Below is the url path('<int:customer_id>/address',views.AddressDetail.as_view()) Wondering that i could print and see object in query set but getting 'Not found' at client side. Please let me know if I am missing out something. -
ModelForm is not saving any data to database - Django
I'm trying add product to my app using a modelForm. Form is rendering. But after submission its not saving any data to database neither giving any error. pleas find the below codes and help. model class Product(models.Model): product_name = models.CharField(max_length=200) product_category = models.CharField(max_length=50, choices=(('Distemper', 'Distemper'), ('Exterior', 'Exterior '), ('Interior', 'Interior'))) product_image = models.ImageField(upload_to='product_images') product_MRP = models.FloatField() product_size = models.IntegerField() product_packeging = models.CharField(choices=(('KG', 'KG'), ('Liters', 'Liters ')), max_length=10) product_datecreated = models.DateField(auto_now_add=True) def __str__(self): return self.product_name + ' | ' + str(self.product_size) + ' | ' + self.product_packeging form class AddProductForm(ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'product_name': forms.TextInput( attrs={'type': 'list', 'class': "form-control", 'placeholder': "Product name"}), 'product_category': forms.Select( attrs={'type': 'text', 'class': "form-control", 'placeholder': "Category"}), 'product_image': forms.FileInput( attrs={'type': 'file', 'class': "form-control", 'placeholder': "Product Image"}), 'product_MRP': forms.NumberInput( attrs={'type': 'text', 'class': "form-control", 'placeholder': "Product MRP"}), 'product_size': forms.NumberInput( attrs={'type': 'list', 'class': "form-control", 'placeholder': "Product Size"}), 'product_packeging': forms.Select( attrs={'type': 'list', 'class': "form-control", 'placeholder': "Select"}), } template {% block content %} <form style="margin-left: 15px; margin-right: 15px" method="post" action="add_product"> {% csrf_token %} {{ form }} <div class="modal-footer" style="display:flex; justify-content: center"> <button style="text-align: center" type="submit" class="btn btn-info">Create</button> </div> </form> {% endblock %} view def add_product(request): form = AddProductForm() context = {'form': form} if request.method == … -
Django channels zero downtime code update?
I have a django channels based app in production environment. I am using supervisord to manage processes. Also I am using uvicorn via gunicorn to handle asgi requests as mentioned here. Whenever I have something new to deploy, I have to restart gunicorn process and it will destroy all old websocket connections and connect them again. Is there a way to persist those websocket connections. Basically, it puts a sudden load on server as every device tries to reconnect after few seconds of disconnection. There is concept of sending HUP signal Link to gunicorn so that only workers processes restart, but even restarting worker processes disconnects websocket connection. Is there a way to do it without losing old websocket connections? Or if not is there a way to avoid sudden load on server on server restart? Can I do it using some proxy server? -
Nginx will not serve django media files, but will serve static files
I am hosting a django docker container on digital ocean. The container uses nginx to handle django static and media files. I am able to serve static files, but not media files. Any idea on what my problem could be? nginx.conf: upstream ether{ server web:8000; } server { listen 80; location / { proxy_pass http://ether; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 800M; } location /staticfiles/ { alias /home/app/web/staticfiles/; } location /mediafiles/ { alias /home/app/web/mediafiles/; } } To make sure nginx was serving the files, I tried deleting /staticfiles/ from the location, and this caused the server to no longer serve static files. settings.py: STATIC_URL = "/staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = "/mediafiles/" MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles") urls.py: urlpatterns = [] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) docker-compose.yml: version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn ether.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: -
Django invalid literal for int() with save_m2m
I try to integrate vue tags input http://www.vue-tags-input.com/#/ with my project. Autocomplete works fine, form also. When I save the form, everything except the category(tags) is saved. I know that with many to many relationship I have to use save_m2m in view, but when I do this, error appear: invalid literal for int() with base 10: 'e' My view: @login_required def save_embed(request): interests = RecipeCategory.objects.all() if request.method == "POST": form = AddEmbed(request.POST) if form.is_valid(): new_embed = form.save(commit=False) new_embed.added_by = request.user new_embed.save() form.save_m2m() else: form = AddEmbed() return render(request, 'embed/embedadd.html', {'form': form, 'interests': interests}) Model: class Embed(models.Model, Activity): url = models.URLField(max_length=255, verbose_name='Adres przepisu') title = models.CharField(max_length=255, verbose_name='Tytuł') description = models.TextField(verbose_name='Opis', blank=True, null=True) type = models.CharField(blank=True, max_length=200) thumbnail_url = models.URLField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to='recipes', blank=True) html = models.TextField() votes = GenericRelation(LikeDislike, related_query_name='embedlikes') added_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) category = TreeManyToManyField(RecipeCategory, blank=True, null=True, related_name='embeds', verbose_name='Kategoria') slug = AutoSlugField(populate_from='title', unique=True) Traceback: Traceback (most recent call last): File "/data/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/data/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/data/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/app/recipes/views.py", line 39, in … -
Reverse for 'employee-delete' with arguments '('',)' not found. 1 pattern(s) tried: ['employee/employee\\-list/(?P<id>[0-9]+)/delete/$']
I am getting Reverse for 'employee-delete' with arguments '('',)' not found. 1 pattern(s) tried: ['employee/employee\\-list/(?P<id>[0-9]+)/delete/$'] this error when i try to delete an employee. I dont know why this error is giving. I have given correct url path. I want to delete employee from my list table using ajax and jquery. employee_list.html: {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> <div class=""> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Employees</b></h2> </div> <div class="col-sm-6"> <a href="{% url 'employee:employee-add' %}" data-target="exampleModal" class="btn btn-success" data-toggle="modal"> <span ></span> <i class="material-icons"></i> <span data-feather="plus"></span>Add New Employee </a> <!--<a href="#deleteEmployeeModal" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE15C;</i> <span>Delete</span></a>--> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Address</th> <th>Phone</th> <th>Department</th> <th>Designation</th> <th>Actions</th> </tr> </thead> <tbody> <!-- Loop for showing employee list in a table--> {% for employee in employees %} <tr> <td> <span class="custom-checkbox"> <input type="checkbox" id="checkbox1" name="options[]" value="1"> <label for="checkbox1"></label> </span> </td> <td>{{employee.e_id}}</td> <td>{{employee.first_name}}</td> <td>{{employee.last_name}}</td> <td>{{employee.email}}</td> <td>{{employee.address}}</td> <td>{{employee.phone_number}}</td> <td>{{employee.department}}</td> <td>{{employee.designation}}</td> <td> <a href="{% url 'employee:employee-update' employee.id %}" class="edit" data-toggle="modal"> <i class="material-icons" data-toggle="tooltip" title="Edit"></i> <span data-feather="edit-2"></span> </a> <a href="{% url 'employee:employee-delete' employee.id %}" … -
Django query - connect User Class with OnetoOnefield class for Telegram Bot
I am having an issue with querying an attribute from a custom class connected with the user class. My Goal: I want to send messages on my website per mouseclick via telegram bot to my phone (messaging works) - For this I need the USER´S CHAT ID As there are multiple users I stored the chat_id in a new model I created, which is linked to User model with a onetoonefield: User = get_user_model() class TelegramProfile(models.Model): name = models.CharField(default="",max_length=200,blank=True,unique=True) user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="user_id") telegram_chat_id = models.CharField(max_length=40,default="",editable=True,blank=True,unique=True) def __str__(self): return str(self.name) My Usermodel is the built in Model: class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return f"@{self.username}" So in my views.py file I have the function on which I grab the message (another model class called Recipe - I identify it by a primary key) and and the chat_id which belongs to a specific user: def bot(request,msg,chat_id,token=my_token): bot=telegram.Bot(token=token) bot.send_message(chat_id=chat_id, text=msg) def home(request,pk): recipe = get_object_or_404(Recipe,pk=pk) user = request.user chat_id = User.objects.get(TelegramProfile.telegram_chat_id,user) #with this query I try to grab the chat_id of the logged in user ingredients = recipe.ingredients ingredients = ingredients.split("<p>") ingredients = "\n".join(ingredients) ingredients = strip_tags(ingredients) bot(request,ingredients,chat_id) return render(request,"recipes/send_recipe.html") So my question is: -How do I make the query for the chat_id so … -
Invalid interpolation format for "environment" option in service "web": "SECRET_KEY
I'm doing a project online book store on django, when i try to setup environment variable I am facing the problem.My docker-compose.yml file looks like version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - SECRET_KEY=secret_key volumes: - .:/code ports: - 8000:8000 depends_on: - db db: hostname: db image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data environment: - "POSTGRES_HOST_AUTH_METHOD=trust" ports: - "5432:5432" volumes: postgres_data: and my settings.py : SECRET_KEY = os.environ.get('SECRET_KEY') Note That my secret_key doesn't contains "$" sign. Whenever I try to do "docker-console down" it shows error. -
Django - Messages functionality not working in Class based view
Unable to display messages in class based view. In another app's views.py, it is working fine where I used function based view. views.py: class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView): model = Post success_url = '/user-profile/' success_message = "Your post has been deleted sucessfully!" def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False urls.py: path('user-profile/', user_views.user_profile, name='user_profile'), html: {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} -
Reverse url problem: template url is giving reverse error
I am getting this error Reverse for 'video_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['video/(?P[-a-zA-Z0-9_]+)/$']. Please help.. #urls.py urlpatterns = [ path('video/<slug:slug>/', views.VideoDetail.as_view(), name='video_detail'), ] #views.py class VideoDetail(DetailView): model = Video template_name = 'video.html' #HTML <a href="{% url 'video_detail' video.slug %}"> #models.py class Video(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=200, unique=True) year = models.CharField(max_length=4) category = models.CharField(max_length=3) genres = models.CharField(max_length=100) poster = models.URLField(default='') plot = models.CharField(max_length=500) trailer = models.URLField(default='') def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("video.html", kwargs={"slug": str(self.slug)}) #urls.py main site urlpatterns = [ path("admin/", admin.site.urls), path("", include("accounts.urls")), path("", include("blog.urls")), path("", include("video.urls")), ] -
Django AllAuth KeyError at /accounts/signup/ 'sociallogin'
I am using Django All Auth for the first time. I have set up all the urls. I haven't setup any social network provider. The login works, but when I click on the signup it comes up with the exception: KeyError at /accounts/signup/ 'sociallogin' I am also trying to make the Firstname and Last name compulsory on the regular SignUp (not the Social Login). Is my forms.py correct? class CustomUserCreationForm(UserCreationForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') class Meta: model = CustomUser fields = ('email', 'first_name', 'last_name') def save(self, request): user = CustomUserCreationForm(request.POST) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() My All Auth Settings ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 7 ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGOUT_REDIRECT_URL ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 300 ACCOUNT_USERNAME_BLACKLIST = ['admin', 'superuser', 'user'] I didn't change anything in the ACCOUNT_FORMS dictionary. Its the default. Thank you very much. -
How to pass parameters of Ajax URL in Django?
I used Ajax to add items to wishlist: <a href="{% url 'listing:wishlist' list.slug %}" id="wishlistbtn" data-slug='{{ list.slug }}'>Add to wishlist</a> the url looks like: path('wishlist/<slug:title_slug>/', wishlist, name='wishlist'), but I don't know how to pass list.slug or title_slug in above url using Ajax: $(document).on('click', '#wishlistbtn', function (e) { $.ajax({ type: 'GET', url: "{% url 'listing:wishlist' %}", data: { title_slug: e.target.getAttribute('data-slug') }, success: function (response) { alert('added to wishlist') } }) }) my above stated solution didn't work? Please help me with this. Thank you. -
TypeError: Object of type Reporter is not JSON serializable
I am trying to add the reporter with ajax but it is not working properly. When I send json data with {'reporter':reporter.name} then it creates the obj in the database successfully but I am not being able to display this newly created obj in the select option. I have to refresh to see this object in the select option. Then I tried sending the object instance as a JsonResponse by dumping with json.dumps(obj) but I am getting this error serializable error. I have to create the reporter object and display in the select option without page refresh. How can I do it ? What's wrong here in my approach ? view class AddReporterView(View): def post(self, request): name = request.POST.get('name') reporter = Reporter.objects.create(name=name) data = { 'reporter': json.dumps(reporter) } return JsonResponse(data) Scripts $(document).on('submit','#target-category-form',function(e) { e.preventDefault(); var form = $(this); $.ajax({ url: form.attr("action"), data: { name:$('#name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, type: 'POST', dataType:'json', success: handleFormSuccess, }); }); function handleFormSuccess(data){ $("#id-categories").html(data); $('#modalOpen').modal('toggle'); console.log(data); } I want to display the created data here in this html select element <select class="form-control" name="reporter" multiple="multiple" id="id-categories"> {% for reporter in reporters %} <option value="{{reporter.pk}}">{{reporter.name}}</option> {% endfor %} </select>