Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
[Dokcer]python3: can't open file '/app/manage.py': [Errno 2] No such file or directory
I'm new to docker, and I tried to run django on the docker container. However, after I ran the "docker-compose up -d" command the error python3: can't open file '/app/manage.py': [Errno 2] No such file or directory shows in docker. Since it seems that the code can be run successfully in mac os, I doubt if it is the problem of Windows11 which I run the file currently. My questions are: 1.Why the this error happens? 2.How I can fixed it? The dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ the docker-compose file version: '3' services: web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db I've tried to solve the problem for hours, but the solutions I searched did not work. Hope someone can help. Thank you very much!! -
Finding 2 values if available in a list in a Django Template
I have the following list called `` :[(2, 'Flat Bench'), (1, 'Flat Bench'), (3, 'Flat Bench')] I am trying to find if the b.order which is the first number and e.name which is the 2nd string is available from a django template. In my trial I made sure that b.order is equal to 2 and e.name is 'Flat Bench'. Here is the django template: {% if b.order and e.name in all_logs %} available {% else%} not available {% endif %} In my case there is no error, it is just always showing not available even if it is available. I am not sure what change I should be doing to get this code to work. -
How to populate a model's foreignkey field from another model instance's foreignkey field
I have the models: Recipe, Ingredient, and Cart. I'll have 2 types of Users: Cooks and Eaters. Cooks create Recipe posts and include the Ingredients for each Recipe. Ingredients are mapped to Products I want the Eaters, as they're on the recipe_detail.html, to have their Cart pre-populated with all the Products referenced in the Ingredient list associated with the Recipe currently being visited. Here's my code: #ingredients/models.py class Product(models.Model): name = models.CharField(max_length=255) class Ingredient(models.Model): recipe = models.ForeignKey(Recipe,on_delete=models.CASCADE, blank=True, related_name='ingredients') product = models.ForeignKey(Product,on_delete=models.CASCADE, blank=True) #cart/models.py class Cart(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='products') #cart/views.py class CartCreateView(CreateView): model = Cart template_name = "recipes/recipe_detail.html" form_class = CartModelForm def dispatch(self, request, *args, **kwargs): """ Overridden so we can make sure the `Recipe` instance exists before going any further. """ self.recipe = get_object_or_404(Recipe, pk=kwargs['Recipe_id']) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): """ Overridden to add the recipe relation to the `Ingredient` instance. """ ingredients = self.recipe.ingredient.all() form.instance.owner = self.request.user.pk form.instance.product = None # <---- The problem return super(CartCreateView, self).form_valid(form) #recipe_detail.html <!-- Recipe --> <div> <h2>{{ recipe.title }}</h2> <p>By: {{ recipe.owner }}</p> </div> <!-- Ingrediants --> <div> <h4>Ingrediant list:</h4> <ul> {% for ingrediant in recipe.ingrediants.all %} <li>{{ ingrediant }} {{ ingrediant.context }} {% … -
How to get values of a dictionary in a Django Template without for loop
I am trying to get a value of a dictionary in a Django Template. I am not sure whether this is possible or not. Here is the following template: {{ active_session.log.values }} This is the print out of it: <QuerySet [{'id': 318, 'log_order': 1, ......other repeated keys and values}> My question how can get all the values of the log_order with going through a for loop in the template knowing that it is a many to many relationship. Here is the models: class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') .................................. here is the views: class workout_details(DetailView): model = Workout template_name = 'my_gym/start_workout.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) p = Log.objects active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id) context = super().get_context_data(**kwargs) context['exercises'] = exercises context['form'] = LogForm() context['p'] = p context['active_session'] = active_session return context There are several answers out there saying that can create a function lookup but it got me an error Failed lookup for key [log_order] in <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x046FE4A8> Here is the function in the models: @register.filter(name='lookup') def lookup(value, arg): value_dict = ast.literal_eval(value) return value_dict.get(arg) Here is the template: {{ mydict|lookup:active_session.log.log_order }} -
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?