Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it able to delete the file after I send files in Django
from django.http import FileResponse def send_file: #some processes response = FileResponse(open(file_name, 'rb'),as_attachment=True) return response I want to delete the file after my web app send it, but my server on Heroku only have 512M . So I can't use too much memory. How can I do that? Many thanks -
Need to Override the save method to save it as base64 from Image field Django
models.py def upload_org_logo(instance, filename): ts = calendar.timegm(time.gmtime()) filepath = f"org_logo/{ts}" if instance: filepath = f"org_logo/{instance.org_id}/{instance.org_name}" base, extension = os.path.splitext(filename.lower()) return filepath class Organisation(models.Model): """ Organisation model """ org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org_name = models.CharField(unique=True,max_length=100) org_code = models.CharField(unique=True,max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, default='blank.jpg', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) org_logo_b64 = models.BinaryField(blank=True, null=True) def save(self, *args, **kwargs): if self.org_logo: logo = open(self.org_logo.url, "rb") print(logo) self.org_logo_b64 = base64.b64encode(logo.read()) super(Image, self).save(*args, **kwargs) When I tried to Post, it is throwing me an error as FileNotFoundError at /admin/onboarding/organisation/7577ef5f-356c-4cbd-8ef6-e906382447ff/change/ [Errno 2] No such file or directory: '/media/white-logo.png' Request Method: POST Request URL: http://127.0.0.1:8000/admin/onboarding/organisation/7577ef5f-356c-4cbd-8ef6-e906382447ff/change/ Django Version: 3.2.12 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/media/white-logo.png' Exception Location: F:\PM-Onboarding-Service\Onboarding-Service\microservices\onboarding\models.py, line 244, in save I tried the method based on this answer django admin: save image like base64. My settings for Media is: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Can anyone please help me to save the image as base64 in the database by override the save method for the imagefield? -
I can't create super user
I am building my website with Django. I need to create a super user but there is a huge error after I enter the user, mail, password. Without a super user, I will not be able to continue developing the project, therefore, I ask for help. Error: Traceback (most recent call last): File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 210, in __init__ with gzip.open(password_list_path, 'rt', encoding='utf-8') as f: File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/gzip.py", line 58, in open binary_file = GzipFile(filename, gz_mode, compresslevel) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/gzip.py", line 173, in __init__ fileobj = self.myfileobj = builtins.open(filename, mode or 'rb') FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/.cache/pip/pool/d4/1e/2a/common-passwords.txt.gz' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/runner/laba/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 157, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 44, in validate_password password_validators = get_default_password_validators() File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 19, in get_default_password_validators return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 30, in get_password_validators validators.append(klass(**validator.get('OPTIONS', {}))) … -
Django ORM Query to show pending payments
Please guide me. I have below models under which a Student can enroll for a course which has a fees specified for it. Against that enrollment a student can make part payments. I am unable to create a query which will show me list of students with courses enrolled and total payment made for that enrollment. class Course(models.Model): name = models.CharField(max_length=100) school = models.ForeignKey(School, on_delete=models.CASCADE) student_class = models.IntegerField(verbose_name="Class", help_text="Class", choices= STUDENT_CLASS) fee = models.IntegerField() created_on = models.DateField(auto_now_add=True) class Enrollment(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) created_on = models.DateField(auto_now_add=True) class Payment(models.Model): PAYMENT_CHOICES = [ ('CAS', 'Cash'), ('CHQ','Cheque'), ] enrollment = models.ForeignKey(Enrollment, on_delete=models.CASCADE) amount = models.IntegerField() mode = models.CharField(max_length=3, choices=PAYMENT_CHOICES) payment_date = models.DateField(auto_now_add=True) -
Failed to pass html input to django
I'm trying to pass date input to django python script in order to retrieve the data based on it. Here is my code. view def daily_usage_report(request): if request.method == 'POST': request_date = request.POST.get('request_date') else: request_date = date.today() print(request_date) ... html <form method="post" action="#"> <input type="date" name="request_date" id="request_date"> <button class="btn btn-primary"><a href="{% url 'daily_usage_report' %}" style="color: white;">Daily Usage Report</a></button> </form> I tried to fill the form with random date, but it keeps printing today date. -
Replace Keyword Argument With Variable in Django Model Filtering
I am performing filtering on a django model based on the data supplied by user in an input form. I don't want to hard-code values and so I would love to loop through the entire query parameters in request.POST and then filter by the key and value. Here is a sample from my code class QueryView(View): def post(self, request, *args, **kwargs): params = request.POST if params: for key in params: queryset = MyModel.objects.filter(key=params[key]) return MyResponse I can't get things to work as key must be a field in MyModel, is there a better way of achieving this same goal. -
How to get value of json field in django views.py
[views.py] from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') histories = History.objects.filter(content__icontains='teacher', date__gte=from_date, date__lte=to_date).order_by('date') for h in histories: histories = History.objects.annotate(teacher=json.loads(h.summary)).values('study_name', 'teacher', 'date') I am trying to print the 'study_name', 'summary', and 'date' fields of the History model that satisfy the period set in Django views.py . The summary field uses json.loads as the json type, but the following error occurs. QuerySet.annotate() received non-expression(s): {'field_summary': {'recruiting': 'None -> Yes', 'teacher': 'None -> Halen', 'subject': 'None -> 'science'}, 'file_summary': {}}. How to get the teacher value of field_summary? -
Werkzeug server is shutting down in Django application
after updating the Werkzeug version from 2.0.3 to 2.1.0, I keep getting errors every time I run the server, and here is the error log: Exception happened during processing of request from ('127.0.0.1', 44612) Traceback (most recent call last): File "/usr/lib/python3.8/socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.8/socketserver.py", line 747, in __init__ self.handle() File "/home/oladhari/.virtualenvs/reachat/lib/python3.8/site-packages/werkzeug/serving.py", line 363, in handle super().handle() File "/usr/lib/python3.8/http/server.py", line 427, in handle self.handle_one_request() File "/usr/lib/python3.8/http/server.py", line 415, in handle_one_request method() File "/home/oladhari/.virtualenvs/reachat/lib/python3.8/site-packages/werkzeug/serving.py", line 243, in run_wsgi self.environ = environ = self.make_environ() File "/home/oladhari/.virtualenvs/reachat/lib/python3.8/site-packages/django_extensions/management/commands/runserver_plus.py", line 326, in make_environ del environ['werkzeug.server.shutdown'] KeyError: 'werkzeug.server.shutdown' this exception keep appearing while incrementing by 2 ( ('127.0.0.1', 44612) -> ('127.0.0.1', 44628) and the server crash checking the changes log, I have found this detail: Remove previously deprecated code. #2276 Remove the non-standard shutdown function from the WSGI environ when running the development server. See the docs for alternatives. here is the link to the changes log it asks to check the documentation for alternatives but can not find any please let me know how I would resolve this error, thank you NB: my python version is 3.8 -
Django Rest Framework API with Primary Key Related Field serializer says that field is required even when it is included
I have an API with Django Rest Framework and one of my Serializers looks like this: class InputtedWaittimeSerializer(serializers.ModelSerializer): restaurant = serializers.PrimaryKeyRelatedField(many=False, queryset=Restaurant.objects.all(), read_only = False) reporting_user = serializers.PrimaryKeyRelatedField(many=False, queryset=AppUser.objects.all(), read_only = False) class Meta: model = InputtedWaittime fields = ['id', 'restaurant', 'wait_length', 'reporting_user', 'accuracy', 'point_value', 'post_time', 'arrival_time', 'seated_time'] depth = 1 read_only_fields = ('id','accuracy','point_value','post_time') Restaurant and AppUser are both different models, and the Serializer model (InputtedWaittime) has fields that are foreign keys to the first two models. I added a PrimaryKeyRelatedField for each of these foreign key relations so that the API would only show their primary keys. So, a GET request to this API looks like this: { "id": 1, "restaurant": 1, "wait_length": 22, "reporting_user": 1, "accuracy": 1.0, "point_value": 10, "post_time": "2022-05-08T23:39:11.414114Z", "arrival_time": "2022-05-08T23:39:05Z", "seated_time": null } Where reporting_user and restaurant just have the primary keys to their entries in the other models. However, I have run into a problem when I try to POST data to this API. When I send data in with just the primary keys for the foreign key fields, the API just returns this response: {"restaurant":["This field is required."],"reporting_user":["This field is required."]}% I used this command to POST data to this API: curl -X … -
PayPal Advanced Credit Card Payments - paypal.HostedFields.isEligible() returns False
I'm trying to integrate PayPal's advanced credit card payments into my web app but the below code always returns false. paypal.HostedFields.isEligible() I've checked the account settings about 100 times. I've enabled all credit card payments, created sandbox businesses accounts and etc. still getting the same error. FYI.. paypal.Buttons works without any issues. Any idea how can I resolve this? -
How to run pytest upon successful post in Django Rest framework?
I want pytest to call a function that can run if a post type is successful and do the same on github actions? It is a django rest framework project and the model is routed as a URL having a single field only At the moment I have multiple import issues cause the previous developer have made multiple .venvs and both useless so python cannot resolve host for most of the import in the project I also have a submodule which also has test files and I want to ignore that is it possible to ignore tests for a specific directory? -
Django not redirecting to home page after filling in register form
I'm new to django. I want to redirect to the home page after filling in the form to register a new user. But that doesn't happen when I click the submit button. Instead, the form fields are cleared and that's it. I've created two apps: blog and users Here's the basic structure of my project, if it's of any importance: ───django_project │ db.sqlite3 │ manage.py │ ├───blog │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ 0001_initial.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ 0001_initial.cpython-39.pyc │ │ __init__.cpython-39.pyc │ │ │ ├───static │ │ └───blog │ │ main.css │ │ │ ├───templates │ │ └───blog │ │ about.html │ │ base.html │ │ home.html │ │ │ └───__pycache__ │ admin.cpython-39.pyc │ apps.cpython-39.pyc │ models.cpython-39.pyc │ urls.cpython-39.pyc │ views.cpython-39.pyc │ __init__.cpython-39.pyc │ ├───django_project │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ settings.cpython-39.pyc │ urls.cpython-39.pyc │ wsgi.cpython-39.pyc │ __init__.cpython-39.pyc │ └───users │ admin.py │ apps.py │ models.py │ tests.py │ urls.py │ views.py │ __init__.py │ … -
Websockets not working with Django channels after deploying
I'm trying to deploy my Django project, but I faced some difficulties. Everything is working perfectly on local machine. I'm using Django + nginx + uvicorn (runned by supervisor). Also, I got my SSL certificate in use. When I try to connect to websocket (/ws) via loading the page and making my js files work, I get a message in console: WebSocket connection to 'wss://example.com/ws/' failed Here is my nginx config map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name example.com; return 301 https://example.com$request_uri; } server { listen 443 ssl; ssl on; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; server_name example.com; client_max_body_size 100M; gzip on; gzip_vary on; gzip_proxied any; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript; location /ws/ { proxy_pass https://uvicorn/ws; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_http_version 1.1; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_intercept_errors on; proxy_redirect off; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-NginX-Proxy true; proxy_ssl_session_reuse off; } location /static/ { root /root/server/social; expires 1d; } location /media/ { root /root/server/social; expires 1d; } location / { proxy_pass https://uvicorn; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } upstream uvicorn { server unix:/tmp/uvicorn.sock; } And the supervisor config [program:django] … -
Django Pycharm debbuger - can't find '__main__' module in ''
I'm trying to solve a problem where django isn't redirecting the way it should, so I'm trying to debug it with Pycharm Community Edition. I've tried setting a Run/Debug configuration as such: But whenever I try to debug it, it gives me this error: C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\Scripts\python.exe: can't find '__main__' module in '' But when I try to just run it, without debugging, it works fine, as seen bellow: I've checked out the following questions but I still can't find an solution: Django 4 Pycharm debugger error: can't find 'main' module in '' - Tried updating Pycharm but nothing changed Pycharm gets error "can't find 'main' module" - Proper script path is already selected What else can I do? Thank you. -
how to override user.check_password(password)
I need to override user.check_password(password) method because I am using a legacy database which is using passwords hashed with .net framework I created a Function that can hash a password and compare it with the hash password which is already saved in the database. my question is how can I override check_password function and when I use it with my function, it will return True -
'CustomUser' object has no attribute 'get'
I'm trying to auto-assign a ModelForm field to be a ForeignKey from the Model that the ModelForm is based off of. The Model includes a ForeignKey that references a CustomUser. What I'd like to do is auto-assign the ModelForm field so that a logged-in user can submit the form as save the data to the database. I keep getting this error: 'CustomUser' object has no attribute 'get'. I don't understand what is throwing this error. I have pointed the settings to my CustomUser and registered the models in the admin files for each app. Additionally, both Models show up in the admin section of my project, but when I save the form for a logged in user I get that error and it doesn't save to the database. Code Below for Reference: class CustomUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Account must have an email address') user = self.model( email = self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email = self.normalize_email(email), password = password,) user.is_admin = True user.is_staff = True user.is_active = True user.is_superuser = True user.save(using = self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length = 100, unique = True) … -
Django: related_name issue
I am trying to make a query with related_name. I need to list tenants and its domain. But I am getting this error: 'TenantManager' object has no attribute 'domains' What am I doing wrong? models.py class Tenant(TenantMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) created_on = models.DateField(auto_now_add=True) objects = TenantManager() auto_create_schema = True auto_drop_schema = True class Domain(DomainMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) domain = models.CharField(max_length=253, unique=True, db_index=True) tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains', on_delete=models.CASCADE) managers.py class TenantManager(models.Manager): def list_all(self): return self.domains.all() viewsets.py class TenantViewSets(viewsets.GenericViewSet): authentication_classes = (JWTAuthentication,) permission_classes = [IsAuthenticated, IsAdminUser, IsSuperUser] def list(self, request): queryset = Tenant.objects.list_all() serializer = Tenant.Serializer(queryset, many=True) return Response(serializer.data) serializers.py class DomainSerializer(serializers.ModelSerializer): tenant = serializers.RelatedField(read_only=True) class Meta: model = Domain fields = ( "id", "domain", "tenant", ) class TenantSerializer(serializers.ModelSerializer): domain = DomainSerializer(read_only=True) class Meta: model = Tenant fields = ( "id", "name", "schema_name", "created_on", "domain", ) -
Django admin site form auto-filled with values in many-to-many relationship
class Student(models.Model): id = models.IntegerField(primary_key=True, unique=True, null=False) name = models.CharField(max_length=100, null=False) password = models.CharField(max_length=100, null=False) course = models.ManyToManyField('Course', related_name='students', blank=True) class Meta: verbose_name_plural = 'Students' def __str__(self): return self.name class Course(models.Model): id = models.IntegerField(primary_key=True, null=False) name = models.CharField(max_length=255, null=False, unique=True) class Meta: unique_together = ('id','name') verbose_name_plural = "Courses" def __str__(self): return self.name I have two models, student and courses and the relationship is many to many. From the django admin site, after adding a new course if I want to add new student the courses field in the student form is already filled with all the added courses and when I save I can't remove those courses. I want to create student without assigning courses initially. How do I do that? -
Problem with different schema relationship in Django Migrations
I have a multiple schema database with relationships between them and I have a problem migrating the database in Django. Firstly I created a BaseModel to override the meta class parameters: base_models.py: import django.db.models.options as options from django.db import models options.DEFAULT_NAMES = options.DEFAULT_NAMES + ("database",) class BaseErpModel(models.Model): class Meta: abstract = True database = "erp" models.py from django.db import models from config.base_models import BaseErpModel from teste_migrate.users.models import User class TrendUpload(BaseErpModel): trend_name = models.CharField("Tendência", max_length=255) created_at = models.DateTimeField("Data de criação", auto_now_add=True) user = models.ForeignKey(User, verbose_name="Usuário", on_delete=models.DO_NOTHING) class Meta(BaseErpModel.Meta): database = "erp" def __str__(self): return f"{self.trend_name} - {self.created_at}" dbrouter.py from django.apps import apps class BaseRouter(object): """A router to control all database operations on models in the erp schema""" def db_for_read(self, model, **hints): "Point all operations on model to 'database' meta db" if hasattr(model._meta, "database"): return model._meta.database return "default" def db_for_write(self, model, **hints): "Point all operations on model to 'database' meta db" if hasattr(model._meta, "database"): return model._meta.database return "default" def allow_relation(self, obj1, obj2, **hints): "Allow any relation in the same Database" return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Don't allow migrate to 'not_alowed_relation_models' """ try: model = apps.get_model(app_label, model_name) except: return None try: database = model._meta.database allow_migration = model._meta.allow_migration except: database … -
How to regroup blog posts with multiple categories by category in Django template
I have Blog with posts that have multiple categories class BlogDetailPage(Page): heading = models.CharField(max_length=150, blank=False, null=False) categories = ParentalManyToManyField("blog.BlogCategory", blank=False) ... class BlogCategory(models.Model): title = models.CharField(max_length=30,unique=True) slug = AutoSlugField(populate_from='title') ... My posts are as follows: Post 1: Category A Post 2: Category A, Category B Post 3: Category B I want regroup posts by category as below: Category A Post 1 Post 2 Category B Post 2 Post 3 My current solution is not giving me correct results. {% regroup posts by categories.all as posts_by_categories %} <ul> {% for category in posts_by_categories %} <li>{{ category.grouper.0 }} # first category name <ul> {% for post in category.list %} <li>{{ post.id }}, {{post.categories.all}}</li> {% endfor %} </ul> </li> {% endfor %} Amy ideas? -
How to save a bunch of many to many fileds using model to dict
I have a group of many to many fields that i am trying to save together with the other fields that are not many to many in django. def save_model(self, model_obj, model_cls): """ Get and save fields of a specific model """ kwargs = model_to_dict(model_obj, fields=[field.name for field in model_obj._meta.fields], exclude=['id', 'maternal_visit_id', 'maternal_visit']) for key in self.get_many_to_many_fields(model_obj): kwargs[key] = (self.get_many_to_many_fields(model_obj).get(key)) temp_obj = model_cls.objects.create(**kwargs, maternal_visit_id=self.id, maternal_visit=self.instance) temp_obj.save() am getting the many to many fields like def get_many_to_many_fields(self, model_obj): """ Return a dictionary of many-to-many fields in a model """ return model_to_dict(model_obj, fields=[field.name for field in model_obj._meta.get_fields() if isinstance(field, models.ManyToManyField)]) and when the script runs, it is giving me an error Internal Server Error: /admin/flourish_caregiver/maternalvisit/6128fcdc-8d39-41eb-a94d-fe839dd69a6e/change/ Traceback (most recent call last): File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/edc_model_admin/model_admin_next_url_redirect_mixin.py", line 68, in change_view return super().change_view(request, object_id, form_url=form_url, extra_context=extra_context) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django_revision/modeladmin_mixin.py", line 24, in change_view return super(ModelAdminRevisionMixin, self).change_view( File … -
How can I use newspaper3k with Django-rest-framework? I want to scrap news articles through newspaper3k then save in sqlite3
I want to scrap news articles through newspaper3k then save in sqlite3. I couldn't find any code where django and newspaper3k coded together. Please help me by writing proper code. Thanks -
How i can implement Calender Schedule Event in Django?
I want to implement this calender event with django. How i can do it .....?? enter image description here -
Why am I getting `NOT NULL constraint failed` error with Django?
I am new to Django. I am to create some sort of todo app. I am having trouble setting IntegerField as optional field. As far as I can see the problem is when I try to save to save the object to the database. I get error: NOT NULL constraint failed: lista_row.quantity. I have made (and migrated) migrations. Here is my models.py: from django.db import models from django.contrib import admin class Row(models.Model): name = models.CharField(max_length=200) quantity = models.IntegerField(null=False, blank=True) -
vuejs 401 unauthorized with axios from django backend with token
im trying to fetch data from django rest backend with axios in vuejs frontend but each time i get this error. the tokens match but it is still not authorizing. {"message":"Request failed with status code 401","name":"AxiosError","config":{"transitional":{"silentJSONParsing":true,"forcedJSONParsing":true,"clarifyTimeoutError":false},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"maxBodyLength":-1,"env":{"FormData":null},"headers":{"Accept":"application/json, text/plain, */*","Authorization":"Token838881311c52b89dd937815066e7eb3a3221604c"},"baseURL":"http://127.0.0.1:8000","method":"get","url":"/api/v1/clients/"},"code":"ERR_BAD_REQUEST","status":401} the axios looks like this axios .get('/api/v1/clients/') .then(response => { for(let i = 0; i< response.data.length; i++){ this.clients.push(response.data[i]) } }) .catch(error => { console.log(JSON.stringify(error)) }) } the settings in my django are ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8000", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES":( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ) }