Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to use the variable in django
i recently started my django course online nad getting some problem. i am not able to use my variable which i passed from index.html to about.html. but in about.html it is not shown up. .py file code : from django .http import HttpResponse from django.shortcuts import render def index(request): return render(request , 'index.html') def about(request): t1 = print(request.GET.get('text' , 'default')) return render(request , 'about.html' , t1) index.html file code: <!DOCTYPE html> <html> <head> <title>template</title> </head> <body> <h1> hello everyone </h1> <form action="/about" , method="get"> <textarea name="text" style="margin: 0px; width: 1245px; height: 171px;"></textarea> <input type="submit" name="OK"> </form> </body> </html> about.html file code : <!DOCTYPE html> <html> <head> <title>template</title> </head> <body> <h1>you typed {{t1}}</h1> </form> </body> </html> -
Django How do I edit a comment
how do I edit an existing comment, when a user comment on a post that user can be able to edit his/her comment. class Comments(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) commented_image = models.ForeignKey(Image,....) comment_post = models.TextField() ....... def comments(request, id): post = get_object_or_404(Image) if request.method == 'POST': form = CommentForm(request.POST) if form.is_form(): comment = form.save(commit=False) comment.user = request.user comment.commented_image = post comment.save() return redirect..... <form method="POST"> {% csrf_token %} <textarea name="comment_post" placeholder="Add comment" id="I'd comment_post"></textarea> <input type="submit" value="POST"> </form> -
django runserver issue on first start
Using Django 3.0 via Pycharm. After starting first time runserver I get the following errors. Would anyone know? The project is completely empty. So far only "startproject" and "runserver" was done. The runserver starts but as soon as I open the link to see in in the browser I get the following meesage? You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. April 02, 2020 - 21:37:53 Django version 3.0.3, using settings 'django_devel_app.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [02/Apr/2020 21:37:56] "GET / HTTP/1.1" 200 16351 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 64833) Traceback (most recent call last): File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\BJS\anaconda3\envs\djangoproject\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 ---------------------------------------- Not Found: /favicon.ico [02/Apr/2020 21:37:57] "GET /favicon.ico HTTP/1.1" 404 1982 ---------------------------------------- … -
Not Redirect after submission the Django Forms
hi dear all of genious Django Expert . i am newbe in django . i having an issue for my form submission . my form is not redirect after click submit . my issue is below <h1> this is views.py page <h1> from django.shortcuts import render, redirect from crud.models import Userlist from crud.forms import UserListForm # Create your views here. def addforms(request): if request.method == "POST": form = UserListForm(request.POST) if form.is_valid(): try: form.save() return redirect() except: pass else: form = UserListForm() return render(request, 'crud/index.html', {'form': form}) def show(request): user9 = Userlist.objects.all() return render(request, 'crud/show.html', {'user': user9}) def index(request): return render(request, 'crud/index.html') -
Restricting access to Django webapp with Stripe?
I'm trying to build a B2B SaaS application where the customer can sign up and invite their respective employees. What options do I have to make sure a customer does not get more access than the amount of licenses they paid for? (Eg, if they pay for 2 licenses, only 2 users should be allowed to use the system) What are some best practices? -
Django: Is there any way to copy a form in the admin to a user-facing page?
https://github.com/mikejohnsonjr/django-powerdns-manager ^ I want to copy the form for adding and editing and deleting new zones. It's a bit counter-intuitive. For example, importing any zone form (like NsRecordModelForm or ARecordModelForm) on a user-facing page will result in being able to add any record (with no styles), rather than a specific type of record. https://github.com/mikejohnsonjr/django-powerdns-manager/blob/master/src/powerdns_manager/admin.py Here is the ugly (no styles) anyzone-ModelForm form: https://i.imgur.com/F6Zcs10.png And here is the admin interface for performing CRUD operations on zones: https://i.imgur.com/5LReNsq.png Can anyone help? Thanks in advance. -
ModuleNotFoundError: No module named 'paypal'
I'm using, Python: 3.8, Django: 3.0, django-paypal: 1.0.0 I'm trying to implement a simple Payment Gateway using Django-Paypal lib. And I'm getting this error during the migration..... (project-venv) PS J:\jaimin (E)\Programming Practice\Django\Payment Gateway using Paypal\simple_ecommerce\django_project> py -3 .\manage.py migrate Traceback (most recent call last): File ".\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'paypal' And here is my settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ecommerce_app', 'paypal.standard.ipn', ] What can I do Now?..... -
AttributeError at /update/ 'Personas' object has no attribute 'is_valid'
I have in models from django.db import models # Create your models here. class Personas(models.Model): Nombre = models.CharField(max_length=50) Apellido = models.CharField(max_length=50) Cedula = models.IntegerField() Direccion = models.CharField(max_length=30) Colegio_Electoral = models.IntegerField() Centro_De_Votacion = models.CharField(max_length=50) Sexo = models.CharField(max_length=13) Telefono = models.CharField(max_length=30) Email = models.EmailField(max_length=50) Edad = models.IntegerField() Sector = models.CharField(max_length=50) def __str__(self): return self.Nombre + " " + (self.Apellido) and views def update(request): if request.method == 'POST': form = Personas(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('formulario.html') else: form = Personas() return render(request, 'formulario.html', { 'form':form }) -
NoReverseMatch exception when creating integration test for REST API with Python Django
I've created a REST API accepting a POST request in Django. The request itself works great when calling from a React front end, there should be nothing wrong with the API itself. I want to create integration test for the API. I've written the below test, which is basically copy/paste from the Django Documentation adapted to my API: from django.urls import reverse, path from rest_framework import status from rest_framework.test import APITestCase class SendLoginEmailTest(APITestCase): def test_post_withValidData_loginEmailIsSent(self): url = reverse('send_login_email') data = {'email': 'validemail@email.com', 'token': '4d4ca980-cb0c-425d-8d2c-7e38cb33f38e'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) I run the test using the command: python3 manage.py test The test fails with the following exception: django.urls.exceptions.NoReverseMatch: Reverse for 'send_login_email' not found. 'send_login_email' is not a valid view function or pattern name. Any ideas what I'm doing wrong? -
Django how to convert FileField & DateTime field to JsonResponse?
I am finally making progress converting some things over to create some api endpoints, with an already existing web app. I have a BuyerForm, and on POST request, everything validates besides the model fields with a DateTime field and FileField. Can anybody assist me with converting that data to a JSON response? if request.method == 'POST': form = BuyerForm(data=json.loads(request.body)) if form.is_valid(): form.save(commit=False) form.buyer = request.user form.disclosures = request.FILES['disclosures'] form.save() data = form.cleaned_data return JsonResponse(data, safe=False) else: data = form.errors.as_json() return JsonResponse(data, status=400, safe=False)``` -
django unique filename extra argument
I want to make my file names unique to prevent collide. image = models.ImageField(upload_to=unique_string_generator, unique=True, blank=True) this is my field. def unique_string_generator(instance: any, filename: str, *, path: str) -> str: """ :param instance: Instance to pass :param filename: filename of the uploaded file :param path: path where to upload :return: where the file will be uploaded """ extension = filename.split('.')[-1] unique_value = uuid.uuid4() filename = f'{unique_value}-{instance.pk}.{extension}' return os.path.join(path, filename) This is my function, how can I pass path='somewhere' to field, because django takes my function as an arguement. A small question, what should be passed for annotation django instance? I just passed instance: any because I couldn't figure out what to annotate? Thanks in advance! -
Django Loop through imputed text from a form
I have the below Django code and I want to be able to loop through the inputted text for name however I do not know the best way to do this. For example in python I have done this by setting the input value as variable and then I can loop through that variable. Is it possible to do that on Django too. Python Code: name = input("Enter name: ").lower() for letter in name: Django HTML code: <form method="post" class="container text-center"> {% csrf_token %} <div> <label for="name">Enter Your Name: </label> <input id ="name" type="text" name='text'> <input type="submit" name="Submit"> </div> </form> <p> {% for letter in "name" %} {% endfor %} <p/> -
launching a django project from a github on my computer with help of visual studio
I have a question about launching a project from a github on my computer. I downloaded this project: https://github.com/justdjango/django-ecommerce Using Visual Studio, first created a new project from existing code, then added the environment (according to the requirements file). But when I start the server, such an error is issued. enter image description here Please tell me what I'm doing wrong. Or the github code itself is not working -
How to deploy simple chatbot (in python,anaconda) in django website?
*enter code here* List itementer link description here -
Queryset - How find a word in foreign key in django?
How find a word in a foreign key? There are classes: class Customers(models.Model): customer = models.CharField(max_length=255, unique=True) order = models.ForeignKey('Order') class Orders(models.Model): orderName = models.CharField(max_length=255) There are these records in Customer and order tables: Order: +-----+------------------+ | id | orderName | +-----+------------------+ | 1 | Apple juice | +-----+------------------+ | 2 | Apple pie | +-----+------------------+ | 3 | Banana juice | +-----+------------------+ | 4 | Banana pie | +-----+------------------+ | 5 | Apple ice cream | +-----+------------------+ | ... | ... | +-----+------------------+ Customer: +-----+----------+-------+ | id | Customer | Order | +-----+----------+-------+ | 1 | A | 2 | +-----+----------+-------+ | 2 | B | 3 | +-----+----------+-------+ | 3 | C | 2 | +-----+----------+-------+ | 4 | G | 1 | +-----+----------+-------+ | 5 | H | 1 | +-----+----------+-------+ | ... | ... | ... | +-----+----------+-------+ I want to get all the records in the customer table that their orders consist of "Apple". I wrote these codes: all_apple_orders = Customer.objects.filter(order='Apple') I got an error message: Field expected a number but got 'Apple'. How should change the code? -
Tempus Datepicker Small Widget Background
I've installed Tempus Dominus Datepicker. But i have problem with the background being too narrow I've search the internets and found that this is supposed to help .bootstrap-datetimepicker-widget.dropdown-menu { width: auto !important; } But i don't understand where to put it (i've only been coding for two weaks). Models class Order(models.Model): timerep = models.FloatField(blank=True, null=True,) Forms class RepairForm(forms.ModelForm): repdate = forms.DateField(widget=DatePicker()) Template {% load bootstrap3 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title></title> {% bootstrap_css %} {% bootstrap_javascript %} {% load static %} {# Include FontAwesome; required for icon display #} <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css"> {# Include Bootstrap 4 and jQuery #} <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> {# Django Tempus Dominus assets are included in `{{ form.media }}` #} {{ form.media }} </head> <body> <form action="{% url 'mtn:edit_order' order.id %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name="submit" role="button" class="btn btn-primary btn-sm">Save Changes</button> </form> How exactly can i change this argument? Or is there another way to fix it? -
Django OneToMany relation on existing database
I'm working on a legacy database constructing an API, and I need to create some respect some hierarchy that is already in place. The API is meant to be read only, so I'm trying to avoid creating any new table in this cenario. There's a table called regionsubregion that has the idregion and idsubregion I need for creating the relation between Region and SubRegion . I was doing simple ForeingKeys like so: class Region(BaseModel): id_region = models.IntegerField(primary_key=True, db_column="idregion") name = models.CharField(verbose_name="Nome", db_column="description", max_length=80) uf = models.CharField( verbose_name="Unidade Federal", db_column="ufe_sg", max_length=2 ) class SubRegion(BaseModel): id_subregion = models.IntegerField(primary_key=True,db_column='idsubregion') region = models.ForeignKey( "Region", on_delete=models.DO_NOTHING, related_name="subregions" ) name = models.CharField(verbose_name="Nome", db_column="description", max_length=80) The Tables in question are region and subregion. But subregion table has no data related to the id of its parent region, this information is contained in the table regionsubregion, like so: idregion idsubregion 8 3 8 10 8 26 9 23 9 28 9 41 9 8 10 18 Before there was a Many to Many relation between those two, but now it is only 1-to-N (One Region has many Subregions, One subregion is bound to one region only). Since the relation information is in an entirely different table and I'm … -
Upload video on website and keep it secured ? (Django)
For the school project I've been working on, the client asked for video uploading, but due to privacy, they wanted to secure the video to be shown only for signed users. I made the page to be secured, but uploading video was a bit of problem. I was thinking about youtube prvacy enhanced mode, but because various users will be uploading, this wasn't a good way to do. So, I was wondering, Can server / host or webpage handle the size of the videos uploaded by users ? Would html5 video tag be ok for this? Would there be any other good option in this case ? -
Why I am getting pylint error in Django blog? How to solve this issue? Installed pylint. Using VSC Mac
I am a beginner in Django, I am trying to build a basic app by referring a tutorial, after completed the code, getting lots of error related to pylint. Please help me to resolve this issue. Thank you.These are the error -
Why the "?page=" doesn't work after I added the pagination to my django website?
I followed the django documentation and I added the pagination and everything looks fine. Here is how it looks how the pagination looks like. And here is my urls.py file: urlpatterns = [ path('', views.home, name='home'), path('new_search', views.new_search, name='new_search'), ] And here is what I got when I click to the next page or any link in the pagination: IntegrityError at /new_search NOT NULL constraint failed: global_store_app_search.search Request Method: GET Request URL: http://127.0.0.1:8000/new_search?page=2 Django Version: 2.1.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: global_store_app_search.search Exception Location: /home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 296 Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/ubuntu/Desktop/TunisiaGlobalStoreDjango/global_store_project', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/ubuntu/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Thu, 2 Apr 2020 18:08:59 +0000 -
How to upload multiple image in django 3?
i want to upload multiple image using django 3. Here My, **Model:** class Image(models.Model): file = models.ImageField(upload_to='images/') **form:** class UploadForm(forms.Form): images = MultiImageField(min_num=1, max_num=3, max_file_size=1024*1024*5) **Views:** class UploadView(FormView): template_name = 'html/form.html' form_class = UploadForm success_url = '/done/' def form_valid(self, form): for each in form.cleaned_data['images']: Image.objects.create(file=each) return super(UploadView, self).form_valid(form) **urls.py:** path('upload', views.UploadView.as_view(), name="upload"), **Finally form.html:** <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Send" /> </form> But i get error: AttributeError at /upload 'list' object has no attribute 'name' -
Django Role Based Authentication based on Permission on URL instead of Permission on model class
I have studied abut Django Authorization. My observation is basically Django Authentication module works fine for Authorization based on role-based Authentication based on Permission on a Model instance. But In Spring framework I found here same role-based Authentication based on Permission on URL or actually relative URL or URL pattern here like .antMatchers("/user/**").hasRoles("USER", "ADMIN") in following code snippet. Here is a code snippet of Spring Framework: @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/static","/register").permitAll() .antMatchers("/user/**").hasRoles("USER", "ADMIN") // can pass multiple roles .antMatchers("/admin/**").access("hasRole('ADMIN') and hasIpAddress('123.123.123.123')") // pass SPEL using access method .anyRequest().authenticated() .and() .formLogin() .loginUrl("/login") .permitAll(); }``` Is there any way or library in Django Similar way of Spring for Authorization based on Permission on URL? Thanks. -
Django Local Font
I can't connect fonts stored in the static/fonts folder. The path itself django as far as I understand sees, but the font is not loaded on the site static/css/main.css: .container { -webkit-box-sizing: border-box; box-sizing: border-box; font-family: url("../fonts/font-light.ttf"); } -
How to add 'Jinja' extension in Pycharm?
I am trying to install jinja extension in pycharm but somehow I am not able to find it in the pycharm marketplace. Can anyone please help me add 'Jinja' extension in pycharm? Thanks -
Django AssertionError: `update()` did not return an object instance
I want to update my model's deleted field. It's a boolean field. I searched on google and stackoverflow but couldn't find an issue with the same error, strange.. Here is my code: probably my serializer is not working, but I can't find where.. Thanks for your help Django keeps saying: AssertionError: `update()` did not return an object instance. this is my test class: def test_delete_device(self): self.client.force_login(self.admin_user) url = reverse( "admin-device-change-status", kwargs={"device_pk": self.undeleted_device.id} ) response = self.client.patch(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["deleted"], True) view: class AdminDeletedDeviceView(GenericAPIView): pagination_class = StandardPagination def get_permissions(self): return IsAuthenticated(), IsAdminUser() def get_serializer_class(self): return AdminDeviceChangeStatusSerializer @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully undeleted the device"), AdminSiteSerializer, ) } ) def patch(self, request, device_pk): """ Undelete device """ device = get_object_or_404(Device, pk=device_pk) serializer_class = self.get_serializer_class() serializer = serializer_class(device, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() if device.deleted == False: device.deleted = True else: device.deleted = False device.save() return Response(serializer.data, status=status.HTTP_200_OK) serializer: class AdminDeviceChangeStatusSerializer(serializers.Serializer): # This method is a method that is needed to override an abstract method in the super class. def create(self, validated_data): # pragma: no cover pass # This method is a method needed to override an abstract method in the super class. def update(self, instance, validated_data): # pragma: no cover pass deleted = …