Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: timezone conversion inside templates
I am attempting to convert UTC dates to my users timezones. All dates are stored in the database as UTC and each users timezone is also stored (captured when they signed up). The problem is, when I use timezone.activate(user_timezone) to try and convert the dates to the users timezone in my templates using the {% timezone on %} template tag, it keeps returning the same UTC date. I have tried every settings configuration possible but the problem continues. views.py from dateutil.relativedelta import relativedelta import def home(request): if request.method == 'GET': #users stored timezone e.g 'america/chicago' users_tz = reqeuest.user.timezone #activate users timezone timezone.activate(request.user.timezone) return render(request, 'home.html') home.html {% load tz %} ... {% localtime on %} <div style="float: right;"><b>Registered: </b> {{ user.registered_date }}</div> {% endlocaltime %} settings.py ... USE_I18N = True USE_L10N = True TIME_ZONE = 'UTC' -
encrypt and decrypt image using javascript
My server using this python function to encrypt and decrypt images. I want to do the same encryption in the frontend and send to this function in the backend. how to convert this method into JavaScript def encrypted_decrypted_image(image): key = 48 count = 0 for index, value in enumerate(image): count += 1 image[index] = value ^ key if count == 10: break return image -
How to use HTMLCalendar
I'm using Django, and I'm using the HTMLCalendar module to print a calendar on a page. Currently, the code below works fine, but when the date between 'from date' and 'to date' is more than 2days, I want to express it in one line instead of adding an event to each date belonging to the period. No matter how hard I searched, I couldn't find any posts with similar difficulties, and I haven't been able to solve them on my own for several days. Help! [models.py] class Leave(models.Model): title = models.CharField(max_length=50, blank=True, null=True) from_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) memo = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) is_deleted = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) return f'<div class="event-title" colspan="{self.end_date - self.from_date}"><a href="{url}" style="color:black;"> {self.title} </a></div>' [forms.py] class LeaveForm(ModelForm): class Meta: model = Leave # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'from_date': DateInput(attrs={'type': 'datetime', 'class': 'datepicker', 'autocomplete': 'off'}, format='%Y-%m-%d'), 'end_date': DateInput(attrs={'type': 'datetime', 'class': 'datepicker', 'autocomplete': 'off'}, format='%Y-%m-%d'), 'user': Select(attrs={"disabled": 'disabled'}), } fields = ['title', 'from_date', 'end_date', 'memo', 'user'] def __init__(self, request, *args, **kwargs): super(LeaveForm, self).__init__(*args, **kwargs) # input_formats … -
django allauth send me to /accounts/social/signup/# after I complete my authentication with google sing-in
I integrated djang0-allauth with my app but something is not fully working. Every time I try to login/sign by visiting http://127.0.0.1:8000/accounts/google/login/ and following the google auth flow, I am eventually sent to http://127.0.0.1:8000/accounts/social/signup/ where I am stuck in some sort of loop of sing-in and sing-up. I guess I didn't set-up my settings properly? Or maybe I need to do something with the adapters.py Just for context, I have a custom user model which maybe is also creating issues? settings """ Django settings for mywebsite project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_on_heroku import django_heroku import cloudinary import cloudinary_storage import dj_database_url from decouple import config import cloudinary.uploader import cloudinary.api # 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 = os.environ.get('DJANGO_SECRET_KEY', False) #env docs https://apple.stackexchange.com/questions/356441/how-to-add-permanent-environment-variable-in-zsh LOCAL = os.environ.get('ARE_WE_LOCAL', False) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True DEBUG_PROPAGATE_EXCEPTIONS = … -
How to get the duration of video when file is uploaded in the Django view.(with ffprobe)
I am creating a video streaming service with the Django. I want to get the duration of video when the video is uploded. So i've installed ffmpeg with brew (Mac OS), and created the command with subprocess but didn't working. I don't know what I have to do. These are things that I tried. views.py class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name = "movies/movie_upload.html" def form_valid(self, form): movie = form.save() filename = movie.video.path result = subprocess.check_output( f'ffprobe -v quiet -show_streams -select_streams v:0 -of json "{filename}"', shell=True, ).decode() fields = json.loads(result)["streams"][0] duration = fields["tags"]["DURATION"] print(duration) movie.user = self.request.user movie.save() return redirect(reverse("movies:detail", kwargs={"pk": movie.pk})) I tried this, but makes the error: Command 'ffprobe -v quiet -show_streams -select_streams v:0 -of json "/Users/bami/Documents/cineacca/uploads/SampleVideo_1280x720_20mb.mp4"' returned non-zero exit status 1. I tried with just filename, not filepath but the error was the same. class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name = "movies/movie_upload.html" def form_valid(self, form): movie = form.save() filename = movie.video.path duration = subprocess.check_output( [ "ffprobe", "-i", f"{filename}", "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=%s" % ("p=0"), ] ) print(duration) movie.user = self.request.user movie.save() return redirect(reverse("movies:detail", kwargs={"pk": movie.pk})) This code makes the same error. class MovieUpload(user_mixins.MoiveUploadPermissionView, FormView): """MovieUpload View""" form_class = forms.MovieUploadForm template_name … -
Django and HTML- how to apply styling to specific answers
I am working on a Django project where I have a survey form and this corresponding HTML syntax : <label for="id_form-{{ forloop.counter0 }}-answer">Answer:</label> {% for answer in answers %} <label for="id_form-{{ forloop.counter0 }}-answer"> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> {{answer.text}} {% if answer.image %} <img src="/static/mysurveys/{{answer.image}}.png"> {% endif %} </label> {% endfor %} This syntax is working fine for now, but my question is, how can I get rid of the for loop so that I can apply specific stylings to each answer? In this case, the user is supposed to select an image from a group of images as the answer, and I just want the images to be arranged in a circle container. I have tried something like this: <label for="id_form-{{ forloop.counter0 }}-answer">Answer:</label> <div class="circle-container"> <label for= 'id_form-{{ forloop.counter0 }}-answer' class='center'> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> <img src="/static/mysurveys/female_neutral.png"> </label> <label for= 'relaxed' class='deg22_5'> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> <img src="/static/mysurveys/female_relaxed.png"> </label> But, with this code the answer is not being recorded in the database and I am getting an error that says: Formset is NOT valid. [{'answer': ['This field is required.']}]. Please, let me know of any … -
Can django-tenants work for project that has a general section and company accounts
I working on a project that will have a main section where the users will have access to sections common to all (for example forums where they can communicate) and company accounts that will only be accessible to those that are members of that account. I have set up django-tenants but I am finding that out of the box it does not seem to work as I thought it would. For example, the tenant accounts have access to the forums even though the forums are only in the "shared apps" settings. The forums linked from the tenant accounts are empty but the should not even exist. Apparently "shared apps" means a shared schema. Another problem is that currently a tenant superuser has the ability to change content that is in a shared app. For example the tenant1 superuser could add/delete forums. This superuser can also see users for the whole site. Is there a way to setup django-tenants so that there is essentially a main project with sections that all users have access to but tenant users only have access to apps in the "TENANT_APPS" section of the settings.py file from inside of the tenant account (ex: tenant1.sitename.com)? -
i create project in django & when I try to run program it shows error of invalid interpreter selected for the project
And after adding a valid interpreter it again shows the error. it was a previously made project and was working without any issue but now it is not working. #help THANK YOU IN ADVANCE. ERRORS: jobs.Job.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". System check identified 1 issue (0 silenced). C:\Users\Admin\Desktop\portfolio>pip install pillow; Requirement already satisfied: pillow in c:\users\admin\appdata\local\programs\python\python39\lib\site-packages (8. 2.0) -
django change view that is colled with `http://127.0.0.1:8000/login/`
I am trying to change the view that is being called when someone hit the url http://127.0.0.1:8000/login/ on my app. I tried the following solution (not sure what I am doing thought)but i didn't work so I was wondering if anyone else had any idea. from django.contrib import admin from django.urls import path, include from django.views.generic.base import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('', include('action.urls')), path('r/', include('urlshortener.urls')), path('myusermodel/',include('myusermodel.urls')), path('login/',RedirectView.as_view(url='myusermodel', permanent=False), name='index'), path('accounts/', include('allauth.urls')), -
Django-compressor has a JS cache folder that is using an absurd amount of space
I woke up this morning to alerts from sentry that my production server has completely run out of space. It took some time figuring out the cause via ncdu, and the results were that my static folder had used over 60GB of space, specifically, CACHE/js that django-compressor is using. I am not completely sure what is happening, or why there are over 500,000 js files where each file is following this format: output.<random string>.js. From my understanding, shouldn't there only be a small number of js files cached? My project doesn't even have that many scripts! It seems to me that every user is getting their own output file, instead of the same cached files being shared to everyone. Base settings: # STATIC # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#static-root # STATIC_ROOT = str(ROOT_DIR / "static") STATIC_ROOT = os.path.join(BASE_DIR, "static/") # https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = "/static/" # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS # STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "compressor.finders.CompressorFinder", ] COMPRESS_ENABLED = True COMPRESS_PRECOMPILERS = ( ('text/x-scss', 'django_libsass.SassCompiler'), ) COMPRESS_FILTERS = { "css": [ 'compressor.filters.css_default.CssAbsoluteFilter', # 'compressor.filters.cssmin.CSSMinFilter', 'core.CSSMinFilter.CSSMinFilter', ] } production settings: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } I originally installed django-compress to fix issues where users … -
How to add a model containing a FilePathField item to an admin panel
I've set up a model which contains a FilePathField() item with the path '/img'. The img folder is located in a static folder in that app and the whole setup works perfectly when adding items through the shell interface. The problem comes in when I try to set up the admin panel to include this model where I get a FileNotFoundError when trying to open existing items or add new ones. The error is: FileNotFoundError at /admin/work_done/project/2/change/ [WinError 3] The system cannot find the path specified: '/img' To get around this I changed the path property to the absolute path with: path=f'{Path(__file__).parent.absolute()}/static/img') This makes the admin panel work but when I add items with that in place the image doesn't show up because it's looking for an image at localhost:8000/static/C%3A/.../static/img/image.png. Is there a way to make this work in admin and have the image show up? I've only found an answer to getting it working in admin but that doesn't mention the image not working in the website. The code I'm using to actually display the image is '{% static project.image %}'. I have tried changing it to '{% url project.image %}' as a long shot but unsurprisingly it didn't … -
Error on Docker-Compose with a Django - postgres db
I'm trying to create a Django application with docker. To get a more scalable application I'm trying to run a Postgres db in a different container. To be more specific, I just followed the tutorial at this link: https://docs.docker.com/samples/django/ The docker compose is this, in which I set the username, psw and name of the database 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" depends_on: - db The connection of the database in settings.py of Django is done in these lines: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } When I try to run the whole project, with the command docker-compose up the web application (which is the Django application) responds with this error: django.db.utils.OperationalError: SCRAM authentication requires libpq version 10 or above I really don't undestand what's wrong in here. Have to update the python - linux container that runs the Django application? Thank you really much in advance for all the help you will get me. -
Python: Django Framework - urls.py: No "name"-Attribute in path()?
I'm currently trying to link from one HTML-Page to another one. Some Tutorials told me I need to link with an url inside the .html-file to the specific path I've been defining before. So that's what I did: <a id ="register" href="{% url 'register_view' %}"> register now</a> and inside my urls.py of the app "login" I also wanted to call the path "register_view" with the name-attribute: urlpatterns = [ path('', login_view), path('register/', register_view, name="register_view"), ] but the problem is: it won't find the attribute "name" inside `path() and I have no idea why. Can you help me out here? Thanks in Advance! -
django POST IntegrityError
I got an IntegrityError when I POST data at /users/profiles. I have only one instance in Profile model. And POST another data. I can not understand why that data exist already.. Here is my code. and I put the trace back after code. models.py from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class Job(models.Model): job_name = models.CharField(max_length=30, blank=False) def __str__(self): return f'{self.pk} {self.job_name}' class UserManager(BaseUserManager): def create_user(self, phone_nm, login_ID, login_PW, age, gender, password): if not phone_nm: raise ValueError('User must have a phone_nm') if not login_ID: raise ValueError('User must have an login_ID') if not login_PW: raise ValueError('User must have a login_PW') if not age: raise ValueError('User must have an age') if not password: raise ValueError('User must have a password') user = self.model(phone_nm=phone_nm, login_ID=login_ID, login_PW=login_PW, age=age, gender=gender, password=password) user.set_password(password) user.is_superuser = False user.is_staff = False user.save(using=self._db) return user def create_superuser(self, phone_nm, login_ID, login_PW, age, gender, password): if not phone_nm: raise ValueError('User must have a phone_nm') if not login_ID: raise ValueError('User must have an login_ID') if not login_PW: raise ValueError('User must have a login_PW') if not age: raise ValueError('User must have an age') if not password: raise ValueError('User must have a password') user = … -
Count and pourcentage
I need a function that allows you to count the number of events by occurence and calculate the percentage for each type in order to present it on a donut chart.js? #models.py Categorie = { ('Annual', 'Annuel), ('Monthly', 'Monthly, ('Weekly', 'Weekly), ('Daily', 'Daily'), } class Even(models.Model): name = models.CharField(max_length=20) date_reported = models.DateField() occurence = models.CharField(max_length=30, null=True, blank=True, choices=Categorie) def __str__(self): return self.name -
In Django/Python, how do I prefix my log messages with the current date and time?
I'm using Python 3.9 and Django 3.2. I have logging configured in my settings.py file LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, } When I do logging in one of my classes, I do it like so import logging ... class TransactionService: def __init__(self): self._logger = logging.getLogger(__name__) def my_method(self, arg1, arg2): ... self._logger.info("Doing some logging here.") How do i configure my logger such that when the message is printed out, it is prefixed by the current date and time? -
Django 1.8.19 and SQL Server
I have a problem, I am using Django 1.8.19 and SQL Server 2019, but I can't connect Django to SQL Server. How to fix it? enter image description here -
Django-filter doesn't filter
Hi I'm new in django and I want to use django-filter for url filtering in django-resframwork but i can't get my data filtered. views.py class ListingFiltered (generics.ListAPIView): queryset = Listing.objects.all() serializer_class = ListingSerializer filterset_backends = (DjangoFilterBackend) # filterset_class = ListingFilters filter_fileds= ['price'] urls.py urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('listings/', ListingViewSet.as_view(), name= 'listings'), path('listings/custom', ListingFiltered.as_view()) ] serializers.py class ListingSerializer(serializers.ModelSerializer): class Meta: model = Listing depth = 1 fields = '__all__' I'm trying http://127.0.0.1:8000/listings/custom?price=1000 and nothing happens. What am I doing wrong? -
Django form - How to autofill fielf from another
I would like to autofill my Kpi fieldd by extracting its value in the name field For example : here kpi = name.split("-")[6] which equal to CPC string. How can I do that please? class UserCampaigns(models.Model): dsp_choices =( ('Amazon', 'Amazon'), ('Amobee', 'Amobee'), ('AppNexus', 'AppNexus'), ('Digiteka', 'Digiteka'), ('DV 360', 'DV 360'), ) kpi_choices = ( ('CPA', 'CPA'), ('CPC', 'CPC'), ('CPD', 'CPD'), ('CPL', 'CPL'), ('CPM', 'CPM'), ('CPV', 'CPV'), ('CTR', 'CTR'), ('Vsibility', 'Visibility'), ('VTR', 'VTR'), ('LTR', 'LTR'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.ForeignKey(CampaignNamingTool, on_delete=models.CASCADE) dsp = models.CharField(max_length=30, choices=dsp_choices) budget = models.DecimalField(max_digits=20, decimal_places=2) kpi = models.CharField(max_length=10) #choices=kpi_choices) start_date = models.DateField() end_date = models.DateField() -
Upload Image using nextJs fail with 415 Unsupported Media Type
I am trying to send a POST request (with an image) to a /api/service/register. Request is sent via fetch api in this way: (formData is an useState) ... const [photo, setPhoto] = useState(null) const onChange = (e) => ( upDatePhoto(e.target.files[0]) ) const onSubmit = async (e) => { e.preventDefault() const body = new FormData() body.append('name', name) body.append('photo', photo) body.append('email', email) body.append('phone', phone) body.append('description', description) try { const res = await fetch('/api/service/register', { method: 'POST', body: body }); ... but i get this error 415 Unsupported Media Type It seems that when I get req.body, I got nothing register.js export default async (req, res) => { ... const apiRes = await fetch(`${API_URL}/ServiceOwners/register/`, { method: 'POST', headers: { 'Authorization': `Bearer ${access}`, }, body: req.body }); ... when i print req.body i get this format ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="name" test test ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="photo" blob:http://localhost:3000/3a6396ef-c0b3-4b7c-8dd5-13f581f0ff59 ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="email" testtest@gmail.com ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="phone" 03 43 55 21 00 ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="description" test ------WebKitFormBoundaryebJPBXTlpiCCQCeA-- I'll show more code if needed. Thanks -
Django form that updates multiple records
I have 2 classes of users who can view a screen that lists all users in my app. The type of user is controlled by a Boolean field on the User model. The screen currently lists out the Users and various details about them (see below). Project Managers should see a read only view of the page where as Administrators should have the ability to edit the Users as well. HTML for the screen. <div class="card-body"> <div class="table-responsive"> <table class="table text-sm mb-0"> <thead> <tr> <th>#</th> <th>Username</th> <th>First Name</th> <th>Last Name</th> <th>Is Contributor?</th> <th>Is Project Manager?</th> <th>Is is_administrator?</th> </tr> </thead> <tbody> {% for user in users %} <tr> <th scope="row">{{ user.id }}</th> <td>{{ user.username }}</td> <td><a class="btn btn-primary" href=" " role="button">{{ user.first_name }}</a></td> <td>{{ user.last_name }}</td> <td>{{ user.is_contributor }}</td> <td>{{ user.is_projectmanager }}</td> <td>{{ user.is_administrator }}</td> <td><a class="btn btn-info" href="" role="button">Edit</a></td> <td><a class="btn btn-danger" href="" role="button">Delete</a></td> </tr> {% endfor %} </tbody> </table> </div> </div> I want to create a version of the screen available to admin users which allows them to view and update users all at once. How can I create a form that updates all the users at once? I'm looking to build something that lists out the users with … -
Send request to Schema Marshmallow + Django
I have a view : class ArticlesListView(APIView): authentication_classes = (JWTAuthentication,) def post(self, request, *args, **kwargs): """Post an Article.""" try: schema = ArticleSchema() article = schema.load( json.loads(request.body)) schema.context = {'request': request} except ValidationError as e: return json_response(e.messages, 400) return json_response(schema.dump(article), 201) which posts, though I wanted to send a request to the ArticleSchema() how can I do this ? Below is the schema : class ArticleSchema(Schema): class Meta(object): model = Article id = fields.Integer() title = fields.String(validate=validate.Length(max=255)) content = fields.String() regions = fields.Method( required=False, serialize="get_regions", deserialize="load_regions" ) @post_load def update_or_create(self, data, *args, **kwargs): print(" args ", args) print(" kwargs ", kwargs) regions = data.pop("regions", "") title = data.pop("title", "") content = data.pop("content", "") user = User.objects.get(id=1) article, _ = Article.objects.update_or_create( id=data.pop("id", None), owner=user, title=title, content=content, defaults=data ) if isinstance(regions, list): article.regions.set(regions) return article -
how do you iterate through two items in a model and display on site using Django?
I have a models.py with the following fields: class ChatStream(models.Model): bot = models.TextField() user = models.TextField() name = models.CharField(max_length=100, null=True) created_date = models.DateTimeField(auto_now_add=True) And I'd like on a website to iterate through "bot" and "user" one at a time, so the site would hypothetically display something like: bot: hello! user: what's up? bot: I'm good user: What's your name bot: bot is my name .... etc. this would keep going... So in my views.py I have def displayDict(request): m = ChatStream.objects.all() return render(request, 'chatStream.html', {"chat": m}) def send(request): message = request.POST.get('userMessage', False) ip = visitor_ip_address(request) response = routes(message, ip) print(ip, "user sent:", message, "bot response:", response) chatItem = ChatStream(bot=response, user=message, name=ip) chatItem.save() return HttpResponseRedirect('/chat/') Then in my template, chat.html I have {% block chatStream %} {% endblock %} And chatStream.html: {% extends 'chat.html' %} {% block chatStream %} {% for a in bot%} {% for b in user%} <p> <b>bot:</b> {{a}} <br> <b>user:</b> {{b}} <br> </p> {% endfor %} <form action="/send/" method = "post">{% csrf_token %} <input type="text" name="userMessage"> <input type="submit" value="Send to smallest_steps bot"> </form> {% endblock %} But this does not work -- no text from the model is displayed on the site. thank you -
django import-export adding an emailValidator adds a new field on export
I have these models: Investment Profile wherein Investment has a foreign key to Profile through email. I'm trying to bulk export but the export adds a duplicate profile__email without any values. Sample result: I noticed its from the added validator in my InvestmentResource: class InvestmentResource(resources.ModelResource): class ValidatingEmailForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row=None, *args, **kwargs): try: validate_email(value) except ValidationError as e: # a quirk of import-export means that the ValidationError # should be re-raised raise ValueError(f"invalid email {e}") try: val = super().clean(value) return value except self.model.DoesNotExist: raise ValueError(f"{self.model.__name__} with value={value} does not exist") email = fields.Field(attribute='profile__email', widget=ValidatingEmailForeignKeyWidget(Profile, field='email'), column_name='profile__email') class Meta: model = Investment clean_model_instances = True import_id_fields = ('id',) fields = ( 'id', 'notes', 'firstname', 'lastname', 'email',) export_order = fields def before_import_row(self, row, row_number=None, **kwargs): self.profile__email = row["profile__email"] self.profile__firstname = row["firstname"] self.profile__lastname = row["lastname"] def after_import_instance(self, instance, new, row_number=None, **kwargs): """ Create any missing Profile entries prior to importing rows. """ try: # print(self.isEmailValid(self.email), file=sys.stderr) profile, created = Profile.objects.get_or_create(email=self.profile__email) profile.firstname = self.profile__firstname profile.lastname = self.profile__lastname profile.save() instance.profile = profile except Exception as e: print(e, file=sys.stderr) If I try to remove the validator and change email in fields to profile__email, the fields exported are what is expected, but when importing, the emails … -
GitHub CI Test Error: relation does not exist. (DRF as BE)
I am working on a project based on Django Rest Framework and I got some CI Test errors when I try to merge my branch to main. Before I merge to main, I have already made some Django Unit Tests and they all can pass locally. (My database is postgres) Here is the error detail: Here is the CI Test Error I have never face this error locally. I tried to re-migration and migrate the database but it still fails in CI test. Dose this because CI test and Django test have different operation logic? Or is it because I have a problem with the processing of the postgres? This is my first question on stackoverflow, appreciate for any reply!