Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django deployment error when using waitress
I am trying to deploy my django project in heroku but i am facing some error when i try to use waitress module this link wont lead to anything what to do -
NOT NULL constraint failed: registration_registration_customuser.user_id
I am trying to register a user for the first time but I am getting a IntegrityError. Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: registration_registration_customuser.user_id when I am trying to create a superuser it is asking me for a user id for which i have to only enter a integer value but it is not accepting any value PS C:\Users\HP\Downloads\E_Authentication_System-master (1)\E_Authentication_System-master> python3 manage.py createsuperuser Username: HP User (registration_customuser.id): 1 Error: user instance with id 1 does not exist. User (registration_customuser.id): 2 Error: user instance with id 2 does not exist. User (registration_customuser.id): and I also can't leave it blank either models.py class registration_customuser(AbstractUser): REQUIRED_FIELDS =['user'] USERNAME_FIELD = ('username') user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, default=None,blank=True, null=True, editable=False) password =models.CharField(max_length=128, verbose_name='password') last_login = models.DateTimeField(blank=True, null=True, verbose_name='last login') username = models.CharField(max_length=200, unique=True) fullname = models.CharField(max_length=254) email = models.EmailField(max_length=254,unique=True) mobile = models.CharField(max_length=12,unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) @property def is_anonymous(self): return False @property def is_authenticated(self): return True admin.py from django.contrib import admin from .models import registration_customuser admin.site.register(registration_customuser) views.py from django.shortcuts import render,redirect from django.urls import reverse from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.models import auth from random import randint from django.core.mail import EmailMessage from sms import send_sms from django.conf import … -
Django HTML to pdf not displaying when for loop longer than 1 page
Note: The html renders to pdf perfectly when the objected passed to the pdf function does not exceed the size of one page. Funnily enough when i remove the styling from the html it works, and by works i mean renders to pdf and create multiple pages... but now obviously without styling! HTML CODE {% load static %} @page { size: A4; margin: 1cm; @frame header_frame { /* Static frame */ -pdf-frame-content: header_content; left: 50pt; width: 512pt; top: 20pt; height: 40pt; } @frame col1_frame { /* Content frame 1 */ -pdf-frame-content: left_content; left: 44pt; width: 245pt; top: 90pt; height: 632pt; } @frame col2_frame { /* Content frame 2 */ -pdf-frame-content: right_content; left: 323pt; width: 245pt; top: 90pt; height: 632pt; } @frame row_frame { /* Content frame 2 */ -pdf-frame-content: table_content; left: 260pt; width: 500pt; top: 270pt; right: 323pt; } @frame { /* Content frame 2 */ -pdf-frame-content: middle_content; left: 50pt; width: 500pt; top: 300pt; right: 323pt; } @frame footer_frame { /* Static frame */ -pdf-frame-content: footer_content; left: 50pt; width: 512pt; top: 772pt; height: 20pt; } @frame footer { -pdf-frame-content: footerContent; bottom: 0cm; margin-left: 10cm; margin-right: 10cm; height: 1cm; } } .page-break{ page-break-after: always; } </head> <body> <div class="container-fluid"> <div id="header_content" … -
Django Models : array of fields
I need a form with 'hundreds' of integer input fields. I was thinking to create an array of integer fields in my model, but this doesn't seem to function: class Array(models.Model): name=models.CharField(max_length=10) data=[] for i in range(100): data.append(models.IntegerField(default=0,blank=True)) Via de shell I can create a record, change a data field and store... from app1.models import Array a=Array(name='first') a.data[0]=10 a.save() but retrieving later doesn't function: I get only <django.db.models.fields.IntegerField> but no actual values... I know about the ArrayField in postgres, but I just use SQLite... Any smarter way than creating 100 individual IntegerFields? -
Django DRF bulk_update primary key
I have used the example from the docs for implementing bulk update: class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping: book.delete() return ret class BookSerializer(serializers.Serializer): # We need to identify elements in the list using their primary key, # so use a writable field here, rather than the default which would be read-only. id = serializers.IntegerField() ... class Meta: list_serializer_class = BookListSerializer https://www.django-rest-framework.org/api-guide/serializers/#listserializer When I try to use this and update a row, I get an error: duplicate key value violates unique constraint \"api_book_pkey\"\nDETAIL: Key (id)=(7) already exists.\n" So it seems like it is not trying to update, rather than creating a new one with the same id. But for me it looks like it is really calling child.update. What is wrong here? -
How to serve media files with control traffic?
I need to serve protected files to users limit by user download quota (for each user). So, I must to calculate every file download. It's easy if I use HttpResponse() for serve files, but it is not efficient and very slow. How do I control every media file download using NGINX server for serve media? Is there any way? -
how to add multiple many to many fields referencing the same table in django
I have a "Film" model in Django and a "Celebrity" Model also. I want to add the celebrity model to the film model as a manytomany field 3 times. once as an actor, once as a director and once as a producer something like this: filmActor = models.ManyToManyField(Celebrity) filmDirector = models.ManyToManyField(Celebrity) filmProducer = models.ManyToManyField(Celebrity) but django doesnt allow me to do so giving me the following error: ERRORS: Core.Film.filmActor: (fields.E304) Reverse accessor for 'Core.Film.filmActor' clashes with reverse accessor for 'Core.Film.filmDirector'. HINT: Add or change a related_name argument to the definition for 'Core.Film.filmActor' or 'Core.Film.filmDirector'. Core.Film.filmActor: (fields.E304) Reverse accessor for 'Core.Film.filmActor' clashes with reverse accessor for 'Core.Film.filmProducer'. HINT: Add or change a related_name argument to the definition for 'Core.Film.filmActor' or 'Core.Film.filmProducer'. Core.Film.filmDirector: (fields.E304) Reverse accessor for 'Core.Film.filmDirector' clashes with reverse accessor for 'Core.Film.filmActor'. HINT: Add or change a related_name argument to the definition for 'Core.Film.filmDirector' or 'Core.Film.filmActor'. Core.Film.filmDirector: (fields.E304) Reverse accessor for 'Core.Film.filmDirector' clashes with reverse accessor for 'Core.Film.filmProducer'. HINT: Add or change a related_name argument to the definition for 'Core.Film.filmDirector' or 'Core.Film.filmProducer'. Core.Film.filmProducer: (fields.E304) Reverse accessor for 'Core.Film.filmProducer' clashes with reverse accessor for 'Core.Film.filmActor'. HINT: Add or change a related_name argument to the definition for 'Core.Film.filmProducer' or 'Core.Film.filmActor'. Core.Film.filmProducer: (fields.E304) … -
how to achieve aggregate average in multiple columns in pandas data frame
I have this below data frame Now given a particular holding_date range , I need the average of the columns grouped by the ticker i.e. I am completely new to pandas data frame , kindly help in sorting this out. Note: the actual data frame is generated from Django table , so Django ORM query is also welcomed -
How do i get the reverse relation sum of each queryset for ListView?
How many votes did the story get? What should I do to see this in ListView? And how can I do this without getting stuck with the n+1 problem? models.py class Story(models.Model): author = models.ForeignKey( MyUser, on_delete=models.CASCADE, related_name='story' ) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) content = models.TextField(max_length=2500, default='') draft = models.BooleanField(default=True) completed = models.BooleanField(default=False) expiration = models.DateTimeField(default=timezone.now()+timezone.timedelta(days=1)) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] indexes = [models.Index(fields=['draft', 'completed']),] def __str__(self): return self.title def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) for slug_id in itertools.count(1): if not Story.objects.filter(slug=self.slug).exists(): break self.slug = f'{self.slug}-{slug_id}' return super(Story, self).save(*args, **kwargs) def get_absoulte_url(self): return reverse('story:detail-story', kwargs={'slug': self.slug}) class Rating(models.Model): story = models.ForeignKey( Story, on_delete=models.CASCADE, related_name='rating' ) user = models.ForeignKey( MyUser, on_delete=models.CASCADE, related_name='rating' ) rate = models.SmallIntegerField(validators=[MinValueValidator(-1), MaxValueValidator(1)], default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: constraints = [ models.UniqueConstraint( fields=['story', 'user'], name='rating validation' ) ] def __str__(self): return f'{self.created_at}' views.py class IndexListView(ListView): model = Story context_object_name = 'stories' template_name = 'story/index.html' paginate_by = 10 queryset = Story.objects.select_related('author').filter(completed=False, draft=False) I want this: The number of votes will appear next to each story on the listing page. I did this using template tag. However, when I check with django-debug-toolbar … -
module 'website.management.commands.updatemodels' has no attribute 'Command'
I am finding a problem while executing this code on my app 'website' using django https://i.stack.imgur.com/rr15N.jpg https://i.stack.imgur.com/LWMP6.jpg -
Working with multiprocessing and Celery tasks
I'm working on a web scraping project in Django. The goal is to scrape advertisement data from 3 websites, create each advertisement as model object, and list them in a view. I've got four scraping functions, for which I've used multiprocessing module in order to run all of them at the same time. All of these functions are ran in this function: @shared_task def run(): ad_list = [] running_tasks = [Process(target=task, args=[ad_list]) for task in [scrape_lento_flats, scrape_lento_houses, scrape_morizon, scrape_gethome]] for running_task in running_tasks: running_task.start() for running_task in running_tasks: running_task.join() return save(ad_list) and then the result is saved: @shared_task(serializer='json') def save(ad_list): for ad in ad_list: location = Location.save( name = ad['location'] ) type = OfferType.save( id = OfferType.types[0] if ad['type'] == 'for sale' else OfferType.types[1] ) category = Category.save( name = ad['type'] ) Advertisement.objects.create( title = ad['title'], description = ad['description'], price = ad['price'], source = ad['source'], url = ad['source_url'], location = location, type = type, category = category, photo_url = ad['photo_url'] ) All of these functions exist in tasks.py file, annotated with Celery's shared_task (except for two util ones, which are simply "polishing" scraped data). I've been following tutorial from https://codeburst.io/making-a-web-scraping-application-with-python-celery-and-django-23162397c0b6, however what I don't understand is that how does Celery … -
redirect_uri mismatch error django heroku app
After deploying a Django google single sign-in app on Heroku I am facing redirect_uri mismatch although I have the correct redirect URI in the google credentials. I don't know where the problem is occurring. The same thing is working perfectly in the local machine. Please help. -
TemplateDoesNotExist when the template does exist
I am receiving TemplateDoesNotExist when i am sure the template exists "TemplateDoesNotExist at /maintenance/1/update/" when just going to /maintenance/ which is the index for that app it's working fine. the template is under the appfolder templates appfolder name then the templates as in the image Here is my settings.py import os from pathlib import Path # 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j@g&qm&20_oct_3f*sn-7n117si&1x4+m9cjao%g_&88gtmk9&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'accounts', 'maintenance', 'mptt', 'crispy_forms', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'nitrofleet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates',], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'nitrofleet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
A question about the python Django framework
In the Django REST framework, if the administrator asks the user to enter answers to some questions that can be added by the administrator account, how should the models class that saves the data submitted by the user be defined when the user fills in the unfixed questions added by the administrator? -
Filter most viewed and used objects in previous week(last seven days) - django
I want to be filtering the most viewed and used objects in the previous week(last seven days) in my project. Models class Banner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=150 , unique=True) description = RichTextField(blank=True, null=True) category = models.CharField(max_length=200) tag = models.CharField(max_length=200) image = models.ImageField(upload_to='banner-images/') updated = models.DateField(auto_now=True) created = models.DateField(auto_now_add = True) banner_users = models.ManyToManyField(User, related_name='banner_users', blank=True) slug = models.SlugField(unique=True, max_length=100) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super(Banner, self).save(*args, **kwargs) I used the hit-count package for the viewing count mechanism and use the banner_users in the model above to track the usage of the banner Views def discoverPage(request): context = {} q = request.GET.get('q') if request.GET.get('q') != None else '' searchbar_word = request.GET.get('q') banners = Banner.objects.filter( Q(name__icontains=q) | Q(user__username__icontains=q) | Q(user__full_name__icontains=q) | Q(description__icontains=q) ) most_viewed = Banner.objects.order_by('-hit_count_generic__hits')[:6] most_used = Banner.objects.order_by('banner_users')[:6] context = {'banners':banners, 'most_viewed':most_viewed, 'most_used':most_used, 'searchbar_word':searchbar_word} return render(request, 'discover-banner.html', context) -
Config Nginx with NextJs and Django rest framework
front of my site written with .next and back of my site written with DRF(Django rest framework) how i can configure Nginx to run .next for front and Django for Back? my current Nginx conf is: server { listen 80; listen [::]:80; server_name portal.asem.com www.portal.asem.com; include snippets/letsencrypt.conf; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name www.portal.asema.com; ssl_certificate /etc/letsencrypt/live/portal.asem.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/portal.asem.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/portal.asem.com/chain.pem; include snippets/ssl.conf; include snippets/letsencrypt.conf; return 301 https://portal.asem.com$request_uri; } server { listen 443 ssl http2; server_name portal.asem.com; ssl_certificate /etc/letsencrypt/live/portal.asem.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/portal.asem.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/portal.asem.com/chain.pem; include snippets/ssl.conf; include snippets/letsencrypt.conf; error_page 404 /custom_404.html; location = /custom_404.html { root /usr/share/nginx/html; internal; } location /STATIC/ { root /home/.../asem/static; } location /MEDIA/ { root /home/.../asem; } location / { proxy_pass http://localhost:3000; try_files $uri /index.html =404; } location /admin { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /user { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } my systemd service for nextJs is: [Unit] Description=Asem Front After=syslog.target network.target [Service] Environment=NODE_PORT=3000 Type=simple User=... Group=www-data Restart=on-failure WorkingDirectory=/home/.../asem-frontend ExecStart=npm start [Install] WantedBy = multi-user.target my next.config.js is : const withPWA = require('next-pwa'); const settings = { env: { API_URL : 'http://portal.asem.com/' }, devIndicators: { autoPrerender: false, }, pwa: { dest: 'public', }, }; module.exports = process.env.NODE_ENV === 'development' ? settings … -
Is it possible to store all inputs of login attempts in a file, in django?
I am currently building a local login page in Django (just started) and was wondering: Is it possible to store all login attempts (both succeeded and failed) in a json file for example? If it is, how? -
How to make an absolute url for pictures
models class ProductImage(models.Model): image = models.ImageField(upload_to="images", null=True, blank=True, verbose_name='Картинка') product_id = models.ForeignKey( ProductItem, related_name="product_image", on_delete=models.CASCADE, blank=True, null=True) models class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Пользователь", related_name='favorites', null=True, blank=True) products = models.ManyToManyField(ProductItem, verbose_name='Продукты', related_name = 'favorites', null=True, blank=True) class Meta: verbose_name = "Избранное" verbose_name_plural = "Избранные" serializers class ProductItemSerializers(serializers.ModelSerializer): product_image = ProductImageSerializers(many=True, read_only=True) class Meta: model = ProductItem fields = ( "id", "title", "size", "category", "product", "description", "price", "equipment", "is_new", "bouquet_care", "specifications", "discount", "product_image", ) views class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserInfoSerializer @action(methods=['get'], detail=True) def user_favorite(self, request, *args, **kwargs): user = self.get_object() favorite = user.favorites.all() serializer = FavoriteListSerializer(favorite, many=True) return Response(serializer.data) when calling http://127.0.0.1:8000/api/v1/users/1/user_favorite/ functions in the user in the view everything is displayed but the picture becomes not clickable without http { "id": 11, "image": "/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_NE6Swo2.jpeg", "product_id": 3 }, { "id": 12, "image": "/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_j5pAcru.jpeg", "product_id": 3 }, { "id": 13, "image": "/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_gx72p5l.jpeg", "product_id": 3 }, but should be { "id": 11, "image": "http://127.0.0.1:8000/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_NE6Swo2.jpeg", "product_id": 3 }, { "id": 12, "image": "http://127.0.0.1:8000/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_j5pAcru.jpeg", "product_id": 3 }, { "id": 13, "image": "http://127.0.0.1:8000/media/images/%D0%91%D0%B5%D0%B7_%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_gx72p5l.jpeg", "product_id": 3 }, how to rewrite ProductItemSerializer to make an absolute url, or what generally needs to be done for this -
Getting corrupt zips using Python3 ZipStream in Django
I'm using zipstream from here and have a Django view that returns a zip file of all file attachments which are all hosted on Amazon S3. But the zip files are all coming up as corrupt when I download them, that is, I can't open them. import io import zipstream s = io.BytesIO() with zipstream.ZipFile(s,"w", compression=zipstream.ZIP_DEFLATED) as zf: for file_path in file_paths: file_dir, file_name = os.path.split(file_path) zf.writestr(file_name, urllib.urlopen(file_path).read()) response = StreamingHttpResponse(s.getvalue(), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename={}'.format('files.zip') return response -
Static files doesn't work on heroku when using primary key in url
I have a problem, static files does not work when there is primary key in the url, problem occurs locally and on heroku. I tried many settings configs and always there was one problem or another. you can check it over this link - https://optifolio-dev.herokuapp.com/vispage/6/ from pathlib import Path import django_heroku import dj_database_url import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY ='smth' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['optifolio-dev.herokuapp.com','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', 'optifolio', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'OPI.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'OPI.wsgi.application' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ … -
Best Practices for migrating python2 to python3 in django
It will be more helpful if you answer the following questions as well. Dealing with models.CharField. In python2, how the CharField value is stored in the database and how it is different from the value which is going to store in python3. -
How can I return complete object which is created with generic create views?
I'm creating an object. Only two fields are required. Rest of them are not require. The problem is after creating object. i'm only getting serialize version of those two fields. But i want to get complete object that is created.. views.py class CreateProjectAPIView(generics.CreateAPIView): """This endpoint allows for creation of a Project""" permission_classes = [IsAuthenticated,] serializer_class = serializers.ProjectSerializer def create(self, request, *args, **kwargs): request.data.update({'platform_subscriber_owner': request.user.id}) print("request.data :",request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) print("serializer.data :",serializer.data) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) models.py class Project(models.Model): platform_subscriber_owner = models.ForeignKey(User, verbose_name=_("project owner"), on_delete=models.CASCADE,null=True,blank=True) platform_subscriber_id = models.CharField(_("Project Key"), max_length=64, blank=True) platform_subscriber_entity = models.CharField(_("Project Names"), max_length=64,blank=True) platform_subscriber_secret_key = models.CharField(_("Project Secret Key"), max_length=64,blank=True) update_time = models.DateTimeField(_("Updated Time"), default = timezone.now) create_time = models.DateTimeField(_("Created Time"), default = timezone.now) postman object after creating: { "platform_subscriber_entity": "naae", "platform_subscriber_owner": 2, } expecting object : { "platform_subscriber_entity": "naae", "platform_subscriber_owner": 2, "platform_subscriber_secret_key":sdakjshdjkashdj, "platform_subscriber_id":jjaskdjskakska, "create_time":now, "update_time:null, } -
How to add left sidebar in custom django admin template
I have created one custom page for Django admin, file name is server.html {% extends "admin/base_site.html" %} {% block content %} <h1>Server management</h1> {% if status == 200 and message %} <ul class="messagelist"> <li class="success">Response status: <strong>{{ status}}</strong></li> <li class="success">{{message}}</li> {% if stdout %} <li class="info">{{stdout}}</li> {% endif %} </ul> {% elif status is not 200 and message %} <ul class="messagelist"> <li class="error">Response status: <strong>{{ status}}</strong></li> <li class="error">{{message}}</li> {% if stdout %} <li class="error">{{stdout}}</li> {% endif %} </ul> {% endif %} <form method="post" id="menu_form" novalidate=""> {% csrf_token %} <div> <fieldset class="module aligned "> <div class="form-row field-parent_menu"> <div> <label for="id_parent_menu">Server action:</label> <div class="related-widget-wrapper"> <select name="server_action" id="server_action"> <option value="" selected="">---------</option> <option value="status">Status of the Server</option> <option value="start">Start the Server</option> <option value="stop">Stop the Server</option> <option value="restart">Restart the Server</option> </select> </div> </div> </div> </fieldset> <div class="submit-row"> <input type="submit" style="float: left;" value="Submit" class="default" name="_submit"> </div> </div> </form> {% endblock %} And my base_site.html looks like this {% extends 'admin/base.html' %} {% load i18n static %} {% block title %}{% trans "My admin" %}{% endblock %} {% block branding %} <div class="3a-image-header"> <img src="{% static 'images/admin-logo.svg' %}"> </div> <div class="3a-text-header"> <h1 id="site-name">{% trans 'Admin Dashboard' %}</h1> </div> {% endblock %} {% block extrastyle %}{{ block.super }} … -
Crisp throws an error 'BoundWidget' object has no attribute 'field' when i want to submit
I am trying to do an advanced rendering on my Django crispy forms the form section of my index.html looks like this <form method = "post"> {% csrf_token %} {{ form.organization |crispy}} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.start_date |crispy}} </div> <div class="form-group col-md-6 mb-0"> {{ form.end_date |crispy}} </div> </div> {{ form.recommend |crispy}} </form> -
Server error in django-heroku app Server Error (500)
after i developed it in heroku and change my DEBUG = False it's throws me an error i try to fix it but i can't cause i'm juniuor web devloper. is somebody can help me fix that please thank you. this is my settings.py file: STATIC_URL = '/static/' #STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'),) STATIC_URL = '/static/' MEDIA_URL ='/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' this is my profile: web: gunicorn myproject.wsgi this is my logs: 2022-01-11T06:03:20.892917+00:00 heroku[web.1]: Idling 2022-01-11T06:03:20.908352+00:00 heroku[web.1]: State changed from up to down 2022-01-11T06:03:22.072179+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2022-01-11T06:03:22.169474+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-01-11T06:03:22.169649+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-01-11T06:03:22.180490+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [INFO] Handling signal: term 2022-01-11T06:03:22.187455+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2022-01-11T06:03:22.192774+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-01-11T06:03:22.281450+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [INFO] Shutting down: Master 2022-01-11T06:03:22.537454+00:00 heroku[web.1]: …