Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django : which files are modified by migrate and makemigration?
I am having this issue of "django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username" on a brand new deployed django app. I have no prreviously existant database, i have no files in my "migrations" folder. But I had done previous migrate and makemigrations on the source files for the deployment. So i'm wondering which files are affected by migrate and makemigrations commands? I have deleted all the files in the migrations folder, but it seems some traces of a preceding user remain... If you could provide me with some hints on the files where a trace of a preceding user exist, it would help me a lot. -
Django Errno 30: Read-only file system deploying to Heroku
I consistently get the following error when Deploying my Django app to Heroku. Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/app/my-app/settings.py", line 292, in <module> django_heroku.settings(locals()) File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 93, in settings os.makedirs(config['STATIC_ROOT'], exist_ok=True) File "/app/.heroku/python/lib/python3.9/os.py", line 225, in makedirs mkdir(name, mode) OSError: [Errno 30] Read-only file system: '/staticfiles' I tried other solutions on SO such as this one with no luck. Here are the relevant versions and settings python==3.9.7 django==3.2.13 django-heroku==0.3.1 whitenoise==6.2.0 From settings.py: import os from decouple import config import django_heroku PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = "/static/" … -
Dajngo all migrations are doubled
I just started my django project and after running the migrations I was trying to create superuser. Then the error popped out that I have unapplied migrations (even though I just did it). When I checked the "showmigrations" it turned out that all the migrations are doubled. I have deleted migration file so does the db (because it was empty anyway). The problem has not disappeared. Does anyone know what may be the problem? admin [ ] 0001_initial 2 [ ] 0001_initial [ ] 0002_logentry_remove_auto_add 2 [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices [ ] 0003_logentry_add_action_flag_choices 2 auth [ ] 0001_initial 2 [ ] 0001_initial [ ] 0002_alter_permission_name_max_length 2 [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length 2 [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts 2 [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null 2 [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 2 [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages 2 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length 2 [ ] 0008_alter_user_username_max_length [ ] 0009_alter_user_last_name_max_length 2 [ ] 0009_alter_user_last_name_max_length [ ] 0010_alter_group_name_max_length 2 [ ] 0010_alter_group_name_max_length [ ] 0011_update_proxy_permissions 2 [ ] 0011_update_proxy_permissions [ ] 0012_alter_user_first_name_max_length [ ] 0012_alter_user_first_name_max_length 2 contenttypes [ ] 0001_initial 2 [ ] 0001_initial [ ] 0002_remove_content_type_name [ ] 0002_remove_content_type_name 2 sessions [ ] 0001_initial … -
Check for a list the elements of which all contain only whitespaces in HTML
I'm building an app in Flask. I'm extracting a variable items (which is a list) and displaying each of its elements in a separate cell. <tr> <th>Some heading</th> {% for item in items %} <td>{{ item }}</td> {% endfor %} </tr> However, some items lists only contain elements consisting of whitespaces only, for example: items = [' ', ' ', ' ', ' '] I want to check that this is NOT the case and create a table row only if at least one element of items contains more than whitespaces. {% if items %} doesn't help because the list has elements. Is there any other way? I don't know JavaScript, but I would be glad to look into that too if there is a way. -
Django - pass multiple HTML form inputs into a view
I have 3 form inputs that will be submitted when one master button is clicked to then be passed into a view as the request parameter. I would like to get the values of first_name, last_name and email inside my view using request.get(). When the button is clicked the values inside my form appear as None HTML: <div id="form_content"> <form action="" method="post"> <section class="form_inputs"> <label for="first_name">First Name:</label> <input type="text" id="first_name"> </section> <section class="form_inputs"> <label for="last_name">Last Name:</label> <input type="text" id="last_name"> </section> <section class="form_inputs"> <label for="email">Email:</label> <input type="text" id="email"> </section> <input type="submit" value="Submit"> </form> </div> views.py def home(request): form_response = request.GET.get("form_content") print(form_response) context = {"title": "Home"} return render(request, "myApp/home.html", context) -
Error during installing requirements.txt in Django (metadata generation failed)
I tried installing requirements.txt in Django. Virtual env is activated. This error is showing after I tried pip install -r requirements.txt After that I also tried to migrate but still not working. This is github fork I downloaded, it has a pickle file as well as its based on ML model. -
Django is redirecting me to sublime text and the last raises import error
Have chosen Sublime as core git editor. And now after every move I do in Django virtual project, i'm being redirecting to sublime text with such error: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" -
Django: how to save data to database in django when a condition is met?
i am writing a logic to allow user pay for items using thier debit card, the logic is working fine. Now i want to save some data to the database when the status=successful. When a user purchase a course i want to add the course and the user who purchased the course to a model that i have created called UserCourse. I have tried adding slug to the process_payment view that i created but it seems not to be working. I also have another view called payment_response that checks if a payment was success or not. How do i add the purchased course and the user that purchase the course in the db? views.py # The course detail view def course_details(request, course_slug): if request.user.is_authenticated: user = request.user course = Course.objects.get(slug=course_slug) @login_required def course_checkout(request, slug): course = Course.objects.get(slug=slug) user = request.user # form to get the student's name, email, amount of course if request.method == "POST": course = Course.objects.get(slug=slug) name = request.POST.get("name") email = request.POST.get("email") amount = request.POST.get("amount") return redirect(str(process_payment(name,email,amount, course))) else: pass # how to handle courses that are free if amount == 0: course = Course.objects.get(slug=slug) userCourse = UserCourse(user=user, course=course) userCourse.save() return redirect('course:course-content', course.slug) # View that processes the … -
Django-postgress: Partial Index on timestamp
Consider queryset = queryset.filter( Q(enabled=False) | Q(expires_at__isnull=False) & Q(expires_at__lte=timezone.now()) | ) I would like to have a partial index to support this query. AFAIK, this index will not be used during the execution of the above query because the value of timezone.now() changes. On the other hand, if I just index enabled that is also not useful because the query planner has to go through the second condition anyway. -
Heroku Deployment: Failed to load resource: the server responded with a status of 404 (Not Found)
I initially deployed my app successfully to heroku but then I edited some text and redeployed it to heroku yesterday only for the js file not to load completely. It tells me failed to load resource on the chrome developer console (It was built using next.js, django and postgresql). I have checked everything and can't seem to find the error, Please I'm really confused and would be some help? favourndubuisi.herokuapp.com -
How to serialize a model with many to maany relashionship?
I have this function in my model, def serialize(self): return { 'id': self.id, 'author': self.author.username, 'text': self.text, 'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"), 'likes': self.likes.all(), 'likes_number': len(self.likes.all()), } but likes is actualy a many to many relashionship with User. How can I serialize it to get something like this? def serialize(self): return { 'id': self.id, 'author': self.author.username, 'text': self.text, 'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"), 'likes': [ user1, user2, etc. ], } So that I can also get rid of the 'likes number' property. -
Handling images via REST API
I'm trying to create a REST API with django-rest-framework which will be handling a few things, the one being sending and receiving images from the frontend. I found this article which tries to explain the idea, but it uses class-based approach in its' views.py and ideally I'd like to stick to a function-based one as I've already done some work that way (not including JWT authorization) and I'd prefer it to stay. I have no clue how to make my backend legible of receiving and sending images, could you please try to provide me with some code snippets (or better yet, articles) on how to do so? Thanks in advance! One thing to mention is that ideally I want to have an endpoint which will handle creating a new object which will come with an image (a plant to be specific) and an endpoint which would handle updating (changing) the object's image. My models.py: class Plant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=150) date_added = models.DateField(auto_now_add=True) description = models.TextField() img = models.ImageField(blank=True, null=True, upload_to=upload_path) plant_species = models.CharField(max_length=150) last_watered = models.IntegerField(default=0) how_often = models.IntegerField(default=0) tracked=models.BooleanField(default=True) My views.py: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username return … -
Django is treating same field which are lowercase and upper case as 2 different entities
I am creating models in django and then entering data in admin panel class Song(models.Model): name = models.CharField(max_length=30,validators=[alphanumeric]).title() slug=models.SlugField(default="",blank=True,null=False,db_index=True) artist = models.CharField(max_length=30,validators=[alphanumeric]) genre = models.CharField(max_length=30,validators=[alphanumeric]) language = models.CharField(max_length=30,validators=[alphanumeric]) image = models.ImageField(null=True,blank=True) But the issue is when I am entering "AceHunter" or "acehunter" as artist it is treating as different artists although I want them as one.... Please can someone help me what error I am making? -
Efficient Way to Search Complex Database
I have a database with 2 data tables: Messages and Annotations. A summary of the models is below. Only the important fields are included. message text = models.CharField(max_length=250, blank=False) accepted_annotation = models.OneToOneField( to='Annotation', related_name='original_msg', on_delete=models.SET_DEFAULT, default=None, null=True ) ...other fields annotation message = models.ForeignKey(to=Message, on_delete=models.CASCADE) user = models.ForeignKey(to=User, to_field='username', on_delete=models.SET_NULL, null=True) text = models.CharField(max_length=249, blank=False) reviewed = models.BooleanField(default=False) ...other fields I would like to search by text and also by the other fields. The complication is that, depending on who requested the data, different information is returned for each message in the database. The following pieces of information determine what is returned: users privilege whether the annotation is marked as reviewed whether there is an accepted annotation whether the user made an annotation Therefore when I search by text, I can't simply search the message text because the logic may determine that an annotation should be displayed for this user instead with completely different text. Currently what I am doing is using prefetch and annotations on the queryset to run through the logic and populate a field called "text_to_search" for each message before sorting and filtering. However, these require subqueries and will be very slow once there are millions of … -
Django Paginator is not giving output
Hope you are doing great. So there is a projects page where there are different number of projects on that page. Currently I am displaying 3 projects per page. Now I want to display number of pages that I have right now. Like there are 9 projects so there should be 3 pages. But My paginator is not displaying any number button on the bottom of the page. Here is the code(Sorry For the bad English I tried my best to explain) View.PY def projects(request): page = request.GET.get('page') results = 3 paginator = Paginator(obj, results) try: obj = paginator.page(page) except PageNotAnInteger: page = 1 obj = paginator.page(page) except EmptyPage: page = paginator.num_pages obj = paginator.page(page) return render(request, 'projects/projects.html',{'list': obj}) Projects.html <div class="pagination"> <ul class="container"> <li><a href="#" class="btn btn--disabled">&#10094; Prev</a></li> {% for page in paginator.page_range %} <li><a href="?page={{page}}" class="btn btn--sub">{{ page }}</a></li> {% endfor %} <li><a href="#" class="btn">Next &#10095;</a></li> </ul> </div> Can you guys tell what could be the issue? -
how to filter columns for each in the same model in Django admin
I have a model called Product. I am using StackedInline to display ProductCostCalculator in my admin panel. The problem that I have is that I will have 20+ columns in my ProductCostCalculator model. Some columns from ProductCostCalculator are not needed in every item in the Product model so I want to exclude all columns that are not needed. I know that I could just put 0 or '-' as default and insert values in proper columns in the admin panel but I would like to make it more dynamic so the user echo will be adding calculator components will not have to do it manually. For example, I want to add 2 items to my Product model. Let's call them Item 1 and Item 2. In Item 1 I will need to insert values in field_1, field_2, and field_3. In Item 2 in my Product model, I will need to insert values only for field_3, field_4 and field_5. Question: How can I assign a column from ProductCostCalculator to an item in the Product model or how can I filter all columns that are not needed in the specific item in the Product model. I am not sure if something like … -
React - How to login a user through Django backend?
Backstory as a learning exercise, I first built a website using only Django; then, I learned React (still in the process) and I was moving the frontend part in it and using Django only as backend. I have them on 2 different addresses 127.0.0.1:3000 and 8000. Now, I created all sort of API where React can fetch and send data to Django in order to read and manipulate the DB, the Login it is mainly the only thing that I'm still missing. I think this is probably due to the fact that I let Django handle all the things for the login, doing minimal work. The situation So, at the moment, in Django the login works this way: settings.py: LOGIN_URL = '/users/login/' LOGIN_REDIRECT_URL = '/users/' url.py: path('login/', auth_views.LoginView.as_view(template_name='registration/user_login.html'), name='user_login'), user_login.html (shorted): {% block body %} {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% endif %} <form method="post"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> {% if next %} <input type="hidden" name="next" value="{{ next }}" /> {% else %} <input type="hidden" name="next" value="{% url 'registration:main_page' … -
AttributeError: 'RedisChannelLayer' object has no attribute 'group_disgard'
traceback File "/Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/channels/generic/websocket.py", line 238, in websocket_disconnect await self.disconnect(message["code"]) File "/Applications/MAMP/htdocs/canvas/src/zzd/zzd/notes/consumers.py", line 20, in disconnect await self.channel_layer.group_disgard( AttributeError: 'RedisChannelLayer' object has no attribute 'group_disgard' consumer class NoteConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['pk'] self.room_group_name = 'note_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name, ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_disgard( self.room_group_name, self.channel_name, ) async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'system_message', 'message': message, } ) async def system_message(self, event): # print(event) message = event['message'] await self.send(text_data=json.dumps({ 'message': message, })) versions (env) 🌹 python Python 3.7.11 (default, Jul 27 2021, 07:03:16) [Clang 10.0.0 ] :: Anaconda, Inc. on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> import channels >>> import asgiref >>> django.__version__ '3.2.8' >>> channels.__version__ '3.0.5' >>> asgiref.__version__ '3.3.4' config CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } Why the method is undefined, how can I dismiss the bug? -
django.db.utils.ProgrammingError: (1146, "Table 'main.socialaccount_socialapp_sites' doesn't exist")
I'm trying to implement Google Login on my Django production website. It works fine on development server, but on my production server, I face this issue after having run python manage.py migrate. I'm not sure what to do, I already tried deleting all the migrations and re-running makemigrations and migrate. -
Django: asynchronous service development through task list sharing
I am creating a web application with Django 3.1.0 and Python 3.8. This application requires the execution of a very long back-office operation and of which I am interested in knowing the percentage of progress. To do this, the server exposes two services: www.contoso.com/process_start: returns a string to indicate the id assigned to the task; www.contoso.com/process_status/taskid: returns a number from 0 to 1 to indicate the progress (as a taskid I use the id returned by the process_start call); To do this I have created the following Python class TASKS = dict() # list of tasks in progress class Task(): def __init__(self): id = get_uid() # generation of a random string TASKS[id] = self # added to the list of tasks in progress self.id = id self.percentage = 0.0 self.thread = Thread(name=self.id, target=self.execute) self.thread.start() @staticmethod def get_status(id: str) -> float: task = TASKS.get(id, None) return (1.0 if task == None else task.percentage) def execute(self) -> None: try: ... finally: TASKS.pop(self.id, None) # removal from the list of tasks in progress The first service creates the task like this: def post(self, request: Request) -> Response: task = TaskReslice() return Response(status=status.HTTP_200_OK, data=task.id) the second service returns the status of the task in … -
'datetime.timedelta' object has no attribute 'isoformat'
I am trying to annotate time field to sum the total time in a week in the following getting the above error class StaffWorkTimeSerializer(serializers.ModelSerializer): timestamp = serializers.DateTimeField(format="%d-%m-%Y", read_only=True) total = serializers.TimeField() work_time = serializers.TimeField(format="%H:%M:%S", read_only=True) user = UserSerializer2(many=False, read_only=True) class Meta: model = StaffWorkTime fields = ['id', 'timestamp', 'work_time', 'user', 'total'] class StaffWorkTimeSerializerView(generics.ListAPIView): model = StaffWorkTime serializer_class = StaffWorkTimeSerializer def get_queryset(self): week_start = datetime.date.today() - datetime.timedelta(days=datetime.date.today().weekday()) week_end = week_start + datetime.timedelta(days=6) queryset = StaffWorkTime.objects.filter(user_id=self.kwargs['pk'])\ .filter(timestamp__range=[week_start, week_end])\ .values(week=TruncWeek('timestamp'))\ .annotate(total=Sum('work_time')).order_by('timestamp') return queryset Any help is appreciated to solve the error. -
How could I add timestamps feature to my djangocms project for videos?
i' m trying to add a feature (like "key moments" on Youtube videos ) to my django-cms project but i couldn't find any idea on net. so, i need your helps. -
Using argparse.REMAINDER to get the rest of the parameters breaks my other parameters
So I have this piece of code which just takes my parameters. class InteractiveTenantOption(object): def add_arguments(self, parser): parser.add_argument("command") parser.add_argument( "-s", "--schema", dest="schema_name", help="specify tenant schema" ) parser.add_argument("command_args", nargs=argparse.REMAINDER) The command looks like this: class Command(InteractiveTenantOption, BaseCommand): requires_system_checks = [] help = "Wrapper around django commands for use with an individual tenant" def handle(self, command, schema_name, command_args, *args, **options): print(schema_name) tenant = self.get_tenant_from_options_or_interactive( schema_name=schema_name, **options ) connection.set_tenant(tenant) call_command(command, *command_args, *args, **options) the problem is that print(schema_name) returns None for every command. Before I added parser.add_argument("command_args", nargs=argparse.REMAINDER) that print was not returning None. For example, if I run: python manage.py tenant_command test_command -s demoproject print result before adding parser.add_argument("command_args", nargs=argparse.REMAINDER): demoproject print result after adding parser.add_argument("command_args", nargs=argparse.REMAINDER): None Why did it change and how can I fix it? Thanks. -
How to open postgres db and see the tables (Django+Postgres+Docker)
I start learning docker with Django+PostgreSQL, I did all steps from there https://docs.docker.com/samples/django/ How can I open created database on terminal or pgAdmin to see tables and change them? I use: Ubuntu 22.04 / Docker Engine 20.10.17 / Docker Compose version v2.6.1 / psycopg2-binary==2.9.3 / Django==4.0.6 / psql (13.7 (Ubuntu 13.7-1.pgdg22.04+1)) my docker-compose.yml: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } some info if needed, postgres file created are owned by root: postgres file 1/2 postgres file 2/2 Thanks for answers! -
Django convert image to webp
I have service in my Django project's app, that upload images, and I need to convert all images to webp to optimize further work with these files on the frontend side. Draft of _convert_to_webp method: # imports from pathlib import Path from django.core.files import temp as tempfile from django.core.files.uploadedfile import InMemoryUploadedFile from PIL import Image # some service class ... def _convert_to_webp(self, f_object: InMemoryUploadedFile): new_file_name = str(Path(f_object._name).with_suffix('.webp')) temp_file = tempfile.NamedTemporaryFile(suffix='.temp.webp') # FIXME: on other OS may cause FileNotFoundError with open(temp_file 'wb') as f: for line in f_object.file.readlines(): ... # will it works good? new_file = ... new_f_object = InMemoryUploadedFile( new_file, f_object.field_name, new_file_name, f_object.content_type, f_object.size, f_object.charset, f_object.content_type_extra ) return new_file_name, new_f_object ... f_object is InMemoryUploadedFile instance from POST request body (Django automatically create it). My idea is to create a temporary file, write data from f_object.file.readlines() to it, open this file with PIL.Image.open and save with format="webp". Is this idea a good one or there is another way to make file converting?