Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User authentication failing while user login in django
I am trying to create a simple login page using python and django. My registration/signup is working fine and I am able to register the user. once the user is registered, while logging in the user using username and password the user is not authenticated. I am not able to find out the exact error, can anyone please guide me through this. This is my views.py file from django.shortcuts import render from django.views.generic import TemplateView, DetailView, ListView from django.contrib.auth import login,logout,authenticate from django.contrib.auth.decorators import login_required from django.urls import reverse from django.http import HttpResponse,HttpResponseRedirect from custom_login_app.forms import CustomUserInfoForm from custom_login_app import models # Create your views here. # about template view class AboutView(TemplateView): template_name = 'about.html' # user profile detail page class ProfileDetailView(DetailView): context_object_name = 'user_detail' model = models.CustomUserInfo template_name = 'userinfo_detail.html' # home page view def index(request): return render(request,'index.html') # logout view @login_required def customlogout(request): logout(request) return HttpResponseRedirect(reverse('index')) # registration view def registration(request): # bool variable to chcek the user is registered registered = False # check the user has poste the data through the form if request.method == 'POST': # create a form object user_form = CustomUserInfoForm(data=request.POST) # check if the form is valid if user_form.is_valid(): # save the … -
Unable to login after PUT operation Django REST Framework
I'm having the following problem: the login request returns "Unable to login with provided credentials" after I do a PUT request (changing fields like first_name, last_name, address) even though the username and password are correct in the DB. The following view I use to make my Login Request. class RetrieveAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) resp = Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email, 'role': user.role, }) return resp And these are for my users and registration of a user: from users.models import User from users.serializers import UserSerializer, RegistrationSerializer from rest_framework import viewsets, generics from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response # Create your views here. class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() class RegistrationView(generics.CreateAPIView): model = User serializer_class = RegistrationSerializer My serializers look like this: from rest_framework import serializers, status from users.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}) class Meta: model = User fields = '__all__' extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): instance = super(UserSerializer, self).update(instance, validated_data) instance.set_password(validated_data['password']) instance.save() return instance class RegistrationSerializer(serializers.ModelSerializer): password … -
Django - Profile doesn't change
I want my users to be able to change their information, when I click "Enregistrer" (Save), I'm redirected but there's no success message and my informations don't change. I think I've setup everything correctly and I looked at similar questions but it still doesn't work. models.py : from django.db import models from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='defaut.png', upload_to='image_profil') def __str__(self): return f'{self.user.username} Profil' forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profil class FormulaireModifUtilisateur(forms.ModelForm): username = forms.CharField( label = 'Nom de compte', min_length = 4, max_length = 150, initial=User.username, ) email = forms.EmailField( label = 'Email', min_length = 4, max_length = 150, ) class Meta: model = User fields = ['username', 'email'] class FormulaireModifProfil(forms.ModelForm): class Meta: model = Profil fields = ['image'] profils.html : {% extends 'home/index.html' %} {% block title %} Profil {% endblock %} {% block content %} <div id='profil'> <img src='{{ user.profil.image.url }}'> <form> {% csrf_token %} {% for field in u_form %} <p> {{ field.label_tag }}<br> {{ field }<br> </p> {% endfor %} {% for field in p_form %} <p> {{ field.label_tag }}<br> {{ field }}<br> </p> {% endfor %} … -
DjangoChannels consumers
I am very interested in the idea to write a chat application. I've recently come across great tutorial at https://channels.readthedocs.io/en/latest/index.html using DjangoChannels All understood, wrote my own one (suppose the same as there), everything is working. However, I ran into a problem: when updating the chat page, the server throws this exception (and after that I can't send messages, so that's quite harmful): Exception in callback AsyncioSelectorReactor.callLater..run() at /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py:287 handle: .run() at /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py:287> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/events.py", line 81, in _run self._context.run(self._callback, *self._args) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py", line 290, in run f(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/daphne/server.py", line 229, in application_checker exception = application_instance.exception() asyncio.exceptions.CancelledError (I am using WebsocketConsumer, python 3.8.2) Actually, I suppose there is a problem with the disconnection with the server when updating the page. I tried to solve it myself but unfortunately didn't succeed :( Could anybody please help me? -
Django Transaction Error: 'You can't execute queries until the end of the 'atomic' block.'
I'm trying to upload a list to my Database. I get this error when I try to migrate. Django Transaction Error: 'You can't execute queries until the end of the 'atomic' block.' From what I have read I have to do something with transaction.atomic(). But it's not clear to me where/what I need to do with that function. Can someone explain where the problem is occurring? restaurants = [ ["Cecilware HWD3 Black 3 Gallon Hot Water Dispenser - 120V", 581.62, 737.78], ["Avamix BXSSJAR 1 Gallon Stainless Steel Blender Jar", 149.99, 206.40], ["Brother HL-L8360CDW Business Color Laser Printer", 328.94, 405.25], ] def change(apps, schema_editor): New_Products= apps.get_model("Home_Page", "New_Products") for restaurant in restaurants: name = restaurant[0] old_price = restaurant[1] new_price = restaurant[2] New_Products.objects.create( Product_Name=name, Old_Price=old_price, New_Price=new_price, ) class Migration(migrations.Migration): dependencies = [ ('Home_Page', '0001_initial'), ] operations = [ migrations.RunPython( change ), ] ``` -
How to use session variable with/inside Django Channels
I'm trying to create simple multiplayer webbrowser card game. I've implemented example chat from docs tutorial. Next thing I'm trying to hack is to allow users to also provide their nickname via html form because I don't want users to register before playing. So I just want to save it in django session to show it inside game. But when I'm trying to access session variable inside Consumer I having an error. Maybe I'm doing it completely wrong, please help me on how to get visitors provide their nicknames during room connection so that they don't need to register. what I have for now: project/routing.py from channels.sessions import **SessionMiddlewareStack** from channels.routing import ProtocolTypeRouter, URLRouter import game.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': SessionMiddlewareStack( URLRouter( game.routing.websocket_urlpatterns ) ), }) app/consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) # get value from django session bang_player_name = self.scope['session']['player'] # here I got an error while accessing saved username print(f'***{bang_player_name} joined the game***') self.accept() .... index.html where users provide their name and room name .... <form action="post" url="/join_game/"> What chat room would you like to enter?<br> … -
Django record selected image
I currently have a 3 x 3 grid of images, displaying a total of 9 images. The sourced images from 3 different folders(representing 3 different categories). Code for this is in the file random_image.py template to display the images is in pickfeel.html The interface looks like this: I want the user to click on an image and press the 'Next' button. When the 'Next' button is pressed it will record the following data: username Category of selected image What should I do implement this? P.S: I'm inexperienced with Django and any help would be greatly appreciated -
Add additional fields data in response to post method in Django
I need to show additional field data for the POST response. This additional field data is not inserting or updating into the database, just want to get in response. this additional data is getting from another model. I need to customize the response JSON representation model class Country(BaseModel): name= models.CharField(null=True) state= models.FloatField(null=True) class Meta: db_table = 'country' class Tour(BaseModel): name = models.ForeignKey(Country, on_delete=models.PROTECT) country= models.FloatField(null=True) class Meta: db_table = 'tour' class TourInter(BaseModel): tour = models.ForeignKey(Tour, on_delete=models.PROTECT) price= models.FloatField(null=True) details= models.TextField(null=True, blank=True) class Meta: db_table = 'tourinternational' Serializer.py class TourInterCreateSerializer(serializers.ModelSerializer): country = serializers.CharField(required=False,read_only=True) class Meta: model=TourInter fields = ('id','tour','price','country') def validate(self, attrs): tour_id=attrs.get('tour').id tourintid = TourInter.objects.filter(tour=tour_id)[0].id countryobj = Tour.objects.get(id=tourid).country country = countryobj.state attrs.pop({'country': country}) attrs = super().validate(attrs) return attrs views.py class TourInterViewSet(viewsets.ModelViewSet): queryset = TourInter.objects.all() def get_serializer_class(self): if self.action == 'create' or self.action == 'update': return TourInterCreateSerializer return TourInterSerializer def dispatch(self,request,*args,**kwargs): response = super(TourInterViewSet, self).dispatch(request, *args, **kwargs) data = {} data= response.data response.data = data return response postman data request: { tour_id: 1, price: 10000 details: "Could be nil" } I need a postman response like a below-having country name for post response, here country is not inserting into the database: { tour_id: 1, price: 10000 details: "Could be nil", country: … -
how to improve exception handling in python/django
This is an example of my exception handling in a django project: def boxinfo(request, url: str): box = get_box(url) try: box.connect() except requests.exceptions.ConnectionError as e: context = {'error_message': 'Could not connect to your box because the host is unknown.'} return render(request, 'box/error.html', context) except requests.exceptions.RequestException as e: context = {'error_message': 'Could not connect to your box because of an unknown error.'} return render(request, 'box/error.html', context) There is only two excepts now, but it should be more for the several request exceptions. But already the view method is bloated up by this. Is there a way to forward the except handling to a separate error method? There is also the problem, that I need here to call the render message for each except, I would like to avoid that. And here I also repeat for each except "could not connect to your box because", that should be set once when there appeared any exception. -
Django Quering ManytoMany field
Good Day, I am creating a simple django project which deals with storage of name of Books and authors and storing list of to be read (TBR). The TBR table is connected to books table as many to many. Now, I am confused in how to query the list of books that are in a specific TBR. The code that I wrote is the following: class BookManager(models.Manager): def is_read(self): return self.filter(read='y') def is_not_read(self): return self.filter(read='n') class Genre(models.Model): name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') def __str__(self): return self.name class Author(models.Model): first_name = models.CharField(max_length=100, help_text="Enter first name of the author",default="Unknown") last_name = models.CharField(max_length=100, help_text="Enter last name of the author",default="Unknown") def __str__(self): return f'{self.first_name} {self.last_name}' class Book(models.Model): YES = 'y' NO = 'n' DID_READ_CHOICES = [ (YES,'Yes'), (NO,'No'), ] title = models.CharField(max_length=100) author = models.ForeignKey( Author, on_delete=models.SET_NULL, null=True, related_name='author_books' ) genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book',blank=True,null=True) read = models.CharField( max_length=1, choices=DID_READ_CHOICES, default=NO, ) objects = BookManager() class Meta: ordering = ['title'] def __str__(self): return self.title class TBR(models.Model): title = models.CharField(max_length=100) book = models.ManyToManyField( Book, related_name='in_tbr', ) class Meta: ordering = ['title'] def __str__(self): return self.title I … -
Django dynamic Url problem- invalid literal for int() with base 10:
I'm trying to make a dynamic url that adds the name of the current user to the path when he tries to go to his personal posts page. In the personalposts page I filtered all the posts and showed a list of the posts of the current user only. I just want to add his name to the url also. thats it. I tried a lot of things and failed. I have a feeling that the problem is that the author refers to the Django's built-in User model. My code: url: path('<username>/', views.personalposts, name='personalposts'), The view: Before the view was: def personalposts(request, username): items = Post.objects.filter(author=request.user) return render(request, 'TheApp/personalposts.html', {'items':items}) I still want to display the personal posts like this. It works but with out the dynamic url. Now I changed it to: def personalposts(request, username): items = Post.objects.get(author=username) return render(request, 'TheApp/personalposts.html', {'items':items}) The model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT) #כדי שרק משתמשים רשומים יוכלו ליצור פוסט title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) post_views = models.IntegerField(default=0) -
wrong output. remove element from list1 if exist in list2
The code is to remove elements present in another list. Wrong Output Code is written here: s=['a@gmail.com','b@gmail.com',] for e in l: if e in s: l.remove(e) print(l)``` Showing wrong output **output should be =['c@gmail.com','d@gmail.com']** **but output coming is ['b@gmail.com','c@gmail.com','d@gmail.com']** -
could not parse the remainder: '[0].title' from 'i[0].title'
I am trying to render the data from the database one by one by it does not work. index.html {% for i in edus %} <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingOne"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">{{i[0].title}} </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne"> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <p>{{i[0].descripiton}} </p> </div> </div> </div> </div> </div> {% endfor %} -
Limit Django UpdateView to author
I've got a UpdateView in Django that I need to restrict to only the author. I having trouble grabbing the Author off of the request. class MyPermissionMixin(LoginRequiredMixin, UserPassesTestMixin): def dispatch(self, request, *args, **kwargs): user_test_result = self.get_test_func()() if request.user != ????.user: #How do I grab the user('Author')?? return self.handle_no_permission() return super().dispatch(request, *args, **kwargs) -
How to solve when Django views.py is not passing the dictionary value to html?
I have a dictionary value in views.py and rendering it to front end. When I loop through the dictionary in html, only one value is showing while other values are not. What could be the issue for this? views.py def Student_Create(request): form = Student_Model_Form(request.POST or None) # get class names and days classes = Create_Class.objects.all() cls = {} for i in classes: cls[i] = { 'class_name': i.class_name, 'from_day': str(i.from_days), 'to_day': str(i.to_days), 'from_time': i.from_time.strftime("%H:%M:%S"), 'to_time': i.to_time.strftime("%H:%M:%S"), } print(cls) template_name = 'genius/students_create.html' context = {'form': form, 'classes': cls} return render(request, template_name, context) student.html <div class="form-group"> <label for="select-class">Select Class</label> <select class="custom-select" multiple name="select-class"> {% for i in classes%} <option value="{{i.class_name}}">{{i.class_name}} : {{i.from_day}}-{{i.to_day}}</option> {% endfor %} </select> </div> And the final output is like this. See The Output Your help would be appreciated. -
One-to-many relationship in django - how to force the parent to have at least one child
I have two models, artwork thats store information about an art piece and media who store information about the media atached to the art piece, in summary an artwork can have one(not zero) or many medias and a media only can belong to an artwork. My problem is that I can do that django force artwork to have at least one media before to be created and I'm not sure about how to work around this, maybe changing the manager? Thank you in advance -
I am getting a fie not found error while trying to call my php script inside of django view via subprocess?
I am trying to call a Php script from my Django view inside the post method, I am using subprocess for this and I am inputting the correct path but it's giving me the File Not Found Error. Here's what I tired subprocess.call(["php", "D:\\projects\\python\\salesproject\\static\\js\\form_submit.php"]) subprocess.call("php D:\\projects\\python\\salesproject\\static\\js\\form_submit.php") -
DRF JWT Authentication object has no attribute 'id'
I'm using a library suggested by DRF (djangorestframework_simplejwt), installed using pip install djangorestframework_simplejwt Added it to settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } Created two endpoints from imported views from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ # JWT Token path('api/token/', TokenObtainPairView.as_view(), name='token_obtain'), # get a new token before the old expires. path('api/token/refresh/', TokenRefreshView.as_view, name='token_refresh'), ] The users are being created without any problem in the database and the passwords are being hashed. If i go to http://localhost:8000/api/token/, then get the following view Posting the correct user with its password and then I get the following error [17/Apr/2020 12:06:51] "POST /api/token/ HTTP/1.1" 500 122221 Internal Server Error: /api/token/ Traceback (most recent call last): File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\tiago\Desktop\letsgo\authenticationJwt\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File … -
Override actions defined in parent class Django admin
I am upgrading a Django project from Django 1.11. I have successfully upgraded the project upto Django 2.1. When I upgraded to Django 2.2, I got this error message "(admin.E130) name attributes of actions defined in class AdimClass(not real name) must be unique" The admins classes are class AAdmin(admin.ModelAdmin) def custom_action(self, request, queryset): # perform custom action ..... def custom_action_2(self, request, queryset): # another custom actions ..... action = [custom_action, custom_action_2] class BAdmin(AAdmin): def custom_action(self, request, queyrset): # performs different actions but has the same name as AAdmin action ..... actions = AAdmin.actions + [custom_action] problem: (admin.E130) name attributes of actions defined in class AdimClass(not real name) must be unique If I remove the custom_action from AAdmin, the error is resolved but the action is no more available for other classes which inherits AAdmin. Goal: keep the action in parent class AAdmin and override it on child class BAdmin. Note: The code is working fine upto Django 2.1. -
How to temporarily disable Django indexes (for SQLite)
I'm trying to create a large SQLite database from around 500 smaller databases (each 50-200MB) to put into Django, and would like to speed up this process. I'm doing this via a custom command. This answer helped me a lot, in reducing the speed to around a minute each in processing a smaller database. However it's still quite a long time. The one thing I haven't done in that answer is to disable database indexing in Django and re-create them. I think this matters for me as my database has few tables with many rows. Is there a way to do that in Django when it's running live? If not in Django then perhaps there's some SQLite query to remove all the indexes and re-create them after I insert my records? -
How to order foreign key objects returned in a Queryset in the same order of their relationship with related object using django-orm
I want to know of a way to achieve this for a very simple case. I have Room object with Facilities as it's foreign key. Suppose related mapping for Rooms is R1->F4, R2->F1, R3->F2, R4->F3 querying database on filtering Room object returns < R1, R2, R3, R4 > So, I want to know how to query database by filtering Facilities object to return < F4, F1, F2, F3 > -
How to provide token key, while accessing webpage in browser
i am developing web app using django_restframework with token authentication. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework.authentication.BasicAuthentication', #'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', )} token will be generated when user done registration in registration page. Next i want user to login, here i have provide permission_class=[AllowAny.] Next is home page, here i provide permission_class = [IsAuthenticated,] while accessing home page, it shows in browser HTTP 401 Unauthorized Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Token { "detail": "Authentication credentials were not provided." } i can see token was there in database.in postman,i have provided token key in header,so got the output.but while using browser i really dont know how to achieve this.please help me to solve this issue.... -
ValueError: invalid literal for int() with base 10: on Django
I later added a new ForeignKey field to the model. But I encountered such an error. Although I delete this field and delete the database and migrate again, I keep getting this error. models.py / gayrimenkul class Post(models.Model): seller = models.ForeignKey('user.User',max_length=120,blank=False,null=False,verbose_name="İlan Sahibi",on_delete=models.CASCADE,default="admin") title = models.CharField(max_length=120,blank=False,verbose_name="Başlık",help_text="Başlık Giriniz.") slug = models.SlugField(max_length=122,default='',unique=True,null=False,verbose_name='Slug Alanı',editable=False) price = models.FloatField(blank=False,verbose_name="Fiyat") content = RichTextField(verbose_name="Detay") img = models.ImageField(blank=True,verbose_name='Post Resim',default='',upload_to=upload_to) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) The linked model in the ForeignKey field is 'user.User' because I created my own user model. C:\Users\adilc\Desktop\Gayrimenkul\Gmn>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, gayrimenkul, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying gayrimenkul.0001_initial... OK Applying gayrimenkul.0002_post_seller...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\adilc\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", … -
How to Serve a React App with Django on Elastic Beanstalk?
I used to have my app on Heroku and the way it worked there was that I had 2 buildpacks. One for NodeJS and one for Python. Heroku ran npm run build and then Django served the files from the build folder. I use Code Pipeline on AWS to deploy a new version of my app every time there is a new push on my GitHub repository. Since I couldn't figure out how to run npm run build in a python environment in EB, I had a workaround. I ran npm run build and pushed it to my repository (removed the build folder from .gitignore) and then Django served the files on EB. However, this is not the best solution and I was wondering if anyone knows how to run npm run build the way Heroku can do it with their NodeJS buildpack for a python app on EB. -
Can't get an object deletion - ?csrfmiddlewaretoken= appears at the end of the current URL in the urlbar (django)
I am building a simple social network in django. In the "home" of my social, I have the list of all posts published by all users, with author and publishing date. Under each post of the logged user, a "delete" button appears. If the user clicks on it, it returns a specific view of that post, with a message "do you really wish to delete this post?" and two buttons to confirm or cancel the post deletion. However, as I click on button "confirm deletion", the page reloads to the same point, and nothing changes except for the fact that ?csrfmiddlewaretoken=--random-sequence-- appears at the end of the current url in the urlbar. What am I missing? Here is my template: <h3>Do you want to delete this post?</h3> <div class="posts"> {% include "posts/_post.html" with post=object hide_delete=True %} </div> <form class="POST"> {% csrf_token %} <input type="submit" value="Confirm Delete" class="btn btn-danger btn-large"> <a href="{% url 'posts:delete' pk=post.pk %}" class="btn btn-simple btn-large btn-default">Cancel</a> </form> and my DeletePost view based on generic.DeleteView: class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ('user', 'group') success_url = reverse_lazy('posts:all') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id = self.request.user.id) def delete(self,*args,**kwargs): messages.success(self.request,'Post Deleted') return super().delete(*args,**kwargs)