Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
transfering ownership of a website that i made
I have been learning Django for a while now and was thinking of starting to freelance but i am not sure how i am supposed to transfer the ownership to other person like am i supposed to give them the code or do i first create a domain and then transfer it to the client, can anyone please tell me the process of transferring the ownership of website to client.Sorry if this is a stupid question as i said i have never done this before and i tried to search for a solution on google but i wasn't able to find a proper answer -
I there anyway to stop python from loading global variables each time when making changes to each other views in django?
I am working on a machine learning project implemented using django and have to impute a big data set as global variable. Problem is when ever I make changes to other function it is reloading each time taking an hour or two to show the output. Is there anyway I can only load the changes made to that particular view other than reloading the entire views code which is imputing each time ? -
how to store form cleaned_data in a Django session
I am developing an ads web site using Django 3.0 and Python 3.8. I want to build multi step form wizard using django session. I have tried previously formtools.wizard but it failed to satisfy all of my requirements. Thus, I decided to write my own code to do that using session to pass form inputs from one class view to another. The first form go through with no error. However, I got the following error message before second form was rendered: Object of type Country is not JSON serializable The view classes are as follow: class PostWizardStepOne(View): form_class = CommonForm template_name = "towns/salehslist/ads_main_form.html" wizard_data = {} def get(self, request, *args, **kwargs): initial = { 'wizard_data':request.session.get('wizard_data', None), } form = self.form_class(initial=initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) print(request.POST) if form.is_valid(): for k, v in form.cleaned_data.items(): self.wizard_data[k] = v request.session['wizard_data'] = self.wizard_data request.session.modified = True print(self.wizard_data) return HttpResponseRedirect('PostWizardSecondStep') return render(request, self.template_name, {'form': form}) class PostWizardStepTow(View): template_name = "towns/salehslist/forms/jobPostForm.html" def get(self, request, *args, **kwargs): print(request.session['wizard_data']) return render(request, self.template_name, {}) Here are the urls: path('post/', PostWizardStepOne.as_view(), name = 'PostWizardFirstStep'), path('post/', PostWizardStepTow.as_view(), name = 'PostWizardSecondStep'), Here are the forms: class CommonForm(forms.ModelForm): class Meta: model = Job fields = … -
MongoDB embedded and array fields in django
I have a question about querying embedded and array fields in django. This is my models.py file: from djongo import models class detalji_igrica(models.Model): pegi_rejting = models.IntegerField() izdavac = models.CharField(max_length=64) zanr = models.CharField(max_length=32) datum_izlaska = models.CharField(max_length=32) class Meta: abstract = True class komentari(models.Model): id_korisnika = models.IntegerField() komentar_naslov = models.CharField(max_length=64) komentar = models.TextField() datum_komentara = models.CharField(max_length=32) rejting_korisnika = models.FloatField() class Meta: abstract = True class Igrica(models.Model): sifra_artikla = models.IntegerField() naziv = models.CharField(max_length=32) cena = models.FloatField() konzola = models.CharField(max_length=32) slika = models.CharField(max_length=64) opis = models.TextField() rejting = models.FloatField() vrsta = models.CharField(max_length=32) detalji_igrica = models.EmbeddedField( model_container = detalji_igrica ) komentari = models.ArrayField( model_container = komentari ) Here is my views.py file: @api_view(['GET']) def najjeftinije_prvo(request): igrice = Igrica.objects.get(detalji_igrica__konzola = "PS3") if request.method == 'GET': igrica_serializer = IgricaSerializer(igrice, many=True) return JsonResponse(igrica_serializer.data, safe=False) And here is serializers.py: class IgricaSerializer(serializers.ModelSerializer): class Meta: model = Igrica fields = ( 'id', 'sifra_artikla', 'naziv', 'cena', 'konzola', 'slika', 'opis', 'rejting', 'vrsta', 'detalji_igrica', 'komentari' ) As you can see it has one embedded and one array field imported from djongo models. Now when I want to search for all games for example that have in detalji_igrica a field konzola = PS3, this is the message I get: FieldError at /api/igrice/najjeftinije Unsupported lookup 'konzola' … -
Django: got an unexpected keyword argument 'empty_label'
I am trying to make the DateField default as nothing. The documentation says to set empty_label="Nothing" but i get an error for that. Model: class Post(models.Model): release_date = models.DateField(null=True, blank=True, default=None) Forms: class NewPost(forms.ModelForm): release_date = forms.DateField(widget=forms.SelectDateWidget(attrs={'class': 'form_input_select_date'}, years=YEARS), required=False, empty_label="Nothing") Error: init() got an unexpected keyword argument 'empty_label' -
Can't figure out the error on my jinja2/django template
Here is my template, the if statements aren't working! {% extends "auctions/layout.html" %} {% block body %} {% if bid.name == User %} <br> <h1>You Won the auction</h1> <br> {% endif %} <h1>Title: {{title}}</h1> <br> <h1>Seller: {{listing.name}}</h1> <br> <h1>Description: {{listing.description}}</h1> <br> <h1>Category: {{listing.category}}</h1> <br> <h1>price: {{bid.price}} by {{bid.name}}</h1> <br> <form action="{% url 'Bid' %}" method="post"> {% csrf_token %} <input type="hidden" name="title" value="{{title}}"> <input type="number" name="price"> <input type="submit"> </form> <form action="{% url 'watchlist'%}" method="post"> { % csrf_token %} Add to watchlist <input type="hidden" name="form_type" value="Watchlist"> <input type="hidden" name="title" value="{{title}}"> <input type="submit"> </form> {% if User == "ilias" %} <br> <h1>Close the auction</h1> <br> <form action="{% url 'close' %}" method="post"> {% csrf_token %} <input type="hidden" name="title" value="{{title}}"> <input type="submit"> </form> <br> {% endif %} <form action="{% url 'comment'%}" method="post"> {% csrf_token %} <h1>Add comment</h1> <input type="text" name="content"> <input type="hidden" name="title" value="{{title}}"> <input type="submit"> </form> {%for item in comments%} <h3>{{item.content}} by {{item.name}}</h3> <br> {%endfor%} {% endblock %} Here is my views.py def listings(request, title): try: listing = Listing.objects.get(title=title) except: return HttpResponse('<h3>Page not found</h3>') else: title = listing.title name = listing.name comments = comment.objects.filter(title=title) bid = Bid.objects.get(title=title) User = request.user.username print name return render(request, 'auctions/listing.html', { 'listing': listing, 'title': title, 'comments': comments, 'bid': bid, … -
How do I verify the ID token with Firebase and Django Rest?
I just can't wrap my head around how the authentication is done if I use Firebase auth and I wish to connect it to my django rest backend. I use the getIdTokenResult provided by firebase as such: async login() { this.error = null; try { const response = await firebase.auth().signInWithEmailAndPassword(this.email, this.password); const token = await response.user.getIdTokenResult(); /* No idea if this part below is correct Should I create a custom django view for this part? */ fetch("/account/firebase/", { method: "POST", headers: { "Content-Type": "application/json", "HTTP_AUTHORIZATION": token.token, }, body: JSON.stringify({ username: this.email, password: this.password }), }).then((response) => response.json().then((data) => console.log(data))); } catch (error) { this.error = error; } }, The only thing I find in the firebase docs is this lackluster two line snippet: https://firebase.google.com/docs/auth/admin/verify-id-tokens#web where they write decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] # wtf, where does this go? # what do I do with this? Do I put it in a django View? I found a guide here that connects django rest to firebase: https://www.oscaralsing.com/firebase-authentication-in-django/ But I still don't understand how its all tied together. When am I supposed to call this FirebaseAuthentication. Whenever I try to call the login function I just get a 403 CSRF verification failed. … -
Django rest framework post request while using ModelViewSet
I am new to Django have background in Node.js. I am creating an API using Django, Django rest framework and PostgreSQL. # Model for Event. class Event(models.Model): heading = models.TextField() event_posted_by = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='events_posted', null=True) event_construction_site = models.ForeignKey( ConstructionSite, on_delete=models.CASCADE, related_name='construction_site_events', null=True) def __str__(self): return str(self.id) # Event ViewSet class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer # Event Serializer class EventSerializer(serializers.ModelSerializer): event_construction_site = ConstructionSiteShortSerializer() event_posted_by = CustomUserSerializer() class Meta: model = Event fields = ('id', 'heading', 'event_posted_by', 'event_construction_site') Everything here works fine and expected as well. Here is the output of my GET Request. { "id": 2, "heading": "ABCD", "event_posted_by": { "id": 1, "email": "abcd@gmail.com", "first_name": "A", "last_name": "B", "profile_picture": "...", "company": { "id": 3, "name": "Company 3" }, }, "event_construction_site": { "id": 2 } }, But now when it comes to create an event this is the view django rest framework shows me. { "heading": "", "event_posted_by": { "email": "", "first_name": "", "last_name": "", "company": { "name": "" }, "profile_picture": "", "user_construction_site": [] }, "event_construction_site": {} } Here as far as I know when need "event_posted_by" by in GET Request but we don't want to post the user info. while creating an event, same for information … -
downloading files from firebase-storage python
I'm trying to download files from my firebase storage with python, and I can't seem to figure out how. I've tried a bunch of different tutorials. So I have the credentials set up as an enviromental path: os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials.json' and then based off what I've seen online, I tried this to donwnload the file from storage. In firebase storage it's just located in the base directory, so I did: storer = storage.child("project_name.appspot.com").download("path_to_file_in_storage") and I get: AttributeError: module 'google.cloud.storage' has no attribute 'child' I already have initialized firebase using this: cred = credentials.Certificate('credentials.json') firebase_admin.initialize_app(cred) This clearly is incorrect, so how would I go about doing this? -
Django how to make a user not edit superuser rights?
I'm trying to get to know the django-admin page. I've edit the adminpage in such a way that staff-users only get to edit some field and the superuser get to edit/change all the fields. One of the field the staff-user is able te edit is the is_active field. the problem i'm facing is that the staff-user is also able to edit the superuser his is_active rights. This is a problem because the staff-user is able to make sure the superuser is unable to login to the admin part of my django site. I've tried several solution's but nothing seems to work. Is there a way to make this work? admin.py @admin.register(User) class CustomUserAdmin(UserAdmin): list_display = ('username','email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('username','email')}), ('Permissions', {'fields': ('is_staff', 'is_active','user_permissions')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username','email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('username',) ordering = ('username',) def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser disabled_fields = set() # type: Set[str] if not is_superuser: disabled_fields |= { 'is_superuser', 'user_permissions', 'is_staff', 'date_joined', } if ( not is_superuser and obj is not None and obj != request.user ): #disable … -
django - gunicorn cant access my static files - expected str, bytes or os.PathLike object, not NoneType
I use django with ubuntu, nginx, gunicorn. I reach my index and HTML files but static files doesn't load. (http://159.65.204.133:8000/) command: gunicorn -c conf/gunicorn_config.py config.wsgi error: Request Method: GET Request URL: http://159.65.204.133:8000/static/assets/css/bootstrap.min.css Django Version: 3.1.3 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'app'] 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 "/var/www/dcna/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/var/www/dcna/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/dcna/env/lib/python3.8/site-packages/django/views/static.py", line 36, in serve fullpath = Path(safe_join(document_root, path)) File "/var/www/dcna/env/lib/python3.8/site-packages/django/utils/_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "/usr/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a) Exception Type: TypeError at /static/assets/css/bootstrap.min.css Exception Value: expected str, bytes or os.PathLike object, not NoneType gunicorn_conf: /var/www/dcna/conf/ command = '/var/www/dcna/env/bin/gunicorn' pythonpath = '/var/www/dcna' bind = '159.65.204.133:8000' workers =3 accesslog ='/var/www/dcna/logs/access.log' errorlog ='/var/www/dcna/logs/error.log' nginx conf: /etc/nginx/sites-available/dcna server { listen 80; server_name 159.65.204.133; location /static { alias /var/www/dcna/static; } location / { proxy_pass http://159.65.204.133:8000; } } django settings STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') MEDIA_URL = '/uploads/' my django project_dir: /var/www/dcna/ (env) root@ubuntu-s-1vcpu-1gb-ams3-01:/var/www/dcna# ls -la total 60 drwxr-xr-x 12 root root 4096 Dec 19 15:27 . … -
How to retrieve blog post from search page, after searching for keywords in blog post?
i am facing a problem on search page, after successfully searching for keyword in data base it gives me the results but when I click on that result on that search page it doesn't direct me to the original post, let me show me what i mean if someone can help me with this; I need this >>> /blog/blogpost/my_article Instead i am redirected to this >>>/blog/search/blogpost/my_article Using Django/ Python, My Search function in Views: def search(request): query = request.GET['search'] myposts = Blogpost.objects.filter(title__icontains=query) context = {'myposts': myposts} return render(request, 'blog/search.html', context) Url Path: path("search/", views.search, name="search") { # Its an APP inside a Project} Kindly let me know if you got it what i am saying, thanks -
HOW I CAN STORED MY MEDIA FILES OUT OF DEVELPMENT MECHINE IN DJANGO?
how i can store MIDEA_ROOT in out of development server in django. i have huge collection of images that's why I wand to store my images in other server or drive. -
Class 'Horario' is not defined / Class 'Horario' has no 'objects' member
I keep getting this error and I can't seem to find the proper answer to it. I have created a model in models.py class Horario(models.Model): dia = models.CharField(max_length=20) mañana = models.CharField(max_length=20) tarde = models.CharField(max_length=20) and now I am creating a view in views.py to render this in a html file that I have called horario.html def horario(request): context = {'horario' : Horario.objects.all()} return render(request, "horario.html", context) The thing is that I keep getting this error. I have read other threads and the correction to this error seems to be pasting this code in settings.json {"python.linting.pylintArgs": [ "--load-plugins=pylint_django" ],} I don't know how to do this since as I do it I get random errors. Anyone knows a proper way to get this done? -
django don't show form in template
django dont show my form in my template where is the problem? forms.py from django import forms class QuestionForm(forms.Form): massage = forms.CharField(widget=forms.TextInput) views.py from cheatexam_question.forms import QuestionForm def newquestion(request): if request.method == 'POST': form = QuestionForm(request.POST) context = { 'form': form } return render(request, 'homepage.html', context) template <form method="post"> {% csrf_token %} {{ form }} <input class="btn btn-warning form-control" type="submit" value="ثبت سوال"> </form> -
Conditional Execution in Same View
I want my declarations to be user-specific. I chose to do this by making my variable declarations in the view conditional based on user-type. Here's a sample. def order_detail(request, order_id): order = get_object_or_404(Order, id=order_id) if request.user.is_supervisor: user_location = request.user.supervisor.town deliverer = User.objects.filter(deliverer__town=user_location) context={ 'order': order, 'all_delivery_guys_in_town': deliverer } template = 'orders/order_mgt/detail.html' return render(request, template, context) For context, I need supervisors to be able to view a list of available delivery guys within the order detail page. In the code sample, I'm getting an error: local variable 'user_location' referenced before assignment 1. How can I correct this error? 2. Is there a better way of making conditional declarations within the same view? -
Select multiple rows from list to perform action
I have a Table-List which is getting their values from the Database, where each row is a representation of a model in the DB. For now, I can edit or delete row for row. <div class="table-responsive"> <table class="table table-bordered"> <thead class="thead-dark"> <tr> <th scope="col">Select Multiple</th> <th scope="col">Col 1</th> <th scope="col">Col 2</th> <th scope="col">Col 3</th> <th scope="col">Col 4</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody> <tr> <td>{{ object.selectedOrNot }}</td> <-- BooleanField? <td>{{ object.value1 }}</td> <td>{{ object.value2 }}</td> <td>{{ object.function1 }}</td> <td>{{ object.function2 }}</td> <td><a href="{% url 'edit' object.id %}">Edit this row</a></td> <td><a href="{% url 'delete' object.id %}">Delete this row</a></td> </tr> </tbody> </table> </div> My Question is: How can I make them selectable (checkbox), to multiple delete or edit desired entries. -
Django, how to get total sum of methods with agregate sum
how to get total sum of methods in django using agregate ? I used this for fields and it work fine but for method it doesn t return anything. class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.PROTECT) def total(self): total = self.invoiceitem_set.aggregate(sum=Sum('subtotal')) return round(total[("sum")] or 0, 2) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.PROTECT) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) def subtotal(self): return self.price * self.quantity -
Django testing database in a restricted environment
as the title says, I'm restricted in my development environment. I cannot create extra databases for testing purposes and only create local files. Using the environ package for django, the configuration of the database is DATABASES = { 'default': env.db('DATABASE_URL', default='postgres://name@localhost'), } As found in this thread, all I need is a "TEST" key in this configuration. It doesn't have one per default so I've bypassed this by writing db = env.db('DATABASE_URL', default='postgres://name@localhost') db["TEST"] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } This doesn't work however. python manage.py test gives me the following output: Creating test database for alias 'default'... /usr/lib/python2.7/dist-packages/django/db/backends/postgresql/base.py:267: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead. RuntimeWarning Got an error creating the test database: permission denied to create database Type 'yes' if you would like to try deleting the test database '/home/<closed environment>/<project>/config/db.sqlite3', or 'no' to cancel: It still tries to create a database inside an environment in which I do not have the power to alter my … -
How do we display the elements in the dictionary passed as a context object to Django and remove them as user selects it?
I want to display the elements passed through the context object and allow users to unselect or remove items they don't want and submit the form with the remaining items. I am new to Django, I know this could have been done in React using state variable. I tried the following- <select id="mySelect" size="{{mems|length}}"> {% for mem in mems %} <option> {{mem.user}} </option> {% endfor %} </select> <button onclick="myFunction()">remove</button> <script> function myFunction() { var x = document.getElementById("mySelect"); x.remove(x.selectedIndex); } </script> It updates the UI for a second and then again reverts back to the starting state because I guess the mem object is not getting modified in this case and hence again renders the complete list. Is there a better option to display these details and manipulate the DOM based on the requirements in Django? ->mems here is the result of a DB query and has objects with reference to the user model. What I want to return to the server-side is these users, which the admin selects. -
POST request giving KeyError Django DRF
I am trying to make a rest api which takes a POST request and saves the data in my model.But as soon I give the post request it gives me key error. My model is this : class ProductInfo(models.Model): title = models.CharField(max_length=15) image = models.TextField() price = models.CharField(max_length=5) def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(ProductInfo, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) proceed = models.BooleanField(default=True) def __str__(self): return self.item.title + ' | ' + self.user.username My serializer which is required in this view: class OrderItemUpdateSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['item_id', 'quantity', 'user_id','proceed'] This is my view.The problem is in the 'update_order_quantity' function.This function is quite similar to 'set_order_item' function which is above 'update_order_quantity' .The error is occuring in the area where I am accessing the validated_data (all of the variables)> I am including the 'set_order_item' because it is similar to 'update_order_quantity' view. Then why 'update_order_quantity' is not working? @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def set_order_item(request): serializer = OrderItemSerializer(data=request.data) if serializer.is_valid(): item = serializer.validated_data['item'] quantity = serializer.validated_data['quantity'] queryset = OrderItem.objects.filter(item=item) if queryset.exists(): info = queryset[0] info.quantity += quantity info.save(update_fields=['quantity']) return Response("Succesfully created", status=status.HTTP_201_CREATED) else: serializer.save() return Response("Succesfully created", status=status.HTTP_201_CREATED) return Response("Not created", status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) def … -
Group by and Aggregate with nested Field
I want to group by with nested serializer field and compute some aggregate function on other fields. My Models Classes: class Country(models.Model): code = models.CharField(max_length=5, unique=True) name = models.CharField(max_length=50) class Trade(models.Model): country = models.ForeignKey( Country, null=True, blank=True, on_delete=models.SET_NULL) date = models.DateField(auto_now=False, auto_now_add=False) exports = models.DecimalField(max_digits=15, decimal_places=2, default=0) imports = models.DecimalField(max_digits=15, decimal_places=2, default=0) My Serializer Classes: class TradeAggregateSerializers(serializers.ModelSerializer): country = CountrySerializers(read_only=True) value = serializers.DecimalField(max_digits=10, decimal_places=2) class Meta: model = Trade fields = ('country','value') I want to send import or export as query parameters and apply aggregate (avg) over it shown by distinct countries My View Class: class TradeAggragateViewSet(viewsets.ModelViewSet): queryset = Trade.objects.all() serializer_class = TradeAggregateSerializers def get_queryset(self): import_or_export = self.request.GET.get('data_type') queryset = self.queryset.value('country').annotate(value = models.Avg(import_or_export)) return queryset I want to get the data in format like: [ { country:{ id: ..., code: ..., name: ..., }, value:... }, ... ] But having an error on country serializer AttributeError: Got AttributeError when attempting to get a value for field `code` on serializer `CountrySerializers`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'code'. -
wagtail: Locale_ID cannot be null
I'm trying to deploy a website with wagtail 2.11 on pythonanywhere. However, I'm unable to save any page models in the frontend. The cause seems to be that in my 'home'-app, migration 0002_create_homepage.py cannot be not applied. Trying so gives me this error (IntegrityError: (1048, "Column 'locale_id' cannot be null")): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/migration.py", line 121, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards self.code(from_state.apps, schema_editor) File "/home/yogagarten/yogagarten.pythonanywhere.com/home/migrations/0002_create_homepage.py", line 21, in create_homepage homepage = HomePage.objects.create( File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create obj.save(force_insert=True, using=self.db) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 789, … -
Import "rest_framework" could not be resolved. But I have installed djangorestframework, I don't know what is going wrong
Here's my settings.py INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig' ] -
django is_active does not disable the user
I have a Django project that is like a blog and only a few people are using its panel. There was a user that about 5 people where using and we decided to disable this user and create separate accounts for them. In order to prevent errors in the future we decided just to disable this user and not to delete it. I did it manually using the Django's admin panel. I changed is_active to false but the user still is active and can login to the blog panel. Can you please help me find what is the reason?