Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Error when running python manage.py collectstatic - SuspiciousFileOperation
I'm preparing to deploy a Django application with a React frontend to Heroku. When I run python manage.py collectstatic, I receive the following error: raise SuspiciousFileOperation(django.core.exceptions.SuspiciousFileOperation: The joined path (/Users/x/Desktop/x/_code/app/static/media/SourceCodePro-Light.77e36241fe57a40a332a.otf) is located outside of the base path component (/Users/x/Desktop/x/_code/app/staticfiles) I've followed the Django documentation on configuring django.contrib.staticfiles for deployment. The relevant settings in settings.py: BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ... STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') As I understand it, the STATICFILES_DIRS setting directs Django where to look for additional static files to collect in the STATIC_ROOT. And the error I'm receiving appears to be because the joined path is not contained within the base path. The problem is that, if this is the case, I don't understand why the base path component does not refer to BASE_DIR, i.e. /Users/x/Desktop/x/_code/app/. I've tried every permutation of adding/removing slashes in every path in the relevant settings, as well as setting STATIC_ROOT = BASE_DIR. Actually, no matter what I change STATIC_ROOT to, I receive the same error and the /Users/x/Desktop/x/_code/app/staticfiles folder is still generated. This leads me to believe that my setting is being overriden somewhere. Thank you in advance for any solutions provided. -
Erro File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax
Estou há horas tentando seguir o tutorial para criar um app no Django mas esse erro insiste. Eu não consigo de forma alguma executar o comando python manage.py makemigrations + (nome do app). Fica acusando esse erro de line 17 syntax error, me estressando isso. Era para ser um framework façil de se usar. Alguém por favor me ajude com isso porque não sei mais o que fazer. -
How to test django non-REST POST endpoint?
I'm having trouble testing one of my endpoints: @require_http_methods(["POST"]) def store(request): try: body_unicode = request.body.decode('utf-8') body = ast.literal_eval(body_unicode) new_short_url = body['short_url'] original_url = body['original_url'] check_parameters(new_short_url, original_url) Url.objects.create(short_url=new_short_url, original_url=original_url) return HttpResponse('Created', status=201) except KeyError as error: return HttpResponse('Missing {}'.format(error.args), status=400) except (AttributeError, IntegrityError, ValidationError) as error: return HttpResponse(error.args, status=400) As you can see, this endpoint only accepts POST requests and when trying to pass data from my tests, it arrives in the request.body, so I implemented my logic to get the data from there: def test_create_url_ok(self): creation_data = { "short_url": "ab", "original_url": "https://stackoverflow.com/" } response = self.client.post(reverse('store'), data=creation_data, content_type="application/json") self.assertEqual(response.status_code, 201) This works, but the problem is that when sending requests from my templates, data is not in the request.body, but in the request.POST. How to send data in the request.POST from my tests? -
way to find in module
I have a Django module called Section with Sections called Primary, Junior, and Secondary, and each class has some number of classes. My question here is how can I print a sing class in a particular section using Django. -
Pylint errors in Django, Pylint(E0611:no-name-in-module) and Pylint(E1101:no-member)
It seems like my models.py, forms.py, urls.py and views.py are not recognizing the elements in each other and I don't understand what could be going wrong. I'm just starting the project (CS50W Project4-Network) and I noticed the problem when I tried to render the model form and the textarea field of the form linked to the model wouldn't show on the browser, it only shows when I click submit, as a missing field to be filled, I'm not sure if its because of the same pylint errors I'm getting or something else. Here is my models: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Post(models.Model): body = models.TextField() date = models.DateTimeField(auto_now_add = True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author", default=None) def __str__(self): return f"{self.body} by {self.author} at {self.date}" The forms.py: from django import forms from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ["body"] widgets = { "body": forms.Textarea(attrs={'class': 'form-control col-md-5 col-lg-6'}), } The views from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import PostForm from .models import … -
I have a problem: ERROR: Could not find a version that satisfies the requirement kivy-deps.angle==0.3.2 (from versions: none)
I just loading my django project to Heroku, but i have this problem, what can i make? remote: ERROR: Could not find a version that satisfies the requirement kivy-deps.angle==0.3.2 (from versions: none) remote: ERROR: No matching distribution found for kivy-deps.angle==0.3.2 -
How to fetch data remotely for displaying into admin/index.html in django adminlte v3
In Django AdminLte3, I want to show custom dashboard along with others Admin models. The data of the dashboard will come from remote server. And my custom dashboard will open by localhost:8000/admin/. How can I achieve this. Thanks in advance for any suggestion. -
How to do different registration forms according to User type. User type should be established before registration itself
I am trying to make different registration forms according to different User types. I`ve created a custom User, which can be either Customer or Seller, like this: class CustomUser(AbstractBaseUser, PermissionsMixin): class UserTypeChoices(models.TextChoices): Customer = 'Customer', _('Customer') Seller = 'Seller', _('Seller') type = models.CharField( max_length=8, choices=UserTypeChoices.choices, ) My idea is that at first, a person, who visites my website should choose his type, and after that he can register according to it`s type. Sellers should have phone numbers as USERNAME_FIELD, while Customers should have email. I know that I will have to write custom backend for this thing, yet still this is what I want to do. I`ve decided to do two different forms for this: First one with only type field, which should redirect to a form with normal registration. This first form looks like this: class UserTypeForm(UserCreationForm): class Meta: model = get_user_model() fields = ["type"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs[ "autofocus" ] = True del self.fields["password1"] del self.fields["password2"] def save(self, commit=True): user = super().save(commit=False) return user And here is where I`ve stopped right now, as it gives me: Traceback (most recent call last): File "D:\Python\Hillel\VolunteeringHub\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File … -
I have an error when i put my django project on Heroku: ERROR: Could not install packages due to an OSError: [Errno 2]
i don't want this package in my project, how can i skip him? Or what can i make? remote: -----> Installing requirements with pip remote: Processing /D:/Python/mymodules/dist/vsearch-1.0.tar.gz remote: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/D:/Python/mymodules/dist/vsearch-1.0.tar.gz' -
how to backend service with neo4j and django
How do I have to connect neo4j in django? I'm using Python 3, so how to write a service?. I'm new to both of them and at the moment I'm a little confused. thank you guys. -
Can't access Django Admin with my Custom User credentials
I created an app 'accounts' from which I created my CustomUser. Then, I created superuser from the command line successfully. But I can't login to Django Admin. Everytime, it displays "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." This is my accounts.models file, The only one I modified. from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import User class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError() if not username: raise ValueError() user = self.model(email=self.normalize_email(email), username=username) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): user = self.create_user(username=username, email=email, password=None) user.admin = True user.staff = True user.superuser = True user.save() return user class CustomUser(AbstractBaseUser): username = models.CharField(max_length=12, primary_key=True, unique=True) id = models.IntegerField(default=1) email = models.EmailField(max_length=255, blank=False, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email'] objects = MyUserManager() def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_superuser(self): return self.superuser @property def is_active(self): return self.active -
How to handle MigrationSchemaMissing Unable to create the django_migrations table (relation "django_migrations" already exists )
Our system has been facing some weird issues in production that I have not been able to figure out until recently. I added Sentry to the Django backend to send error reports and came across - a migration/database sync issue. The error occurs when the django python manage.py migrate (actually python manage.py migrate_schemas since we are using the django-tenant-schemas package) command is being executed. The error reads as such: Traceback (most recent call last): File "/backend/manage.py", line 21, in <module> main() File "/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django_tenants/management/commands/migrate_schemas.py", line 89, in handle executor.run_migrations(tenants=tenants) File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/standard.py", line 14, in run_migrations run_migrations(self.args, self.options, self.codename, schema_name, idx=idx, count=len(tenants)) File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/base.py", line 45, in run_migrations migration_recorder.ensure_schema() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 70, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (relation "django_migrations" already exists ) I have backups dating back 1 month but this issue must have occurred prior to those backups because they did not fix the issue. I have … -
Import "decouple" could not be resolvedPylancereportMissingImports even after retrying pip install python-decouple
How can I get off this <<<Import "decouple" could not be resolvedPylancereportMissingImports>>> even after retrying pip install python-decouple. Check the screenshot ! https://i.stack.imgur.com/6XOjd.png -
Django, store internal link in database
I want to save the internal URL (you can see in the picture below, the last input), and then access it from the code, so I will be able to change it from the admin panel, but it shows error like in image 2 -
Celery Worker Disconnects But Continues To Run Task
I have 8 workers in celery all running on different machines that run very long tasks (multiple hours) These tasks are able to be stopped with app.control.revoke(task_id, terminate=True) and are visible in app.control.instpect() What happens is that some order of events causes the workers to disconnect from RabbitMQ and are no longer visible within the app.control.instpect() method, but the underlying code continues to run within the worker. These tasks are also not able to be terminated. And what would cause something like this to happen? Is there a way to prevent this disconnect from happening? And what would cause something like this to happen? The worker is started with celery -A project worker -l info -P eventlet --concurrency 5 > /dev/null -
AttributeError: module Django.contrib.auth.views has no attributes
I am new to the django development. In my Django app useraccounts, I am creating blog site. However, when I went to run python manage.py makemigrations, I encounter the error: AttributeError: module Django.contrib.auth.views has no attribute 'login'. Don't know what to do . Here is my code: model.py from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) # kwargs--handle named arguments that you have not defined in advance. #reverse()--if you change the url in future then you can reference that url using reverse(urlname). #This looks through all URLs defined in your project for the URL defined with the name url_name and returns the actual URL def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post',related_name='comments',on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse("post_list") def __str__(self): return self.text views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from blog_app.models import Post, Comment from django.utils import timezone … -
Python for web development [closed]
I am newbie in development field. What do I need to know about python programming language to learn Django python for web dev backend. -
PyCharm CE: Django Unexpected expression syntax
I am doing the following code using PyCharm and Django and I'm getting the unexpected expression syntax error at the very end for ('products':products)) and I'm not sure why. from django.shortcuts import render from django.http import HttpResponse from .models import Product def admin_console(request): products = Product.objects.all() return render(request, 'products/products_page.html', ('products': products)) -
Writable Nested Serializers Error in POST - Invalid Pk - object does not exist
I’m working on writable nested serializers. I want to enter data containing 2 tables — request, and parts in one request. I was able to do serialization but as I try to POST a request, it sends me an error throwing that an object does not exist. Probably because parts has foreign key referencing to request. What could be the solution for this? # API - Response HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "parts": [ { "requestid": [ "Invalid pk \"ID0000001\" - object does not exist." ] } ] } #serializer.py class PartSerializer(serializers.ModelSerializer): class Meta: model = partsTable fields = '__all__' class RequestSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True, write_only=True) class Meta: model = requestTable fields = ['requestid', 'requeststatusid', 'requesterid', 'businessunitid', 'plantid', 'requestname', 'projectmanager', 'parts'] def create(self, validated_data): parts_data = validated_data.pop('parts') request = requestTable.objects.create(**validated_data) for part_data in parts_data: partsTable.objects.create(request=request, **part_data) return request # models.py class partsTable(models.Model): partsid = models.CharField(max_length=100, null=False, primary_key=True) validatorid = models.ForeignKey(userTable, on_delete=models.CASCADE) request = models.ForeignKey(requestTable, related_name='parts', on_delete=models.CASCADE) partsstatusid = models.ForeignKey(partsStatusTable, on_delete=models.CASCADE) userpartsid = models.CharField(max_length=40, null=True) class requestTable(models.Model): requestid = models.CharField(max_length=12,primary_key=True) requeststatusid = models.ForeignKey(requestStatusTable, on_delete=models.CASCADE) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) businessunitid = models.ForeignKey(businessUnitTable, on_delete=models.CASCADE) plantid = models.ForeignKey(plantTable, on_delete=models.CASCADE) requestname = models.CharField(max_length=100, null=False) projectmanager … -
Wagtail internationalization - add pages with other language
I followed the steps from the official wagtail documentation to add a mulit-lingual django-app. So far I got one Page which indicates the language english. I added german to the wagtail.locales and want to translate the english page into german but I didn't find any input or select to change the pages's language. Unforunatly I didn't found any example code on how to translate text. I tried packages like wagtail-localize but those are not compatible with the latest version (v4.0.2). -
in Django, does class based view is enough for CRUD and can do anything a "noraml view" can do?
I have found that class-based views can save time and effort and are more efficient than normal views however I have learned it In the scope of CRUD operation and I don't know if it can do more than this. my question is if class-based views can do anything so no need to create views in a regular way or if the regular way has some pros over class-based views? -
registration form methods in django custom user model
I am creating a custom user model for django.My question is When I create a user via the template form the methods (clean_user_name,clean_password2,clean_email) in RegistrationForm class in forms.py get automatically called when a user attempt to fill the form so why does that happen as for what I know only init method gets automatically called. models.py class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, user_name, password, **other_fields) def create_user(self, email, user_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user class UserBase(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) about = models.TextField(_( 'about'), max_length=500, blank=True) # Delivery details country = CountryField() phone_number = models.CharField(max_length=15, blank=True) postcode = models.CharField(max_length=12, blank=True) address_line_1 = models.CharField(max_length=150, blank=True) address_line_2 = models.CharField(max_length=150, blank=True) town_city = models.CharField(max_length=150, blank=True) # User Status is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
How to call class method in Django URLs path?
How to call class method in Django URLs path? I want to call data_display method inside DataLoad class. how can i call it in my URLs.py file? so when i hit the path then it will render to the data_display.html template. views.py class DataLoad: def __init__(self, save_path, name_of_file): self.save_path = save_path self.name_of_file = name_of_file def file_load(self): file_path = os.path.join(self.save_path, self.name_of_file+".html") return file_path def data_display(request,*args, **kwargs): df = pd.read_csv("/home/satyajit/Desktop/opensource/data/us_amz.csv", low_memory=False) json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'data': data} return render(request, "home/data_display.html", context) urls.py from apps.home.views import DataLoad data = DataLoad.data_display(request) urlpatterns = [ #path('data_display', DataLoad.as_view(), name='data_display'), path('data_display', data, name='data_display'), ] -
I cannot create the new user in django
I cannot create any new user from this method redirect is working and every thing is working but new user is not creating this id my view from urllib import response from django.shortcuts import redirect, render from .forms import RegisterForm from main.views import home # Create your views here. def register(request): form = RegisterForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect("home") else: form = RegisterForm() return render(request, "register.html", {"forms":form}) Forms.py from dataclasses import field from socket import fromshare from xml.parsers.expat import model from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username","email","password1","password2"] -
why 'ImproperlyConfigured ' by an id prefix in django serializer's fields= ('userid',) and not in fields='__all__'?
At the following code I get the 'ImproperlyConfigured' error, while with the uncommented line and won't. Why? class EigenBankRekeningSerializer(serializers.ModelSerializer): class Meta: model = EigenBankRekening fields = ( 'id' 'userid', 'aangemaakt', 'gewijzigd', 'naam', 'informatie', 'iban_prefix', 'bankrekening', 'valuta', 'eigen_gbr', 'zakelijke_rekening', 'oudedagsreserve', ) # fields = '__all__' Exception Value: Field name iduser is not valid for model EigenBankRekening. In views.py I've got a filter by userid, but why is it prefixed with id in the API? class EigenBankRekeningView(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = EigenBankRekeningSerializer queryset = EigenBankRekening.objects.all() def get_queryset(self, **kwargs): user_bank = EigenBankRekening.objects.filter(userid=self.request.user.id) return user_bank