Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to assign task to group in django viewfloe
Im looking for a solution to assign task to group in viewflow I Assigned task to user by .Assign(username='employee') -
How to associate a comment with a parent comment in Django models
I have built an application with comments that are commented on a parent comment. I have the following comment model. How can I associate the comment with a parent comment ? class Comment(models.Model): uuid = models.UUIDField(max_length=255, default = uuid.uuid4) description = models.CharField(max_length=5000, default="") likes = models.PositiveIntegerField(default=0) dislikes = models.PositiveIntegerField(default=0) uploaded_at = models.DateTimeField(null=True, blank=True) commentinguser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) video = models.ForeignKey(Video, on_delete=models.CASCADE) -
Encrypt the uploaded file and then store it
I am trying to encrypt the user uploaded file and then save them to the machine. but i am getting error , Its mainly because my code for algorithm looks for file in given path, but here the uploaded file is in upload memory so any ideas to directly encrypt file and then store it. Request Method: POST Request URL: http://127.0.0.1:8000/user/UploadToCloud/ Django Version: 3.0.6 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'admins', 'user', 'login'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\PMD\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\PMD\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\PMD\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Programming\python\Django\CryptoCloud\user\views.py", line 78, in UploadToCloud if(Aes.encrypt_file(file_temp,'out.enc')): File "E:\Programming\python\Django\CryptoCloud\user\algorithms.py", line 64, in encrypt_file file_size = os.path.getsize(in_file_name) File "C:\Users\PMD\AppData\Local\Programs\Python\Python37\lib\genericpath.py", line 50, in getsize return os.stat(filename).st_size Exception Type: TypeError at /user/UploadToCloud/ Exception Value: stat: path should be string, bytes, os.PathLike or integer, not _TemporaryFileWrapper here is my code: ///// view.py ///// def UploadToCloud(request): if request.method == "POST": print('POST Method Works Fine') usremail = request.session['email'] form = UserFileUploadForm(request.POST, request.FILES) if form.is_valid(): print(form.cleaned_data['algorithms']) ipfile = form.cleaned_data['userfile'] # accesskey = form.cleaned_data['accesskey'] accesskey = … -
vendors.min.js:2 Uncaught RangeError: Maximum call stack size exceeded using AJAX with django
I'm trying to make an ajax request in the Django project, using Django Ajax, here is my code : the HTML code where the call is made function addRecipe() { const recipeSize = document.getElementById('recipeSize'); const recipeItem = document.getElementById('autocomplete-input'); const recipeQuantity = document.getElementById('recipeQuantity'); alert(recipeSize.value); alert(recipeItem.value); alert(recipeQuantity.value); $.ajax({ url: "{% url 'add_recipe_item' %}", data: { 'the_size_id': recipeSize, }, dataType: 'json', success: function (data) { console.log(data); } }); } URL.py path('ajax/add/recipe/item/', products_views.add_recipe_item, name="add_recipe_item"), views.py @ajax def add_recipe_item(request): size = get_object_or_404(Size, id=request.GET.get('the_size_id')) print(size.name) data = { 'the_size': size.name, } return data When I run the function in HTML, It gives back this error after lagging for a few seconds vendors.min.js:2 Uncaught RangeError: Maximum call stack size exceeded -
Django - How to create multiple users for a single app
myproject ---myapp I have created a django project which has an app in it that does viewing , adding data to database etc. Now I want to create multiple users who can use this app with their own data. What is the best way about it. Lets say there are 3 users user1, user2, user3 Currently I am planning to do this. I copy the myapp code and create 3 apps corresponding to each user. So the project directory looks something like this myproject ---myapp ---myappuser1 ---myappuser2 ---myappuser3 So I now have 3 apps with similar functionality and each of the user has their own data. Now, the hurdle is how do I restrict access so that each user can see his own app. For instance, user1 should be able to only see myappuser1 contents and user2 should only see myappuser2 contents. How can I do this ? I tried creating groups in django admin but that only gives me permissions to edit the items under the myapp. It doesn't restrict user to not allow other user pages. Option 2: Create seperate django project for each user. This solves the user restriction but to deploy in heroku I should register … -
list object has no attribute "values"
In Django, this is my code and it is working fine. from myapp.models import Users user = Users.filter(organization ="abc").order_by("-created_at")[offset:offset+limit] user.values("id") But when I try to break the code into smaller parts, it throws an error on the third line saying: attribute error: list object has no attribute "values" from myapp.models import Users user = Users.filter(organization ="abc").order_by("-created_at") user = user[offset:offset+limit] user.values("id") I was just wondering why it is happening? -
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 …