Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django confirm delete modal
I'm trying to have a modal appear when the user clicks the delete button on a task. The modal has a button with the delete_task_view which takes in the pk of the task. I;m trying to find a way to pass it the pk without creating a modal for every task inside the for loop. template.html <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-lg-6 col-md-12"> <div class="card"> <div class="card-header card-header-success"> Create Task </div> <div class="card-body"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form|crispy}} <button type="submit" class="btn submit-btn mt-3 mr-2"><i class="fa fa-share"></i> Submit</button> </form> </div> </div> </div> <div class="col-lg-6 col-md-12"> <div class="card"> <div class="card-header card-header-success"> Tasks </div> <div class="card-body"> <table class="table"> <tbody> <th>Task</th> <th>Action</th> {% for task in tasks %} <tr> <td>{{task.task}}</td> <td class="td-actions text-right"> <button type="button" rel="tooltip" title="Edit Task" class="btn btn-white btn-link btn-sm"> <i class="material-icons">edit</i> </button> <button type="submit" rel="tooltip" title="Remove" class="btn btn-white btn-link btn-sm" data-toggle="modal" data-target="#exampleModalCenter"> <i class="material-icons">close</i> </button> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Confirm Action</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to … -
Django DRF signal, post_save is not firing
I am having a issue about creating a token. I setup DRF's TokenAuthentication but when I sign up a user signal is not firing. in settings.py INSTALLED_APPS = [ .. 'rest_framework', 'rest_framework.authtoken', .. ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } inside account app, this signals.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): print("fired") if created: Token.objects.create(user=instance) I can save the new user but for new user can't create a token. print("firing") not running as well. What am I missing here? -
Why is my Django search filter not able to find newly created entries?
My Django search filter is able to filter and display search queries for existing entries in my database flawlessly. But if I create a new entry and then search for that entry, I do not get any result. Here is my view - def listUser(request): searchTerm = '' if 'search' in request.GET: searchTerm = request.GET['search'] obj = Employee.objects.first() obj.refresh_from_db() searchTerm = Employee.objects.filter( Q(organization__orgname__icontains=searchTerm) | Q(team__teamName__icontains=searchTerm) | Q(agile_team__agileTeamName__icontains=searchTerm) | Q(name__icontains=searchTerm) | Q(assoc_id__icontains=searchTerm)) result = {'searchTerm': searchTerm} return render(request, 'scrapeComments/listUser.html', result) else: context = {'listUser': Employee.objects.all()} return render(request, 'scrapeComments/listUser.html', context) Here is my template to display the search query - <table class="table table-borderless"> <tbody> {% for user in searchTerm %} <tr> <td>{{user.name}}</td> <td>{{user.assoc_id}}</td> <td>{{user.organization}}</td> <td>{{user.team}}</td> <td>{{user.agile_team}}</td> </tr> {% endfor %} </tbody> Thanks in advance! -
Docker: Multiple Compositions
I've seen many examples of Docker compose and that makes perfect sense to me, but all bundle their frontend and backend as separate containers on the same composition. In my use case I've developed a backend (in Django) and a frontend (in React) for a particular application. However, I want to be able to allow my backend API to be consumed by other client applications down the road, and thus I'd like to isolate them from one another. Essentially, I envision it looking something like this. I would have a docker-compose file for my backend, which would consist of a PostgreSQL container and a webserver (Apache) container with a volume to my source code. Not going to get into implementation details but because containers in the same composition exist on the same network I can refer to the DB in the source code using the alias in the file. That is one environment with 2 containers. On my frontend and any other future client applications that consume the backend, I would have a webserver (Apache) container to serve the compiled static build of the React source. That of course exists in it's own environement, so my question is like how … -
Django Comment Function creates HTTP 405 Error
I tried to create a commenting function for my Django blog application and comments as such work fine but I can only add them through my admin page. However, I would like users to be able to add comments to blog posts. Comment model in models.py: class Comment(models.Model): post = models.ForeignKey('feed.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=500) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.content I tried to add the commenting function with a Class based view in my views.py: class CommentCreateView(CreateView): model = Comment fields = ['content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) In my urls.py I have added the comment path as such that it uses the same path as the blog post, so the users can add comments on the same page and after the comment is posted they are still on the page of the post. urlpatterns = [ path('', login_required(PostListView.as_view()), name='feed-home'), path('user/<str:username>/', login_required(UserPostListView.as_view()), name='user-feed'), # Blog Post View path('post/<int:pk>/', login_required(PostDetailView.as_view()), name='post-detail'), # (NOT WORKING) Comment View path('post/<int:pk>/', login_required(CommentCreateView.as_view()), name='post-detail'), path('post/new/', login_required(PostCreateView.as_view()), name='post-create'), path('post/<int:pk>/update', login_required(PostUpdateView.as_view()), name='post-update'), path('post/<int:pk>/delete', login_required(PostDeleteView.as_view()), name='post-delete'), path('about/', views.about, name='feed-about'), ] For my other forms such as login, register etc. I have used crispy forms and I thought I could … -
Django - How to get that an object attribute be automatically updated depending on the actual date?
I need that an object attribute be automatically updated past some puntual date and time. I have a class and a method within this class to try to perform this, but the issue here is that I need to call the method (or access a @property) to this be applied. The code is something like this: class Foo(models.Model): status = models.CharField() expiring_time = models.DateTimeField() def is_active(self): date = datetime.datetime.now() if date > self.expiring_time: self.status = "expired" self.save() I found some similar questions but none of them seems to get the point that I'm looking for. I heard about celery to perform scheduled tasks, but as I understood this just be keep calling the method and is not the same that I'm looking for. I would like to know if is there a way to keep this method "always active", or what could be a way to achieve this? -
How to upload images or static files in a django project
Ive tried everything. I cannot upload images in my website. How to do that. It just gives an icon of an image not the image itself. When i write {% load static %} in my html5 file which is running bootstrap css stuff it simply displays that on the webpage. it takes this command as text. Also ive tried to shift the whole iconic folder i downloaded to static directory but py manage.py collectstatic showed 0 files , 130 unmodified.enter image description here -
django Pagination in ListView
How do i create pagination in Django ListView? and i just want that per page have 5 records only this is my views.py def list(request): user_list = StudentsEnrollmentRecord.objects.all() page = request.GET.get('page', 1) paginator = Paginator(user_list, 10) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'Homepage/search_and_page.html', {'users': users}) class ArticleListView(ListView): model = StudentsEnrollmentRecord page = 5 # if pagination is desired template_name = 'Homepage/studentsenrollmentrecord.html' searchable_fields = ["Student_Users", "id", "Section"] user_list = StudentsEnrollmentRecord.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return(context) and this is my html search_and_page.html <table id="customers"> <tr> <th>Username</th> <th>Firstname</th> <th>Email</th> </tr> {% for article in object_list %} <tr id="myAnchor"> <td class="grpTextBox">{{ article.username }}</td> <td class="grpTextBox">{{ article.Firstname }}</td> <td class="grpTextBox">{{article.Email}}</td> </tr> {% endfor %} </table> in web view -
How to do product sorting when we search for certain product in Django?
views.py:- def search(request): global pro global products if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2': q = request.GET.get("q") products = Product.objects.filter(active=True, name__icontains=q) categories = Category.objects.filter(active=True) brands = Brand.objects.filter(active=True) context = {"products": products, "categories": categories, "brands": brands, "title": q + " - search"} return render(request, "shop/home.html", context) pro = products if request.GET.get('price_filter') == '1': products = pro.order_by('price') categories = Category.objects.filter(active=True) brands = Brand.objects.filter(active=True) context = {"products": products, "categories": categories, "brands": brands} return render(request, "shop/home.html", context) elif request.GET.get('price_filter') == '2': products = pro.order_by('-price') categories = Category.objects.filter(active=True) brands = Brand.objects.filter(active=True) context = {"products": products, "categories": categories, "brands": brands} return render(request, "shop/home.html", context) In HTML:- <form method='get' action='#' style="margin-top:-20px; margin-left: 8px;"> <input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High <input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low <button class="btn" type="submit" value="Sort">Sort</button> </form> Using that search we I am able to sort low to high, but when I choose High to Low, it shows certain Error:- Cannot use None as a query value I know this is not the right method to do this, but can please help me out with this, or guide me with the correct way to do sorting. -
with token authentication method applied in django,I am not able to access fucntions with "POST" method
i have applied token authentication to my api in django rest framework in views.py..now when i send a url request in POSTMAN with the 'Authetication: Token dggjgsjgsjgfjggsdgggs' i am not able to access GET methods but not POST or DELETE methods. -
Is there a Django Mock Library that allows filtering of mocked query sets based on foreign keys
Problem Overview Based on the all() method of a Django model manager, filter all models in query set based on 2 fields. (Doable with Q object) Afterwards, for each model from my filtered query, check if said model is a foreign key in another Django model instance. If the model does not act as foreign key, add its information to a dictionary and append said dictionary to a list If the model does act as a foreign key, ignore it and go to the next model Using django-mock-queries, I can easily mock the features needed to accomplish step 1 (The MockSet objects provided by the library allow the use of filtering with Q objects for Django model attributes). However, it seems that I cannot filter for objects in a MockSet for attributes that are also Django objects (i.e. MockModels used to mock said objects) Concrete Example More concretely, I can filter for MockModels in a MockSet based on attributes like so. mock_set = MockSet(MockModel(attribute_1="foo"), MockModel(attribute_1="bar")) foo_set = mock_set.filter(attribute_1="foo") However, the following use of filter will return an empty queryset mock_model = MockModel(attribute_1="bar") mock_set = MockSet(MockModel(model_attribute=mock_model), MockModel(model_attribute=MockModel(attribute_1="bar"))) foo_set = mock_set.filter(model_attribute=mock_model) I've tried using Model Bakery as an alternative library, however the … -
Django - How to combine two queries after doing a group by
GOAL: Group by ITEM all INCOMING and its OUTGOING then SUM the quantity to come up with a simple table in my template like this: Item | Total In | Total Out| Stock 1. Cement | 400 | 300 | 100 My models.py class Incoming(models.Model): ... project_site = models.ForeignKey(ProjectSite, related_name='in_project_site', default=7, null=True, on_delete = models.SET_NULL) item = models.ForeignKey(Item, related_name='item_in', null=True, on_delete = models.SET_NULL) quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0) ... class Outgoing(models.Model): ... base_in = models.ForeignKey('warehouse.Incoming', related_name='out', on_delete = models.SET_NULL, null=True) quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0) ... Okay so the goal is to group all incoming by ITEM, then annotate the current total Incoming and Outgoing. So naturally I did this in my views.py incoming = Incoming.objects.filter(project_site__id=self.object.id) context['inventory'] = incoming.values('item__item_name')\ .annotate(tot_in=Sum('quantity'))\ .annotate(tot_out=Sum('out__quantity')) This does not give the proper SUM for the total_in, now after some search this is apparently an issue. One suggestion I found was to separate the query into to so this is what I did. context['current_in'] = incoming.values('item__item_name').annotate(tot_in=Sum('quantity')) context['current_out'] = incoming.values('item__item_name').annotate(tot_out=Sum('out__quantity')) This gives me the correct SUM for each In and Out, now my problem is how to UNITE/COMBINE the two again so I could easily loop through it on my template? I did … -
Mock A Folder Including Its Contents For Unit Test
I am unit testing a function which generates a pdf and stores it in the MEDIA folder. This means my MEDIA folder fills with files generated during unit testing which I must then manually delete. To overcome this I decided to mock the media folder from django.test import override_settings import tempfile @override_settings(MEDIA_ROOT=tempfile.gettempdir()) def test_redirects_after_POST(self): # user is created # POST is tested (pdf is generated within this view) # assertions made This seems like it should work. My problem is that during the first step - where the user is created for the test, the user is given a default profile picture, which is stored in the MEDIA folder. Since I am mocking this folder, the image doesnt exist I get the following error FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Acer\\AppData\\Local\\Temp\\profile_pics\\default.jpg' My question is how can I mock the default profile image in the MEDIA folder OR otherwise work around this? Thank you -
Unable to iterate a dictionary in django templating language
I have not been able to iterate (key and values) in a nested dictionary generated from views.py where context = { "orders_current": orders_current } with return render(request, "orders/cart.html", context) orders_current is a result from a query in views.py: orders_current = Orders.objects.values('def', 'abc', 'toppings') 'toppings' is stored in the database as JSON data but converted (loads) back to a dictionary in the class method: def __str__(self) in models.py. I did this since I read somewhere this is a recommend way of storing a dictionary in the postgresql. Note that orders_current has multiple and nested dictionaries e.g.: < QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] > The dictionary {{ order.toppings }} passed to the html, cart.html is shown to have the value (in verbatim) e.g.: {"Mushrooms": 1.5, "Canadian Bacon": 1.5} So my latest attempt to extract the topping name and the corresponding price (key, value) from the dictionary is: {% for order in orders_current %} ... <table> {% for name, price in order.toppings.items %} <tr> <td>{{ name }}:</td> <td>${{ price }}</td> </tr> {% endfor %} </table> I got no values (name, price)from this code snippet. Based on my web searches, I've … -
How to pass varibles from javascript to django views file
I am uploading CSV and print it on the webpage and later I am trying to pass the variable to Django view.py function but I can't able do that so please someone help me to fix this issue <input type="file" id="fileinput" /> <script> function readSingleFile(evt) { var f = evt.target.files[0]; if (f) { var r = new FileReader(); r.onload = function(e) { var contents = e.target.result; <!--document.write("File Uploaded! <br />" + "name: " + f.name + "<br />" + "content: " + contents + "<br />" + "type: " + f.type + "<br />" + "size: " + f.size + " bytes <br />");--> var lines = contents.split("\n"), output = []; for (var i=0; i<lines.length; i++){ output.push("<tr><td>" + lines[i].split(",").join("</td><td>") + "</td></tr>"); } output = "<table>" + output.join("") + "</table>"; document.write(output); <!--$.post(output);--> exportTableToCSV(null,'test.csv') } r.readAsText(f); document.write(output); <!--$.post(output)--> } else { alert("Failed to load file"); } } document.getElementById('fileinput').addEventListener('change', readSingleFile); </script> view.py code def read(request): if request.method == 'POST': count = request.POST.get['ouput'] print(count) return -
AWS Elastic Beanstalk Django Migration
I have an EC2 instance set up through Beanstalk, but I cannot get the config to run migration my .ebextension/django.config option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: my_app.settings aws:elasticbeanstalk:container:python: WSGIPath: my_app.wsgi:application NumProcesses: 3 NumThreads: 20 container_commands: 00_test_output: command: "echo 'testing.....'" 01_migrate: command: "python manage.py migrate" leader_only: true After checking the logs, it says Invalid HTTP_HOST header: '52.37.179.147'. You may need to add '52.37.179.147' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '172.31.0.249'. You may need to add '172.31.0.249' to ALLOWED_HOSTS. Now even if I add these ip's to ALLOWED_HOSTS in my settings.py, the problem remains. I searched around here and found no answer to this specific issue Without the migration commands, my server is built successfully and is running. Anyone know why? -
Left Join to the latest row using django
I have two tables. Products [id, name, category] Sales [product, date, price] I want to get every Product with the latest row from Sales. If there is no row in sales, I still want to get that product row. The rows are foreign key related. What is the Django way of doing such a left join? -
Can I rely on RAM Objects? Django
I'm very new in Django. And I'm building a web app that uses a lot of calculations in the backend with numpy matrixes and other libraries, it's a scientific application solving a np-hard problem. I've created a simple database and I'm saving the matrixes in the database and a Global Object I created in views.py.The issue is that I first save the matrixes in the Global Object (It means is saved in RAM memory) because I have to do a lot of calculations and then save the results in the matrix, and later in other view func I will take the matrixes with the calculations and save them in the database. Here is some of my code: views.py import PesosObjetivos as po #PesosObjetivos is a module where many calculations are made import numpy as np #other imports that are not important to write here nombre_met_MAN="Método Manual" nombre_met_GMWM="Método Media Geométrica" nombre_met_SDWM="Método Desviación Estándar" nombre_met_CRITICM="Método Matriz de Correlaciones" nombresMets = np.array([nombre_met_MAN,nombre_met_GMWM,nombre_met_SDWM,nombre_met_CRITICM]) class ObjetoVistas(): """ Class to create the Global Object """ def __init__( self, nombresMetodos=np.array([]), metodosUsados=np.array([]), matrices=np.array([]), pesosMAN=np.array([]) ): self.nombresMetodos = nombresMetodos self.metodosUsados = metodosUsados self.matrices = matrices self.pesosMAN = pesosMAN #Object for the view which saves the matrixes and other numpy … -
Pasar valores por defecto en class (CreateView) de Django al crear nuevos modelos [closed]
El código es para una biblioteca en la que un libro puede tener varias copias con distintos autores o idiomas. Quiero crear un nuevo modelo (instancia de libro) que está relacionado con otro por medio de un ForeingKey (libro). Al usar class BookInstanceCreate(CreateView) me guarda el nuevo registro sin inconveniente, pero tengo dos problemas. Necesito retornar a el detalle del libro, no al de la instancia del libro. AL usar success_url='/books_details// que es a donde quiero retornar tengo que mi url necesita una pk, pero no sé cómo pasársela. Me renderiza un formulario para escoger entre todos los libros y es muy dispendioso tener que buscar el libro al que quiero crearle una instancia, me gustaría que este valor esté por defecto (obtenido desde el template anterior que es el detalle del libro a instanciar) para solo modificar los que me interesan con fields =[...] Dejo el código que tengo con los campos de interés: models.py: import uuid class Book(models.Model): title=models.CharField( max_length=100, help_text="enter the book's name" ) summary=models.TextField( max_length=1000, help_text="insert a short description" ) def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) class BookInstance(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, help_text="ID único para este libro particular en toda la biblioteca" … -
Uploading and viewing pdf in django
I am making a Webapp using django. In the app, users can login and upload one pdf file. Then others users can visit their profile and view/download the uploaded pdf file. I know how to upload the pdf. But how do I make it viewable and downloadable from the site?? -
(Python) How do I pass the variable in a decorator to functions?
I have been trying to use a decorator for web token like so: def login_required(func): def wrapper(self, request, *args, **kwargs): header_token = request.META.get('HTTP_AUTHORIZATION') decoded_token = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['email'] user = Customer.objects.get(email=decoded_token) customer_id = user.id try: if Customer.objects.filter(email=decoded_token).exists(): return func(self, request, *args, **kwargs) else: return JsonResponse({"message": "customer does not exist"}) except jwt.DecodeError: return JsonResponse({"message": "WRONG_TOKEN!"}, status=403) except KeyError: return JsonResponse({"message": "Key Error"}, status=405) except Customer.objects.filter(email=decoded_token).DoesNotExist: return JsonResponse({"message": "User Not Found"}, status=406) return wrapper class CartView(View): @login_required def post(self, request): import pdb; pdb.set_trace() try: body = json.loads(request.body) # below is when the customer's order is still active if user.order_set.all().last().order_status_id == 2: # update the order by just adding carts order = user.order_set.all().last() order_id = order.id However, when I check with 'import pdb' the variables 'header_token', 'decoded_token', 'user' and 'customer_id' does not turn up in the 'post' function, thus resulting in 500 error. Here is what I find via pdb. (Pdb) decoded_token *** NameError: name 'decoded_token' is not defined (Pdb) user *** NameError: name 'user' is not defined (Pdb) Performing system checks... What should I do to make them pass onto the function rather than disappear as soon as the interpreter exits the decorator? Thanks! -
I leave a question regarding DRF multi-image processing
class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = "image" class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True) class Meta: model = Post fields = ( "id", "author", "content", "images", ) I'd like to get the results the following response from the above communication codes. (위 코드로 GET 통신에서 아래와 같은 응답 결과를 얻고 싶은데요.) { "id": 53, "author": 1, "post": "awesome", "images": { "image": "abc.png", "image": "def.jpg", } } The images field does not apply and appears like below. (images 필드가 적용되지 않고 아래와 같이 나오는 상황입니다.) { "id": 53, "author": 1, "post": "awesome", } Which part should I fix? I also attach the code for the model. (어떤 부분을 고쳐야할까요? 모델 단 코드도 같이 첨부합니다.) class Post(models.Model): author = models.ForeignKey("User", on_delete=models.CASCADE) post = models.CharField(max_length=100) class PostImage(models.Model): post = ForeignKey("Post", on_delete=models.CASCADE) image = models.ImageField(upload_to="image", blank=True) -
TypeError at /admin/mainapp/newsadmodel/add/ expected string or bytes-like object
I'm using django storages to access aws s3 bucket. While adding images to the model NewsAdModel using admin panel, I'm getting this error. TypeError at /admin/mainapp/newsadmodel/add/ expected string or bytes-like object. It does not give me any error hint. What could be wrong here? models.py class NewsAdModel(models.Model): name = models.CharField(max_length=255) pic = models.FileField(storage=PublicMediaStorage(),upload_to='ads') class Meta: verbose_name = 'News Ad' verbose_name_plural = 'News Ads' def __str__(self): return self.name Error message: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/mainapp/newsadmodel/add/ Django Version: 2.2.12 Python Version: 3.7.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'mainapp', 'storages'] 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: File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\sites.py" in inner 223. return view(request, *args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in add_view 1645. return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in changeform_view 1529. … -
How to fix Unexpected token error, expected “}”
I keep on getting an error saying unexpected token but have no idea where that unexpected token is at? Please help Code is below import React from 'react'; import react, { Component } from 'react' import { Plateform, StyleSheet, View,Text } from 'react-native'; function Header() { return ( <div> <this.View style={style}/> <Text style={[styles.setFontSize.setColorRed]}>Welcome to the dealership!</Text> <header className="header"> <div className="col1"> </div> <div className="col2"> <div className="menu"> <h3>About</h3> <h3>Cars</h3> <h3>Contact</h3> <h3>Search</h3> <header/> <View/> </div> </div> **Here is where the error seems to be happing** ); } export default Header; App = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center' }, setFontSize: { fontSize: 20, fontWeight : 'bold' }, setColorRed : { color: '#f44336' } }); Error is below as well Line 37:12: Parsing error: Unexpected token, expected "}" 35 | 36 | App = StyleSheet.create({ 37 | container: { | ^ 38 | flex: 1, 39 | justifyContent: 'center', 40 | alignItems: 'center' -
Django: Attempting to create custom 2 password confirmation in my registration form. Form is not valid?
my name is Paul, I am an early high school beginner working on my first "independent" project. "Independent" meaning without tutorial guidance. My goal is to make a calendar website, just to keep track of a list of events such as homework, meetings, and such. Currently, I am working on the registration form. At first, I used the built in UserCreationForm but I decided to create my own HTML form. I am working on recreating this 2 password confirmation form which would take in the two inputs, make sure there aren't any forbidden keys, make sure that the two passwords are matching, and then save that password into the User model's password, along with a username, first_name, and last_name(this would happen in my view.py file). When I first tried registering, nothing would pop up and as I checked the admin page it turns out no new Users were made. So I put up messages throughout my view if statements to see where the code was getting cut off. It turns out that the form.is_valid was returning false, and I'm not too sure why. I want to believe it may be that my HTML form inputs do not match my forms.py …