Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way in Django to specify a starting/first test?
My tests take a long time to run, and many times fixing one test often fixes multiple tests, so I often use --failfast to fix tests one by one in the order in which they error out. I fix a test, then rerun to find the next failure that wasn't due to the same root cause as the one I just fixed. The problem is that the tests take a long time to run and I have to wait through all the tests that I already know will pass. *I'm aware that code changes to fix one test could break a previously run/successful test, but I'd prefer to handle that in a second run. What I would like to do is specify a "starting test" so that I only run the tests from the previous failure forward. I don't see a way to do that using python manage.py test. Is there a trick to get it to not test previously run tests and just pick up where it left off? -
Django dev server does not start if noreload is not set
I'm encountering an issue when attempting to start the Django development server with runserver_plus from django-extensions When I initiate it with the following command: python backoffice/manage.py runserver_plus 0.0.0.0:8000 --noreload It starts successfully without any problems. However, if I use the following command instead python backoffice/manage.py runserver_plus 0.0.0.0:8000 Notice that if I not pass the --noreload flag, it returns the following error: backoffice/manage.py: [Errno 2] No such file or directory The command is being executed in the same place so it does not make sense why is not finding the manage file. Why does it only work when I include --noreload? Is there a way to make it work? I would like to use the reload capability to save time in development process. Thank you! -
Why am I getting Post method error while submitting form in Django?
This is the error which i m getting when trying to click on the submit button: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/contact/ Using the URLconf defined in career.urls, Django tried these URL patterns, in this order: admin/ myapp/ signup /contact ^media/(?P\<path\>.\*)$ The current path, contact/, didn’t match any of these. I am attaching my file code below: Contact.html: <div class="container my-3"> <h1>Contact Admin</h1> <form method="post" action="/contact"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" aria-describedby="name"> </div> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" name="email" id="email" aria- describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="phone">Phone Number</label> <input type="phone" class="form-control" name="phone" id="phone"> </div> <div class="form-group"> <label for="content">How may we help you?</label> <textarea class="form-control" name="content" id="content" cols="30" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> views.py: def contact(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] content = request.POST['content'] print(name, email, phone, content) contact.save() return render(request, "myapp/contact.html") models.py: class Contact(models.Model): sno = models.AutoField(primary_key=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=10) email = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.name admin.py: from django.contrib import admin from .models import\* admin.site.register(Careers) … -
Problem Configuring Static in OpenLiteSpeed with Django Project (www.menuweb.cl)
The problem. traditional-italian-food-world-tourism-day.jpg:1 - Failed to load resource: the server responded with a status of 404 /#:1 - Refused to apply style from 'https://menuweb.cl/python/static/main/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I'm trying to set up a Django project on OpenLiteSpeed and am facing some challenges in properly configuring the static files.Based on the user manual's recommendations, I've set STATIC_URL and STATIC_ROOT in my settings.py as follows: STATIC_URL = '/python/static/' STATIC_ROOT = '/usr/local/lsws/Example/html/growpyme/static' Here's my directory structure: /usr/local/lsws/Example/html/ growpyme/ staticfiles/ main/ static/ carta/ static/ growpyme/ static/ If anyone has previously configured Django static files in OpenLiteSpeed and can offer guidance, it would be greatly appreciated. Thank you in advance! <!DOCTYPE html> <html lang="es"> <head> {% load static %} <meta charset="UTF-8"> <title>App Menu Web</title> <!-- Incluir Bootstrap CSS y JS usando un CDN para mejor compatibilidad --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Vincula tus hojas de estilo CSS --> <link rel="stylesheet" type="text/css" href="{% static 'main/home.css' %}"> <!-- Vincula tus librerías o frameworks JS --> <script src="{% static 'jquery.js' %}"></script> <link href="https://fonts.googleapis.com/css2?f...0&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet"> </head> -
I can't install ebcli with Python 3.11.4 | AttributeError: cython_sources | Getting requirements to build wheel did not run successfully
When I try to install ebcli using Python 3.11.4 (inside a venv, as per the official instructions)I get an error and I just can't get around it. If I try to install ebcli using Python 3.8.10(again inside a venv, but this time the 3.8.10 version), it does work. The error looks like this: File "/tmp/pip-build-env-yn_umd7x/overlay/lib/python3.11/site-packages/setuptools/_distutils/command/sdist.py", line 336, in _add_defaults_ext self.filelist.extend(build_ext.get_source_files()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<string>", line 201, in get_source_files File "/tmp/pip-build-env-yn_umd7x/overlay/lib/python3.11/site-packages/setuptools/_distutils/cmd.py", line 107, in __getattr__ raise AttributeError(attr) AttributeError: cython_sources [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. I already followed the troubleshooting recommendations, which consists on installing dependencies, and it didn't have any effect. I already googled for this specific issue and I can't find a solution. I did find this issue containing AttributeError: cython_sources which might be related, but I don't know what action to take from there. -
Add prefix to router while still showing it in API root view
To simplify my question, I have a Django project with two apps: devices and pins with the following urls.py: # devices/urls.py router = routers.DefaultRouter() router.register(r'relays', api_views.RelayViewSet) router.register(r'ultrasonic_sensors', api_views.UltrasonicSensorViewSet) router.register(r'contact_sensors', api_views.ContactSensorViewSet) ... urlpatterns = [ path('', include(router.urls)), ] # pins/urls.py router = routers.DefaultRouter() router.register(r'pins', api_views.PinViewSet) urlpatterns = [ path('', include(router.urls)), ] and the main project's urls.py looks like this: from devices.urls import router as devices_router from pins.urls import router as pins_router urlpatterns = [ path('', include(pins_router.urls)), path('devices/', include(devices_router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Question: I want to "group" or prefix all device_router urls with /devices/ while still showing it on the root API view. Currently, I can view /devices/relays/<pk>, however it is not shown in the root API view of DRF. Current result: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "pins": "http://pinode:8000/pins/" } Required result: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "pins": "http://pinode:8000/pins/", "devices": "http://pinode:8000/devices/" } Where http://pinode:8000/devices/ shows the following: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "relays": "http://pinode:8000/devices/relays/", "ultrasonic_sensors": "http://pinode:8000/devices/ultrasonic_sensors/", "contact_sensors": "http://pinode:8000/devices/contact_sensors/", } -
Update / edit post with multiple images in django
I am working to create a social network with django and I want to update a post that contains multiple images. So far, I can create a post with images by using 2 model Post and Images. This is my update function for now, I copy it form my create_post function: def update_post(request, pk): if request.method == 'GET': post = Post.objects.get(pk=pk) post_form = PostModelForm(post.content) if request.method == 'POST': print('dude u call me') postForm = PostModelForm(request.POST) profile = Profile.objects.get(user=request.user) images = request.FILES.getlist('images') if postForm.is_valid(): post_form = postForm.save(commit=False) post_form.author = profile post_form.save() for image in images: photo = Images(post=post_form, image=image) photo.save() messages.success(request, "Yeeew, check it out on the home page!") return HttpResponseRedirect("/") else: print(postForm.errors) return HttpResponseRedirect("/") Update template <div class='ui segment'> <h3>Update post</h3> <form action="" method="POST" class="ui form" enctype="multipart/form-data"> {% csrf_token %} {{form}} <button type='submit' class="ui button primary mt-5">Update</button> </form> </div> Post model form class PostModelForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'rows': 2})) class Meta: model = Post fields = ('content', ) Images model class Images(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='posts', verbose_name='Image', validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])], blank=True) Post model class Post(models.Model): content = models.TextField() liked = models.ManyToManyField(Profile, blank=True, related_name='likes') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='posts') My create template … -
How to get cognito user pool's custom attributes from access token? it shows only user attrs why?
def lambda_handler(event, context): if event["httpMethod"] == "GET": print('Event_Auth:', event) headers = event['headers'] access_token = headers.get('Authorization') if access_token: pieces = access_token.split() if len(pieces) == 2 and pieces[0].lower() == 'bearer': access_token = pieces[1] print('Without Bearer:', access_token) is_valid = validate_token(access_token) def validate_token(access_token): try response = cognito.get_user(AccessToken=access_token) if response['Username']: print('Response:', response) print('Cognito Username:', response['Username']) return True except: return False This is my lambda handler, what we are using? we have an authroizer in api-gateway which triggers a lambda function and obtain an Access Token... i have an intermediate knowlodge about aws. Problem: We haved added custom attrs in coginto user pool, and we need these attrs to build SaaS which is very much important for us. So, what is happening now, we are unable to retrieve custom attrs of user pool in the event because custom attrs doesn't exist in event, but user attrs are in the event, then why custom doesn't exists in the event? What will be the solution for that, kindly let me know we stuck there from last couple of days? ` Response: {'Username': 'XXXXXXX', 'UserAttributes': [{'Name': 'sub', 'Value': 'ca2ae0ae-XXXXX-XXXXX'}, {'Name': 'email_verified', 'Value': 'true'}, {'Name': 'email', 'Value': 'example@email.com'}], 'ResponseMetadata': {'RequestId': '87314820-7141-4089-a92c-XXXXXXXXXXXX', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Wed, 09 Aug 2023 12:04:57 … -
Django data table load thousands of rows using server side AJAX
I have already created a data table that is working just fine. The only problem is that because there are thousands of rows it takes quite a while to load. Below is my code view def live_equity_balance_original(request): if request.method == 'POST': mt4_checked = 'mt4' in request.POST.getlist('platform') mt5_checked = 'mt5' in request.POST.getlist('platform') ctrader_checked = 'ctrader' in request.POST.getlist('platform') platforms = [var_name for var_name, var_value in [('mt4', mt4_checked), ('mt5', mt5_checked), ('ctr', ctrader_checked)] if var_value] variable_names = { 'mt4': 'balance_equity_mt4_query', 'mt5': 'balance_equity_mt5_query', 'ctr': 'balance_equity_ctr_query' } for platform in platforms: if platform in variable_names: module_name = 'queries.queries' variable_name = variable_names[platform] module = importlib.import_module(module_name) balance_equity_query = getattr(module, variable_name) if platform == 'mt4': df = my_library.get_mt4_data(balance_equity_query) df = df.loc[df.login.astype(str).str.len() > 5] exclude_strings = ['MANAGER','tEsT','COVER'] df = df[~df['group'].str.contains('|'.join(exclude_strings),case=False)] df = df.loc[(df['balance']!=0)|(df['equity']!=0)] df = df.head(100) headers = df.columns json_records = df.reset_index(drop=True).to_json(orient ='records') data = json.loads(json_records) context = {'headers': headers,'data': data} return render(request, 'live_equity_balance.html', context) table.html template {% load custom_filters %} <div class="container"> <br><br><br> <table class="table row-border cell-border display compact" id="example" style="text-align: center;"> <thead class="table-success"> <tr> {% for header in headers %} <th>{{ header }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in data %} <tr> {% for header in headers %} <td>{{ item|get_value:header }}</td> {% endfor %} … -
Function does not return http 400 request
queryset = WaitingForParticipationInEvent.objects.all() serializer_class = WaitingForParticipationInEventSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): instance = serializer.save() if `ParticipationInEvents`.objects.filter(user=instance.user, event=instance.event).exists(): print(5551) print(ParticipationInEvents.objects.filter(user=instance.user, event=instance.event).exists()) return Response({"message": "User already in event"}, status=status.HTTP_400_BAD_REQUEST) else: waiting_serializer = WaitingForParticipationInEventSerializer(data={'url': instance.url, 'id': instance.id, 'username': instance.username,'first_name': instance.first_name, 'read': instance.read, 'user': instance.user, 'event': instance.event}) if waiting_serializer.is_valid(): waiting_serializer.save() print(555) return Response({"detail": "Допущено: Объект успешно создан в ModelA."}, status=status.HTTP_201_CREATED) return Response(waiting_serializer.errors, status=status.HTTP_400_BAD_REQUEST) There is my model viewset, when I am creating WaitingForParticipationInEvent object I need to check an existence of ParticipationInEvents object with the same user and event, if exists I return bad request, if does not I create the object. Butyour text it does not return bad requеst though print(5551) works. Help pls -
Django different 404 Errors on Production
I have product pages and tag pages on my website. For the product query, I use the code: product = get_object_or_404(Product, slug=slug), and for the Tag query, I use: tag = get_object_or_404(Tag, slug=slug). When running my code on my local machine with DEBUG set to True, I encounter a Django error page with a 404 status code. However, in my production environment, I experience different behaviors for the two types of pages. For tag pages, like https://my.domain/tag/abrakadabra/, I correctly receive a 404 error page. However, for product pages, like https://my.domain/product/abrakadabra/, I encounter an internal server error instead of the expected 404 error page. Interestingly, when I set DEBUG to True on my production server, I do receive the correct 404 Django error page for both tag and product pages. -
Migrating from SQLITE to postgreSQL in django raises " can't adapt type 'CharField'"
I'm using Django 4.1.10 and i'm trying to migrate from sqlite to postgresql but when I try to execute de migration files or dump data from manage.py i get this error django.db.utils.ProgrammingError: can't adapt type 'CharField' It happens both whe using python.exe manage.py migrate and python.exe manage.py dumpdata > datadump.json Is there any restriction related to datatypes? -
How to show Django static file on windows 10 IIS
I'm trying to deploy Django app on windows 10 iis my app is working fine but Django static file not serve. Here my setting which is I'm configure on windows 10 IIS Server **Web config ** <appSettings> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="E:\django\crm\crm\crm" /> <add key="DJANGO_SETTINGS_MODULE" value="crm.settings" /> </appSettings> <system.webServer> <handlers> <remove name="crm" /> <add name="crm" path="*" verb="*" modules="FastCgiModule" scriptProcessor="E:\django\crm\crm\crm\env\Scripts\python.exe|E:\django\crm\crm\crm\env\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> </configuration> Add Website FASTCGI Setting Handler Mapping Setting Py """ Django settings for crm project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d)et0_8*dvb(x9fytai2_2zz(*37vfm*1617*8ajyftycu@a49' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['192.168.11.59','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', 'dbbackup', ] DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage' DBBACKUP_STORAGE_OPTIONS = {'location': BASE_DIR / 'backup'} MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
The current path, admin/, didn’t match any of these
My django project does not find the admin path, when I try to access it. My project URLs are as follow: from myapp.views import UserView from django.contrib import admin urlpatterns = UrlPattern() urlpatterns.register(UserView) urlpatterns += [path('', include('myapp.urls'))] urlpatterns += [path('admin/', admin.site.urls)] the error I get when try to access: 127.0.0.1:8000/admin/ The current path, admin/, didn’t match any of these. -
Django stuck after doing code change (hot reload not working)
I upgraded my Django version from 3.2.15 to 4.2.1 and also my Python version from 3.7.13 to 3.11.0 and the hot reload of my Django project stopped working. The server starts as expected with the pipenv run python src/manage.py runserver {host}:{port} command, but when I do a code change and save the file the server gets stuck saying: [INFO] [django]: /my-route/my-file.py changed, reloading And I have to kill the process on the console and start it again to make it work. When I had my old dependencies, after saving a file the server just reloaded and it showed the changes. I tried to set the verbosity to 3, but I can't get any information explaining the error and I don't know how to debug it. It looks like it uses StatReloader to detect this file changes: [INFO] [django]: Watching for file changes with StatReloader gets printed before starting the server. I would really appreciate it if you can give me some help or direction to follow about this topic. Thanks in advance! -
Foreign key issue : (3780, "Referencing column 'user_id' and referenced column 'id' in foreign key constraint)
In my django website I have a user model : from django.contrib.auth.models import AbstractUser class User(AbstractUser): class Meta: app_label = "myapp" The issue is when I try to create a simple other model referencing to the User model : class TestTable(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) value = models.FloatField() I get this error when trying to migrate after makemigrations : (3780, "Referencing column 'user_id' and referenced column 'id' in foreign key constraint I think the issue is about the type of the "id" in user table and "user_id" in test table, when I describe the tables with SQL commands I get this : mysql> describe myapp_user; +--------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | password | varchar(128) | NO | | NULL | | | last_login | datetime(6) | YES | | NULL | | | is_superuser | tinyint(1) | NO | | NULL | | | username | varchar(150) | NO | UNI | NULL | | | first_name | varchar(150) | NO | | NULL | | | last_name | varchar(150) | NO | | NULL | | … -
Django Email Incorrect Accent Characters
I'm facing an issue with sending emails using Django where the accent characters are not rendered correctly. ** Problem:** When I send an email containing accent characters (e.g., é, à, ü), they SOMETIMES appear incorrectly in the received email. Instead of the correct character, I see a different symbol/letter. I'm using Django, in particular Celery do send the emails. Here is my code: Template: {% extends 'general/mail_header_and_footer.html' %} {% load settings %} {% load i18n %} {% block title %}{{ title }}{% endblock %} {% block description %} <p>Ciao {{ customer_name }},</p> <p> The booking for {{ experience_variant_name }} is not available for {{ starting_time|time:'H:i' }} of {% language 'it' %} {{ starting_date|date:'l, d F Y' }} {% endlanguage %}. </p> Python: email = EmailMessage( subject=subject, body=message, from_email=DEFAULT_FROM_EMAIL, to=[booking.customer_email], bcc=MANAGERS_EMAILS, headers={"Content-Type": "text/html; charset=UTF-8"}, ) email.content_subtype = "html" email.send() settings.py: EMAIL_CHARSET = "utf-8" And I'm using sendgrid. -
i have some questions about full-stack with django
I learned Python and I plan to become a web developer, but I don't know if it is better to become full stack or back end. I know Django is good for Python. Is it good to learn the backend first? This is the road map I decided to follow, do you approve? https://github.com/HHHMHA/django-roadmap -
Issue with accessing form.cleaned_data in Django view function
I'm encountering an unexpected issue while working on a Django project involving a registration form. I have two code snippets that are functionally similar, but I'm getting different outcomes regarding the access to form.cleaned_data. I'm hoping someone can help me figure out what might be causing this discrepancy. Code Snippet 1: def signup(req): if req.method == 'POST': form = RegisterForm(req.POST) if form.is_valid(): messages.success(req, 'Account Created successfully') form.save() print(form.cleaned_data) return render(req, 'signup.html', {'form': form}) else: form = RegisterForm() return render(req, 'signup.html', {'form': form}) Code Snippet 2: def signup(req): if req.method == 'POST': form = RegisterForm(req.POST) if form.is_valid(): messages.success(req, 'Account Created successfully') form.save() print(form.cleaned_data) return render(req, 'signup.html', {'form': form}) form = RegisterForm() return render(req, 'signup.html', {'form': form}) In both snippets, the form is submitted and processed similarly. However, when I use the first snippet, I can successfully access form.cleaned_data and print it after a successful form submission. But when I use the second snippet, form.cleaned_data seems to be unavailable, and the printed output is empty. I have double-checked the code for any typos or missed details, but both snippets are practically identical. I'm quite puzzled as to why this difference in behavior is occurring. -
css files are blocked when I am using production mode with Django
I have a django app. And I try to simulate production envrionment. So I have splitted the settings in three seperate files: local , prod and base. Part of the base.py looks like: import os from pathlib import Path from os import environ from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG') == "False" STATIC_URL = '/static/' STATIC_DIRS = [ (BASE_DIR, 'static') ] STATIC_ROOT = BASE_DIR /'staticfiles' STATICFILES_DIRS =['DierenWelzijn'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR /'media' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = BASE_DIR/'media' MEDIA_URL = '/media/' And the manage.py file looks like: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys from DierenWelzijn.settings import base def main(): """Run administrative tasks.""" if base.DEBUG: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.local') else: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.production') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your … -
Display multiple images in one post content on social media
I'm making a social network website with django, html, css, jquery. I already can upload images to database and display it in my post but I want to organize it a little bit just like this. How can I do that with html and css? -
Why in Django many-to-many relation shows wrong data in the admin panel
I'm trying to implement the many-to-many relation to support in the user model these features: user followers (persons who follows the user) user following (persons the user follows) To achieve that I'm using double relation on the same model because followers/following are the same User models. Basically it works hoverwer I'm facing a weird behavior in the Django admin panel. When I add some user to other user to the following list (in the shell everything ok), the Django admin panel shows that user in the followers list but he should be in the following list. I can't understand why it happens. Many thanks for any help! My models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): followers = models.ManyToManyField('self',blank=True,related_name='user_followers',symmetrical=False) following = models.ManyToManyField('self',blank=True,related_name='user_following',symmetrical=False) pass Supppose Admin wants to follow Neo. Neo should have follower - Admin. Admin - should have Neo in his following list. Shell commands and result: admin = User.objects.filter(username='admin')[0] neo = User.objects.filter(username='neo_anderson')[0] // check that everything is empty neo.user_following.all() <QuerySet []> neo.user_followers.all() <QuerySet []> // --- admin wants to follow neo --- // add the admin to the neo followers neo.user_followers.add(admin) neo.save() // add the neo to the admin following admin.user_following.add(neo) admin.save() // check if … -
How to declare user_id on ModelViewSet in DjangoRestFramework
Foreignkey root is User> Comparelist > obj I don't know what's wrong with my code. Error message said me comparelist required user_id accounts> models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import UserManager from core.models import TimestampedModel class User(AbstractBaseUser, PermissionsMixin, TimestampedModel): email = models.EmailField(max_length=30, unique=True, null=False, blank=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' accounts> serializers.py from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' def create(self, validated_data): user = User.objects.create_user( email = validated_data['email'], password = validated_data['password'] ) return user ImageConverters> models.py from django.db import models from accounts.models import User class CompareList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) class Obj(models.Model): comparelist = models.ForeignKey(CompareList, on_delete=models.CASCADE) object_name = models.CharField(max_length=100) image = models.URLField(max_length=500) ImageConverters> serializers.py from .models import CompareList, Obj from rest_framework import serializers class ObjSerializer(serializers.ModelSerializer): class Meta: model = Obj fields = ['object_name', 'image'] class CompareListSerializer(serializers.ModelSerializer): objs = ObjSerializer(many=True, read_only=True) class Meta: model = CompareList fields = ['id', 'objs'] def create(self, validated_data): # print(dir(self)) print(self) print('------------------') images_data = self.context['request'].FILES texts_data = self.context['request'].data comparelist = CompareList.objects.create(**validated_data) print(texts_data) for image_data, text_data in … -
Django on_delete for Model with custom delete function
I have the following models: class Concert(models.Model): name = models.CharField(max_length=255) is_deleted = models.BoolField(default=False) def delete(self): self.is_deleted = True self.save() class Ticket(models.Model): concert = models.ForeignKey(Concert, on_delete=models.CASCADE) is_deleted = models.BoolField(default=False) def delete(self): self.is_deleted = True self.save() I noticed when I call delete on Concert, it doesn't call delete on Ticket. This is expected behavior, right? Is there any way to trigger CASCADE even in the case of this custom delete function? -
Google Ads API & Python - How to get all accounts (name + ID) that a user has access
I'm trying to get the account name and ID of all the accounts that the logged user has access to. I've managed to get the IDs using the code on https://developers.google.com/google-ads/api/docs/account-management/listing-accounts?hl=es-419. But I need the names too and apparently you have to make one API call for each ID to get their account names or any other info. I've tried with the following Python (Django) code, but it's not working (it probably could be improved a lot and maybe has mistakes, I'm a Python beginner): def one(request): client = credenciales(request) ga_service = client.get_service("GoogleAdsService") # Get customer resource names from the original code customer_service = client.get_service("CustomerService") accessible_customers = customer_service.list_accessible_customers() customer_resource_names = accessible_customers.resource_names # Prepare a list to store customer data list_clients = [] # Iterate through each customer resource name for resource_name in customer_resource_names: # Extract the customer ID from the resource name custom_id = resource_name.split('/')[-1] # Create a query using the customer_id query = f''' SELECT customer_client.descriptive_name, customer_client.id, customer_client.status FROM customer_client ''' stream = ga_service.search_stream(customer_id=custom_id, query=query) for batch in stream: for row in batch.results: data_clients = {} data_clients["descriptive_name"] = row.customer_client.descriptive_name data_clients["id"] = row.customer_client.id data_clients["status"] = row.customer_client.status list_clients.append(data_clients) # Pass the list of customer data to the template context = { …