Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disable logging of `exc_info` when raising `BadRequest`?
When a Http404 is raised, the log provides the relevant information but not the details of the exception But when a BadRequest is raised, the log includes exc_info so it makes it look like something went wrong rather than standard error handling of bad requests. So is there a way to disable or modify this behavior? -
how to customize all-auth errors for mismatch passwords to othere languge?
class PasswordVerificationMixin(object): def clean(self): cleaned_data = super(PasswordVerificationMixin, self).clean() password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if (password1 and password2) and password1 != password2: self.add_error("password2", _("You must type the same password each time.")) return cleaned_data I want to override this class and make the error message to 'this a test' i am stuck i tried overriding it but nothing any help? I want to override this class and make the error message to 'this a test' i am stuck i tried overriding it but nothing any help? -
How to get csrfToken for front-end to submit logins in Django
I've read all the issues about this, but it's still not clear to me. I am not using Django templates to handle login functions (login, logout, changepassword, create user, etc). I tried POSTing to the accounts/login page with "username": <user>, "password": <password> But it also wants a CsrfViewMiddleware token. It's not clear to me where I get that. Does the front-end have to requrest it first from another endpoint? Is there some other way to do the CSR checking? -
CORS Policy Error with Specific Data in React and Django Application
CORS Policy Error with Specific Data in React and Django Application I'm experiencing an issue with CORS policy in my React frontend and Django backend application. The error message I'm receiving is: Access to fetch at backend URL' from origin 'frontend URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I have configured all the CORS Configuration in settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with',] Installed apps also 'corsheader' is added The problem is i am getting this issue for only one data not for all data for my views i added Decorators like: @csrf_exempt @require_http_methods(["OPTIONS", "POST"]) As it is working fine in Local,Development only for Staging i am getting this issue that to for only some data others are working fine -
custom storage-backend class not working as expected with s3, boto3 and django-storages
I am following this tutorial here from Michael Herman, trying to setup s3 storage for my django project and I am facing some issues right from the start of the tutorial. First, when I tried running the collectstatic command, I got this error: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied I looked up a bit, and apparently you have to set AWS_DEFAULT_ACL = None and doing that fixed it. So now my static files were being uploaded to the s3 bucket when I ran collectstatic. But when I visited the webpages, the static images and stylesheets were not getting fetched as expected. I tried many different things at this point, but none of them worked. I typed the s3 object url in the browser and this was the error I was getting: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>419CX01JK1CAKYCS<RequestId> <HostId>rB7y8qLl5a5G0I1LVx2lexUbJpcvnrdKIMZ3AVq69C81B3j4BRWZwLq5THNLINwSv6q5HFSAednN1yq2tRCQ6THuxEn+S/Kj</HostId> </Error> Now the next thing I did was to make all the bucket objects as public. The tutorial doesn't do this and I'm not sure if its a bad thing or not? Anyone please point out if it is. Using this answer, I set the Block all public access setting to off and also added a Bucket … -
Bootstrap modal does not trigger inside a django for loop
I want to attach a modal to all images. But for some reason the modal is not triggered and the entire page becomes un-clickable. I have made sure that all modals triggers and modal have a unique ID without any results. Can anyone see what I am doing wrong? {% for photo in user_photos %} <div class="image-container"> <div class="image-wrapper" data-bs-toggle="modal" data-bs-target="#photoModal{{photo.id}}"> <img src="{{ photo.photo.url }}" alt="Användarbilder"> {% if request.user == photo.user %} <form method = "POST"> {% csrf_token %} <i class="bi bi-x-lg profile_delete_photo" title="Radera" data-photoId = "{{photo.pk}}" data-url = "{% url 'profilepage_app:deletePhotoAjax' %}"></i> </form> {% endif %} </div> <span>Uppladdat: {{ photo.timesince }}</span> <!-- Modal --> <div class="modal fade" id="photoModal{{photo.id}}" tabindex="-1" aria-labelledby="photoModallabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="photoModal{{photo.id}}Label">Modal title</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> {% endfor %} I also have this for loop and modal in another page, but it works fine. {% for diary in user_diaries %} <tr> <td> <!--Diary title--> <a href="{{diary.get_absolute_url}}">{{diary.title|truncatechars:30}}</a> {% if request.user == user %} <div> <!--Dropdown--> <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false" fill="currentColor" class="dropdown-toggle bi bi-three-dots-vertical" … -
Error while using django-vite-plugin and react
I am using django-vite-plugin and react for the frontend of my project. I followed the tutorial on https://react.dev/learn/add-react-to-an-existing-project and when testing using index.js I got the error '[vite] Internal server error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.' I would like to kindly ask for assistance solving this problem. I first tried this and got an error import { createRoot } from 'react-dom/client'; document.body.innerHTML = '<div id="app">JS working</div>'; const root = createRoot(document.getElementById('app')); root.render(<h1>Hello</h1>); However when I commented out the last line it worked. LIke this: import { createRoot } from 'react-dom/client'; document.body.innerHTML = '<div id="app">JS working</div>'; const root = createRoot(document.getElementById('app')); //root.render(<h1>Hello</h1>); My index.html is {% load vite %} <!DOCTYPE html> <html lang="en"> <head> <!--Other elements--> <!--Vite dev client for hmr (will not be displayed on production)--> {% vite %} {% vite 'newspaper/css/styles.css' 'newspaper/js/main.js' %} </head> <body> <!--Page content--> </body> </html> My vite.config.js is //vite.config.js import { defineConfig } from 'vite' import { djangoVitePlugin } from 'django-vite-plugin' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [ djangoVitePlugin([ 'newspaper/js/app.js', 'newspaper/css/style.css', ]), react() ], }); My package.json is { … -
Drop duplicates when quering multiple tables in Django
I have a custom manager with search, which orders return results by rank: class MyManager(models.Manager): def search(self, query, fa, fb=None, fc=None, fd=None, qs=None): if not qs: qs = self.get_queryset() try: if not (1 in [c in query for c in '&|()!*:"']): query = " & ".join([f"{q}:*" for q in query.split()]) vector = SearchVector(*fa, weight="A", config="english") if fb: vector += SearchVector(*fb, weight="B", config="english") if fc: vector += SearchVector(*fc, weight="C", config="english") if fd: vector += SearchVector(*fd, weight="D", config="english") query = SearchQuery(query, search_type="raw") qs = ( qs.annotate(search=vector, rank=SearchRank(vector, query)) .filter(search=query) .order_by("-rank", "-id") .distinct("rank", "id") ) qs.count() # Trigger exception except (ProgrammingError, UnboundLocalError): qs = qs.none() return qs But when I try searching on related fields, it still returns duplicate results: class Case(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE) user = models.ForeignKey(Profile, on_delete=models.SET_NULL) hashtags = models.CharField(max_length=255) closed = models.BooleanField(default=False) objects = MyManager() class CaseProgress(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) desc = models.TextField() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class CaseListView(ListView): model = Case def get_queryset(self): query = self.request.GET.get("query", None) show_closed = ( True if self.request.GET.get("show_closed", False) == "true" else False ) if query: if not show_closed: qs = self.model.objects.filter(closed=False) else: qs = self.model.objects.all() fa = ( "id", "machine__serial_number", "machine__company__name", "user__user__first_name", "user__user__last_name", ) fb = ("hashtags",) fc … -
Coloured output from native Django test runner
I'm trying to get a colored output (red or green) when running my Django tests with the native Django test runner. I'm running a poetry virtualenv (python 3.11.6) with Django (5.0.3) and colorama (0.4.6) in a zsh on MacOS but the output remains colourless. Following the Django documentation, I've set export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" in my zsh before calling python manage.py test apps.myapp. Yet, the output remains colourless. Same result when adding the --force-color option. However, spinning up the same virtualenv and executing from colorama import Fore, Style print(Fore.RED + 'This is red text' + Style.RESET_ALL) returns a red text (as expected). What do I have to do to get a colored output from the native Django test runner without switching to a different one? -
init_fs_encoding during deploying django app to apache
i'm trying for hours to deploy a django app on an apache2 and still get following error: PYTHONHOME = '/home/rickmanns/bar/bar/djenv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = '/home/rickmanns/bar/bar/djenv/lib/python3.11' sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/rickmanns/bar/bar/djenv' sys.base_exec_prefix = '/home/rickmanns/bar/bar/djenv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/rickmanns/bar/bar/djenv' sys.exec_prefix = '/home/rickmanns/bar/bar/djenv' sys.path = [ '/home/rickmanns/bar/bar/djenv/lib/python311.zip', '/home/rickmanns/bar/bar/djenv/lib/python3.11', '/home/rickmanns/bar/bar/djenv/lib/python3.11/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' My Apache config looks like following: Alias /static /home/rickmanns/bar/static <Directory /home/user/myproject/static> Require all granted </Directory> <Directory /home/rickmanns/bar/bar> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess bar python-path=/home/rickmanns/bar python-home=/home/rickmanns/bar/djenv WSGIProcessGroup bar WSGIScriptAlias / /home/rickmanns/bar/bar/wsgi.py If it's helpful - i followed this tutorial: https://pimylifeup.com/raspberry-pi-django/ Thanks to everyone! -
django probleme with image in shared hosting
I have an image problem that displays locally but not on shared hosting. The site works well in hosting , the custom js and css files are ok. In my Django template, I have this image: <div class="col-sm-3 order-3 order-sm-3"> <!-- form pub --> <img class="img-thumbnail" src="{% static 'img/exemple_banner_01.png' %}" alt="..." /> </div> This image is in: static/img/myimage.png I do python manage.py collectstatic After that, this image is found here: collectstatic/img/myimage_01.ze25a48a4c2.png In settings file: STATIC_URL = 'static/' STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))] STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage My css and javascript files are ok. When displaying, my image doesn't show up. mysite.com/static/img/myimage_01.ze25a48a4c2.png "Not Found The requested URL was not found on this server." I tried to put in the settings: /home/user/public_html/myapp/static but it gives me a 500 error. I should add that I'm in debug False mode. Thank for help -
Case Insensitivity Issue with Tag Suggestions in Wagtail
I'm studying Wagtail and encountered the following issue when setting up tags. I added the following models: @register_snippet class BlogTag(TagBase): free_tagging = False name = models.CharField(max_length=25, unique=True) slug = models.SlugField(max_length=255, unique=True, blank=True) class Meta: verbose_name = "blog tag" verbose_name_plural = "blog tags" class TaggedBlog(ItemBase): tag = models.ForeignKey( BlogTag, related_name="tagged_blogs", on_delete=models.CASCADE ) content_object = ParentalKey( 'home.BlogPage', on_delete=models.CASCADE, related_name='tagged_items' ) I enabled the setting TAGGIT_CASE_INSENSITIVE = True. However, when a user fills in the tags while creating a page, the case is still taken into account - if the user enters a word in lowercase, options from the dropdown list do not appear. Here is the model, if it matters: class BlogPage(Page): tags = ClusterTaggableManager(through=TaggedBlog, blank=True) date = models.DateField("Мы это написали:") author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='blog_pages') body = StreamField([ ('heading', blocks.CharBlock(form_classname="title", label="Заголовок")), ('paragraph', blocks.RichTextBlock(label="Текст")), ('image', ImageChooserBlock(label="Изображение")), ('quote', blocks.BlockQuoteBlock(min_length='20', label="Цитата")), ('media', EmbedBlock(label="Ссылка на видео")), ], verbose_name='Содержимое') content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('body'), FieldPanel('slug', permission='superuser'), FieldPanel('tags'), ] edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Центр управления постами'), ObjectList(Page.promote_panels, heading='Promote', permission='superuser'), ]) def _get_unique_slug(self): slug = slugify(self.title) unique_slug = slug num = 1 while Page.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self._get_unique_slug() super().save(*args, **kwargs) Please tell … -
Django is randomly ignoring certain days when I try to bulk_create. How do I solve this? How does this even happen?
How does Django randomly skip days when trying to bulk_create? The dataset is a CSV exported via a third party tool from a MSSQL Server. Exhibit 1 - Data from my database: Note the whole 2024-06-13 is missing. Exhibit 2 - Data dump from my dataframe: When I look at my pandas dataframe, there was data for 2024-06-13. So reading the CSV and parsing the date works. At first, I thought the issue was using too much memory to bulk_create so I tried chunking. The problem still remained. But if it was a memory problem, then it wouldn't so cleanly eliminate that day without affecting the other days around it. The session start/stop times correspond with when the shop opens and closes on the 12th and 14th. It's not the only day that randomly disappeared. There are other days before this as well that have vanished. Also, the last possible import date was 2024-06-24. After that, it won't import any more sessions that exists in my dataframe. I tried both SQLite and Postgres to no avail in case it was a database issue. This is how it's imported from my dataframe via DjangoORM: sessions = [Session(**row) for row in df.to_dict(orient='records')] … -
What is the correct way for implementing Hyphenopoly?
I'm having trouble implementing Hyphenopoly (https://github.com/mnater/Hyphenopoly) on a Django project. Sometimes it seems to work fine, sometimes not. Besides, on mobile browser the result are unpleasant, since hyphens appears in a pretty inconsistent fashion (or doesn't at all) on elements with italian language. Further, I cannot understand the documentation provided. My fault. Herein I report part of the directory structure of the project As you can see, and for what I understood, I loaded only few files from the original library, in order to hyphenate italian and english pieces of text (separated or mixed). The main language is still en, since I defined it in the lang attribute of the html element; for each element featuring italian content, I specified the language attribute accordingly (for mixed content, I used spans). In the head element of my base.html: <script src="{% static './hyphens/Hyphenopoly_Loader.js' %}"></script> <script src="{% static 'HyphenConfig.js' %}"></script> The HyphenConfig.js file, instead: $(document).ready(function() { var Hyphenopoly = { require: { 'en-us': 'ALL', 'en': 'ALL', 'it': 'ALL' }, paths: { patterndir: "./hyphens/patterns/", maindir: "./hyphens/" }, setup: { selectors: { '.hyphenate': { compound: "all", leftmin: 0, rightmin: 0, minWordLength: 4 } } } }; }); I also defined the hyphenate class in the … -
Django is unable to send email out even though conf is correct
Django is unable to send email out. But https://www.smtper.net/ was able to send a test email with same exact settings, user, pass. What do I need do more in django to send email out? settings.py ## #environment variables from .env. from dotenv import load_dotenv load_dotenv() NOREPLYEMAIL = os.getenv('NOREPLYEMAIL') NOREPLYEMAILPASS = os.getenv('NOREPLYEMAILPASS') ### Email config EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtppro.zoho.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = NOREPLYEMAIL EMAIL_HOST_PASSWORD = NOREPLYEMAILPASS DEFAULT_FROM_EMAIL = NOREPLYEMAIL view.py # using https://docs.djangoproject.com/en/5.0/topics/email/ @csrf_protect def test(request): testemail = EmailMessage( "Hello", #subject "Body goes here", #message body NOREPLYEMAIL, #from ["mygmail@gmail.com",], #to reply_to=[NOREPLYEMAIL], headers={"Message-ID": "test"}, ) testemail.send() -
Django - the date field in the data entered form is reset during editing
I made a model, form and views. I added some data via form. And then when i want editing, all fields are full but datefield is empty. I want to see date which i added before. But nothing. I use all ai solutions also javascript, jquery, but nothing. How can i solve this problem. I have model like this and class Cilt(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Kullanıcı") birth_place = models.CharField(max_length=200, blank=True, null=True, verbose_name="Birth Place") birth_date = models.DateField(blank=True, null=True, verbose_name="Birth date") def __str__(self): return f"{self.user.username}" forms.py class CiltForm(forms.ModelForm): class Meta: model = Cilt exclude = ['user'] fields = '__all__' widgets = { 'birth_place': forms.TextInput(attrs={'class': 'form-control'}), 'birth_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), def __init__(self, *args, **kwargs): super(CiltForm, self).__init__(*args, **kwargs) instance = kwargs.get('instance', None) if instance: initial_date = instance.ucuk_en_son_cikis_tarihi self.fields['birth_date'].initial = initial_date self.fields['birth_date'].widget = forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}) edit views def cilt_duzenle(request, user_id): ciltler = get_object_or_404(Cilt, user__id=user_id) if request.method == 'POST': form = CiltForm(request.POST, instance=ciltler) if form.is_valid(): form.save() return redirect('cilt_detay', user_id=user_id) else: form = CiltForm(instance=ciltler) return render(request, 'cilt/cilt_duzenle.html', {'form': form}) -
Connection Timeout on External API Call on Server but Works Locally
I have a Django 4.2.2 application running on Python 3.11. One of the views is as follows: import requests from django.http import HttpResponse def get_captcha(request): response = requests.get( "https://geoportale.cartografia.agenziaentrate.gov.it/age-inspire/srv/ita/Captcha?type=image&lang=it" ) session_id = response.cookies.get("JSESSIONID") request.session["CAPTCHA"] = session_id content_type = response.headers["content-type"] return HttpResponse(response.content, content_type=content_type) When running the application locally, the API call is executed successfully. However, when running on an Aruba server, it results in a timeout. Here are the steps I've taken to try to resolve this issue, without success: Downgraded OpenSSL to the same version used locally (1.1.1n) Disabled the firewall Changed DNS servers for domain resolution Downgraded the Python version Below is the result of traceroute from the server: traceroute to geoportale.cartografia.agenziaentrate.gov.it (217.175.52.194), 30 hops max, 60 byte packets 1 host2-224-110-95.serverdedicati.aruba.it (95.110.224.2) 0.702 ms 0.744 ms 0.824 ms 2 cr2-te0-0-0-2.it2.aruba.it (62.149.185.196) 0.865 ms 0.919 ms * 3 * * * 4 * * * 5 * * * 6 * 93-57-68-2.ip163.fastwebnet.it (93.57.68.2) 10.095 ms 10.516 ms 7 81-208-111-134.ip.fastwebnet.it (81.208.111.134) 10.482 ms 10.370 ms 10.536 ms 8 * * * 9 * * * 10 * * * 11 * * * 12 * * * 13 * * * 14 * * * 15 * * * 16 * … -
How to order migration files across different apps in django?
I am working on a django project. After some time, I wanted to refactor the code. I wanted to create a new app and move some of my models to that app. Here's an example: Suppose I have an app named CategoryApp and two models in it named Product and Category. class Category(models.Model): ... class Product(models.Model): ... After some time of coding, I realized that I need a separate app for Product. So, I created a new app named ProductApp. And copied the Product model from CategoryApp to ProductApp. I managed all the foreign keys and relationships appropriately. Now, I need to create the migration files. First of all, I created a migration file for the app ProductApp (python3 manage.py makemigrations ProductApp) that just creates a new table productapp_product in the database. The migration file is named 0001.py. I applied this migration and a new table is created. Second, I created an empty migration file in the ProductApp (python3 manage.py makemigrations ProductApp --empty). The migration file is named 0002.py I modified the contents of the empty migration file to run SQL query to copy all the data from categoryapp_product table to productapp_product. I also added reverse_sql in case I need … -
TypeError at /predict/ predict_view() missing 2 required positional arguments: 'user_skills' and 'project_skills'
def predict_view(request, user_skills, project_skills): # Fetch data from the database freelancer_data = freelancer_info.objects.get(skills=user_skills) freelancer_data.save() project_data = project_info.objects.get(required_skills=project_skills) project_data.save() # Convert data to DataFrame freelancer_df = pd.DataFrame(list(freelancer_data)) project_df = pd.DataFrame(list(project_data)) # Add labels freelancer_df['label'] = 'freelancer' project_df['label'] = 'project' # Combine data combined_df = pd.concat([freelancer_df, project_df]) combined_df.columns = ['text', 'label'] # Feature extraction vectorizer = CountVectorizer() X = vectorizer.fit_transform(combined_df['text']) y = combined_df['label'] # Split the data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Train the Naive Bayes model model = MultinomialNB() model.fit(X_train, y_train) # Make predictions y_pred = model.predict(X_test) # Evaluate the model accuracy = accuracy_score(y_test, y_pred) report = classification_report(y_test, y_pred) # Render the results context = { 'accuracy': accuracy, 'report': report, } return render(request, 'frontend/predict.html', context) This my code for making a prediction using naive bayes algorithum, but I receive. TypeError at /predict/ predict_view() missing 2 required positional arguments: 'user_skills' and 'project_skills' How do I over come this issue? -
Unique Constraint Failed In Upsert When Calling bulk_create with update_conficts
Im facing a unique constraint failed error with django. The objective of the api is, eithering creating or updating marks of the student, based on subject variation, exam_results and in bulk. For that, I've used bulk create with update conflicts flag. Here is the current model class Marks(Common): exam_results = models.ForeignKey( "ExamResults", on_delete=models.CASCADE, related_name="marks" ) subject_variation = models.ForeignKey( "SubjectVariation", on_delete=models.CASCADE, related_name="marks" ) student = models.ForeignKey( "Student", on_delete=models.CASCADE, related_name="marks" ) marks_obtained = models.FloatField() objects = BaseModelManager()class Marks(Common): now, when I do bulk create, it asks for unique fields, and since I only want to update marks if there is same exam results, subject variation and student in another instance. So, i add that to unique fields of bulk create. class MarksUpsertSerializer(serializers.ModelSerializer): class Meta: model = Marks fields = ("exam_results", "subject_variation", "marks_obtained") class BulkMarksUpsertSerializer(serializers.Serializer): marks = MarksUpsertSerializer(many=True) def create(self, validated_data): marks = [Marks(**item) for item in validated_data["marks"]] marks = Marks.objects.bulk_create( marks, update_conflicts=True, update_fields=["marks_obtained"], unique_fields=["exam_results", "subject_variation"], ) return marks but when I do this, it says there is no unique or exclusion constraint matching the ON CONFLICT specification. I assumed its because there's no constraint thats been provided to say that those fields must be unique together, so I added a constraint on … -
Django connection to Postgresql encoding problem
I can not connect Django to PostgreSQL database. It show me an encoding problem: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 86: invalid start byte The problem is in that line: File "C:\Users\Robo\Desktop\Stock\venv\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) I have tried to change encoding in Settings option, but with no results. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "Stocks", "USER": "postgres", "PASSWORD": "password", "HOST": "127.0.0.1", "PORT": "5432", "encoding": "utf-8", } } -
Problem when trying to include Allauth form in django template
I have this custom form templates/account/signup.html {% load i18n %} <h2> custom {% trans "Sign Up" %}</h2> <form class="max-w-[500px]" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-group flex flex-row justify-between w-full mt-2 py-4 px-6 bg-white rounded-xl text-black"> {{ form.username.label_tag }} {{ form.username }} {{ form.username.errors }} </div> <div class="form-group flex flex-row justify-between w-full mt-2 py-4 px-6 bg-white rounded-xl text-black"> {{ form.email.label_tag }} {{ form.email }} {{ form.email.errors }} </div> <div class="form-group flex flex-row justify-between w-full mt-2 py-4 px-6 bg-white rounded-xl text-black"> {{ form.password1.label_tag }} {{ form.password1 }} {{ form.password1.errors }} </div> <div class="form-group flex flex-row justify-between w-full mt-2 py-4 px-6 bg-white rounded-xl text-black"> {{ form.password2.label_tag }} {{ form.password2 }} {{ form.password2.errors }} </div> <button type="submit" class="btn btn-primary mt-4">{% trans "Sign Up" %}</button> </form> when open on its own everything work just as expected, but when i try to include this in base.html <div role="tabpanel" class="tab-content bg-base-100 border-base-300 rounded-box p-6"> {% include "account/signup.html" %} </div> form looks like this: included signup form Any idea how to fix this? When I open the signup.html normaly <a href="{% url 'account_signup' %}">Allauth Signup</a> the form looks OK and I can create new account. I want include this html to … -
can't create, edit or upload ... not enough storage. get 100 gb of storage for ₱89.00 ₱22.25/month for 2 months in Django Python
I have this kind of error in my web application when I reload it appears few seconds during loading, is there any code did I made that shows this error? I've used django framework, and I think there's nothing wrong in the template which I used Vuexy dashboard , i think this is not connected to the google storage and my Pc's storage because I tried it in different Pc but the message still appears Is there any wrong with my development? I appreciated the help -
How do I correctly define the url in Django (error Page not found (404))
(I tried solutions provided in similar questions, but they didn't work). I am learning Django, and building the following project: My project is es. I have 3 apps called event, items_dashboard and item. Each event has one items_dashboard, and zero or more items. When the user is in /event/<event_id>/items_dashboard/index.html, there is a link to add a new item to event <event_id>. This opens a form /item/new/<event_id>. When I fill and submit this form, I get the following error: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/item/new/ Using the URLconf defined in event_site.urls, Django tried these URL patterns, in this order: [name='index'] event/ item/ new/<int:event_id> [name='new'] item/ <int:pk>/ [name='detail'] item/ <int:pk>/delete [name='delete_item'] The current path, item/new/, didn’t match any of these. Question: How do I correctly define the url for this scenario? ================================================================= Support material: My relevant urls.py files are as follows: es/urls.py: urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('event/', include('event.urls', namespace="event")), path('item/', include('item.urls', namespace="item")), # path('', index, name='index') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) item/urls.py: app_name = 'item' urlpatterns = [ # path('new/', views.new, name='new'), path('new/<int:event_id>', views.new, name='new'), path('<int:pk>/', views.detail, name='detail'), ] event/urls.py: app_name = 'event' urlpatterns = [ path('new/', views.new, name='new'), path('<int:pk>/', views.detail, name='detail'), path('<int:event_id>/items_dashboard/', include('items_dashboard.urls', namespace='items_dashboard')), path('<int:event_id>/item/', … -
Django: url transition doesn't work, how to fix it?
Good afternoon! I encountered this bug: when clicking on a link, the url changes, but the transition to another page doesn't work. To be more precise: There is a page that displays information about an article (test is the slug of the article): http://127.0.0.1:8001/articles/article/test/ url to go to the update page: http://127.0.0.1:8001/articles/article/test/update/ Composition of the urls.py file: urlpatterns = [ path('', views.index, name='articles_catalog'), path('article/<slug:slug>/<str:author>/', views.details, name='comment_creation'), path('article/<slug:slug>/update/', views.update_article, name='update_article'), path('article/<slug:slug>/', views.details, name='details'), path('new_article/', views.new_article, name='new_article') ] Link to go to: <a href="{% url 'articles:update_article' slug=article.slug %}" id="update_article" target="_self" rel="noreferrer noopener" class="thq-button-filled thq-button-animated" > UPDATE </a> The view itself: @login_required() def update_article(request, slug): print('OK1') article = Article.objects.get(slug=slug) tags = Tag.objects.all() if request.method == 'POST': print('POST') else: form = ArticleForm(instance=article) return render(request, 'articles/create-update.html', {'form': form, 'tags': tags}) As a result, when I click on the link, the url in the address bar changes, but the page itself - remains the same. Please advise me what I might have missed.