Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DB issue (Interface error: connection closed)
Calling all Pythonistas! I'm embarrassed to say, but this issue has been plaguing us for 3 weeks! It's intermittent with no rhyme or reason. Ubuntu 22.04 running Docker containers (uses the solid cookiecutter-django) as a base which we've used successfully for many years. django==4.1.9 gunicorn==20.1.0 psycopg2==2.9.6 When submitting a simple registration form, randomly, but very frequently we get the following error: InterfaceError connection already closed This issue is ALWAYS at django/db/backends/postgresql/base.py in create_cursor at line 269 which is cursor = self.connection.cursor() In Sentry it shows as a "System" error, not an "In-App" error (ie - code flaw). The form: class GuestForm(forms.ModelForm): time = forms.ChoiceField(choices=[]) # time = forms.ChoiceField(choices=[("18:30", "6:30 PM")]) class Meta: model = Guest fields = ["first_name", "last_name", "email", "opt_in"] def __init__(self, *args, **kwargs): logger.debug("=> Init GuestForm") super().__init__(*args, **kwargs) self.fields["time"].choices = get_choices() def clean_time(self): """Return a time.""" cleaned_data = super().clean() hours, minutes = cleaned_data["time"].split(":") try: return datetime.time(int(hours), int(minutes)) except ValueError as exc: raise ValidationError( "Invalid value: %(hours)s %(minutes)", code="invalid", params={"hours": hours, "minutes": minutes} ) from exc The view: class RegisterView(FormView): form_class = GuestForm template_name = "tour/register.html" tourgroup = None @transaction.atomic def form_valid(self, form): """While we are creating a Guest, we are ultimately creating a TourGroup.""" # Create or get … -
Django admin _continue and _addanother not working
I have 3 buttons in django admin: save, save and add another, save and continue. They have their input names in html like _save, _addanother and _continue. All of these buttons do the same thing - save model and redirect to the main page (like when I click on the save button) class StudyFormAdmin(admin.ModelAdmin): list_display = ['name'] fields = ['name'] I found out that response_add method contains redirect functionality (https://github.com/django/django/blob/ef62a3a68c9d558486145a42c0d71ea9a76add9e/django/contrib/admin/options.py#L1316). Then I tried to check what in my request.POST. I add these lines to my model: def response_add(self, request, obj): print(request.POST) return super().response_add(request, obj) Output: <QueryDict: {'csrfmiddlewaretoken': ['2IOoriUmt5IzfIKU7MY53hZ9dgupnM3sNU6ltcaKXXzwmDB73xekyXn55Pw197dF'], 'name': ['adfgdfg']}> I have tried all these buttons for each model I have but response always the same -
How to Fill in django form with a json file?
I'm building a django system that will receive a file and will return a json file and some graphics. The graphics is working but now and i need to fill in a django form with a json file. Basically, when the user make the upload a django form will filled and after that the graphics will return. How can i do that ? -
Django ModelForm CharField changed to ModelChoiceField results in not filled in values in edit mode
I have a model that has owner as CharField that should "house" the username of the owner of the object. I am using a ModelForm to create the form to create the object and the same to edit it later on. Now I want this owner field to be a choice field with the usernames of the current users. This is easily done by adding owner = forms.ModelChoiceField.... to the ModelForm. This works for creating new objects. Now when editing (going to the /{object_id}/edit link using a GET request) the object I call the ModelForm with the object instance. All fields are then nicely filled in except for my owner field, that just shows the default '-----' and you have to reselect it again. What I want is that that field is filled in with the value it currently is and I can then change it if I want based on the choices of current users. Just to preempt this answer: I do not want to make owner a ForeignKey relationship with user. My minified code: Model: class MyObjects(models.Model): owner = models.CharField(max_length=1024, blank=True) Form: class MyModelForm(ModelForm): owner = forms.ModelChoiceField(queryset = User.objects.all().only('username') def __init__(self, *args, **kwargs): super().__init__....... <bunch of code for … -
How to annotate Django models with new field based on existing fields?
I have Django models with a text field that is just a string. In views, I want to create a new field using annotate with the new fields being a comparison that compares the string of each of these objects text fields with another string, and ordering the queryset by that newly made comparison field. First I have this to get only objects that at least contain the other string: queryset = textObject.objects.filter(text_icontains=queryString) The next part is where I am confused. How can I access each objects text field from this queryset so that I can make a new field with annotate based on these comparisons? -
How display Average Ratings on several pages in Django
Am trying to display the Average ratings on other pages in Django, but it fails. Below its my code. models.py class ActionGame(models.Model): publication_status = models.CharField(max_length=20, choices=STATUS, default="Draft") cid =ShortUUIDField(help_text='Place for the Game ID ', unique=True, max_length=10, length=7, prefix='act',alphabet='abcdfgh12345' ) game_name = models.CharField(max_length=50, help_text='Enter The Name Of Game') game_image = models.ImageField(help_text='Enter The Game Picture Here',default='Action-images/default.jpg',upload_to='Action-images') RATING=[ (1,"★"), (2,"★★"), (3,"★★★"), (4,"★★★★"), (5,"★★★★★"), ] class ActionGameReview(models.Model): game_name =models.ForeignKey(ActionGame, on_delete=models.CASCADE, related_name='reviews') user =models.ForeignKey(User, on_delete=models.CASCADE) review =models.TextField(max_length=5000, blank=False) rating = models.IntegerField(default=1, choices=RATING) created_at=models.DateTimeField(auto_now_add=True) Views.py def action_description(request, cid): description=ActionGame.objects.get(cid=cid) #getting Average Review avg_rating=ActionGameReview.objects.filter(game_name=ActionGame.objects.get(cid=cid)).aggregate(rating=Avg('rating')) # ...... def action(request): action_pages = ActionGame.published.all() # ..... The issue is, l cant display the ratings average in the action view template yet on the action-description Works veryfine. how can l imprement the Average Rating on other pages, Anyone to help me. -
Django Templates: Render a dictionary object stored in a context object?
In Django I have a dictionary object like this: car = { 'color': 'red', 'doors': 4 } I would like to store this dictionary in an Django ORM Model class like so: class Things(models.Model): car = models.TextField() ... other fields My template is a view for Things. Is it possible to access values for car in the template a way such as this: Car color: {{ things_object.car.color }} Note, it is not a requirement to use TextField to save the car dictionary. -
Let Django access serial port in Lubuntu
So, I need my Django to access the serial port I'm correctly using it via pyserial package the issue is that, every time I boot the OS I got the error of Access denied. The only way to make it work is to grant access to the specific serial for everyone via sudo chmod 666 /dev/ttyUSB0 Is there a way to let Django access the serial anyway, instead of let eveyone access it with 666? -
Django race conditions between create() and get()
Since our last release a range of what seems can only DB race conditions have been happening.We use python 3.10, django-rq, Django 4 and Postgres. In one case: x = Model.objects.create() job.delay(x=x) In the job we call Model.objects.get(id=x.id) and it returns nothing. This is happening roughly 1 in 5 times from logs In another case we create the object, add it to a list then act on the list and again it works most of the time but we are getting one off 'matching query does not exist.' errors. I am completely stumped as to what I should do, I cant find many similar issues and can't recreate the issues in my test environment. My best assumption is too many writes to the DB so the transactions aren't being committed by the time the code tries to get the objects again. Any help/advice would be amazing Have gone through the code step by step to ensure the logic is sound Have tried recreating a 'busy' DB but have had no success there Have tried broken data etc but it all gets caught and our logs don't suggest anything like this either -
Enable adding a model field choices to Django admin dashboard and also be able to add or delete the choices
The normal way of interacting with a django model is by using admin.site.register(my_model) in admin.py file. If you want to enforce model's field validation you use the choices field option like this in models.py file. from django.db import models MY_CHOICES=[ ('A','choice 1'), ('B','choice 2'), ('C','choice 3'), .... ] class MY_MODEL(models.Model): ....Some other fields/columns.... options=models.CharField(max_length=2,choices=MY_CHOICES) How would I go about displaying the choices in the admin dashboard and also be able to add new types of choices? Also, is it possible to enforce validation by importing values from the database as field options? I tried having another model that will be a table containing the value and descriptions columns. class MY_CHOICES_MODEL(models.Model): value=models.CharField(max_length=2,..) descriptions=models.TextFeild(blank=False) Trying to pass this around to another models field options is the challenge -
Django model Attributes for Booking system
I'm itermediate in Django ... I work on Booking system with Django. I have two main models : 1.Service & 2.Reservation Service is like this: class AllService(models.Model): title = models.CharField(max_length=100) active = models.BooleanField(default=True) slug_service = models.SlugField(allow_unicode=True, max_length=100, unique=True, default='-') pic = models.ImageField(upload_to='service/') current_queue = models.PositiveSmallIntegerField(default=0) max_queue = models.PositiveSmallIntegerField(default=5) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='services') description = models.TextField() created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now=True) price = models.FloatField(null=True, blank=True, default=1000) service_off = models.FloatField(null=True, blank=True, validators=[MinValueValidator(0.0), MaxValueValidator(0.2)]) def full_queue(self): if self.current_limit > self.max_limit: self.is_available = False @property def remaining_queue(self): return (self.max_limit - self.current_limit) def adding_in_queue(self): k = self.current_limit k += 1 self.current_limit = k return self.current_limit def reset_queue(self): if datetime.now()==time(hour=0, minute=0, second=0.00): self.current_limit=0 and the Reservation is like this : class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reservations') service = models.ForeignKey(AllService, on_delete=models.CASCADE, related_name='reservation') pick_date = models.DateField() description = models.TextField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} {self.service}" class Meta: ordering = ['-created_at'] def clean(self): if self.pick_date < timezone.localdate(): raise ValidationError("day was passed") else: return super().clean() def adding_user_to_queue(self): AllService.adding_in_queue() what I try to do is : when someone choose a service in the Reservation model the "adding_user_to_queue" triger the "adding_in_queue()" method and add up the current_limit field by one, but it doesn't work! I see … -
Pytorch RuntimeError: mat1 & mat2 shapes cannot be multiplied(1x2 and 10000x100)
I am trying to build a spam classifier. However, when sending a POST request, I am getting this error. RuntimeError at /classify/ mat1 and mat2 shapes cannot be multiplied (1x2 and 10000x100) Yes, it's quite straightforward, but even when adjusting the variables, I still get the same result. How can I solve this issue? My model.py file: import nltk from nltk.stem import PorterStemmer import re import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from sklearn.feature_extraction.text import CountVectorizer from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('punkt') try: wordnet.ensure_loaded() except LookupError: nltk.download('wordnet') class LogisticRegression(nn.Module): def __init__(self): super(LogisticRegression, self).__init__() self.linear1 = nn.Linear(10000, 100) self.linear2 = nn.Linear(100, 10) self.linear3 = nn.Linear(10, 2) def forward(self, x): x = torch.flatten(x) x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x def classify_spam(message): model = LogisticRegression() model.load_state_dict(torch.load('W:/SpamOrHamProject/SpamOrHamBack/api/AIModel/SpamClassification.pth')) model.eval() cv = CountVectorizer(max_features=10000) processed_message = preprocess_message(message) vectorized_message = cv.fit_transform([processed_message]).toarray() with torch.no_grad(): tensor_message = Variable(torch.from_numpy(vectorized_message)).float() output = model(tensor_message) _, predicted_label = torch.max(output, 0) return 'Spam' if predicted_label.item() == 1 else 'Not Spam' def preprocess_message(message): remove_non_alphabets = lambda x: re.sub(r'[^a-zA-Z]', ' ', x) tokenize = lambda x: word_tokenize(x) ps = PorterStemmer() stem = lambda w: [ps.stem(x) for … -
Getting "404 Error: Page not Found" in Django-ninja API
I've faced this problem with all APIs for any application in the project. To be honest, I've no idea what triggers the problem. Probably, wrong import module or mismatch in urls. I'd like to show you my project structure for better understadning: Project structure Here's my code from news/views.py: from asgiref.sync import sync_to_async # Create your views here. from django.core.exceptions import ObjectDoesNotExist from ninja import Router from ninja.errors import HttpError from .models import News from .schemas import NewsIn router = Router(tags=["News"]) @router.post("/") async def create_news(request, data: NewsIn): news = await sync_to_async(News.objects.create)(**data.dict()) return {"id": news.id} @router.put("/{news_id}/") async def update_news(request, news_id: int, data: NewsIn): try: news = await sync_to_async(News.objects.get(id=news_id)) for key, value in data.dict().items(): setattr(news, key, value) await sync_to_async(news.save()) return {"success": True} except ObjectDoesNotExist: raise HttpError(404, "News not found") @router.delete("/{news_id}/") async def delete_news(request, news_id: int): try: news = await sync_to_async(News.objects.get(id=news_id)) await sync_to_async(news.delete()) return {"success": True} except ObjectDoesNotExist: raise HttpError(404, "News not found") And then code from core/urls.py: `from django.contrib import admin from django.urls import path from ninja import NinjaAPI from news.views import router as news_router from partners.views import router as partners_router from educational_programs_and_categories.views import program_router, category_router api = NinjaAPI() urlpatterns = [ path("admin/", admin.site.urls), path("api/", api.urls), ] api.add_router("news", news_router) api.add_router("partners", partners_router) api.add_router("educational_programs", … -
am having this error trying to run my django project runserver is not working
Traceback (most recent call last): File "C:\Users\user\Desktop\TECH STUDIO FILES\Ecommerce\ec\manage.py", line 22, in main() File "C:\Users\user\Desktop\TECH STUDIO FILES\Ecommerce\ec\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 399, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 261, in fetch_command commands = get_commands() ^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 107, in get_commands apps = settings.INSTALLED_APPS ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init_.py", line 54, in getattr self.setup(name) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init.py", line 50, in _setup self.configure_logging() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init.py", line 72, in configure_logging from django.utils.log import DEFAULT_LOGGING File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\log.py", line 7, in from django.views.debug import ExceptionReporter, get_exception_reporter_filter File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\debug.py", line 12, in from django.template import Template, Context, TemplateDoesNotExist File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template_init.py", line 53, in from django.template.base import (ALLOWED_VARIABLE_CHARS, BLOCK_TAG_END, File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\base.py", line 19, in from django.utils.html import escape File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\html.py", line 14, in from .html_parser import HTMLParser File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\html_parser.py", line 12, in HTMLParseError = _html_parser.HTMLParseError ^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'html.parser' has no attribute 'HTMLParseError'. Did you mean: 'HTMLParser'? every thing but the server fails to run -
Using PyOTP library,giving message wrong OTP
I am using PyOtp library to generate 6 digit otp ,the backend I am using is python django and the frontend is react. My issue is that sometimes(not always) when I generate OTP and click to verify OTP,I enter the correct OTP which is generated but it gives me wrong OTP message and then when I resend OTP,it takes it as correct one.I am not able to figure out that why even after entering the correct OTP ,it is saying me that it is wrong OTP.What could be the issue.I am not using the latest version of PyOTP,could that be an issue or it is something related to time sync. Kindly help me on this. Thnakyou I used the library implemented in API created in python and integrated it in react. -
DRF formdata with file and nested array of objects not taking nested array of objects
Unable to send nested objects when using formdata. Since I have large number of files using base64 is not a solution. current solution was to use JSON.stringify from client side for product_timings and send it as a single field, But I would like to know if normal modal field with file upload is possible with DRF. Here is my APIView class ProductCreateApi(APIView): permission_classes = [permissions.DjangoModelPermissions] queryset = Product.objects.all().order_by("-created_at") parser_class = [MultiPartParser, FormParser, JSONParser, FileUploadParser] class ProductCreateSerializer(serializers.ModelSerializer): class ProductCreateProductTimingSerializer(serializers.ModelSerializer): class Meta: model = ProductTiming fields = ['start_time', 'end_time'] product_timings = ProductCreateProductTimingSerializer(write_only=True, many=True) product_images = serializers.ListField( child=serializers.ImageField(allow_empty_file=False, use_url=False), write_only=True ) class Meta: model = Product fields = '__all__' In post man I tired product_timings[0][start_time]: 09:30:00 product_timings[0][start_time]: 09:30:00 Still it is throwing validation error messages like { "product_timings": [ { "start_time": [ "This field is required." ], "end_time": [ "This field is required." ] } ] } Please note neither base64 image field for product_images nor single JSON field for product_timings is not the solution I'm looking for. -
Something similar to Counter in a Django table
I have a table in sqlite3 with a column that tells me the winners of a game: (computer = 1, human = 2, tie = 0) The model (I'm working on django) is something like this, at least the necessary part: class GameWinners(models.Model): CHOICES = [(0, 'Draw'), (1, 'Computer'), (2, 'Human')] game_winner = models.IntegerField(choices=CHOICES) I would like to obtain a dictionary that counts me the times that each one has won or the ties. something similar to Counter from collections: games = {0: 27, 1: 125, 2: 170} I know that I could do it this way: tie = GameWinners.objects.filter(game_winner=0).count() computer = GameWinners.objects.filter(game_winner=1).count() human = GameWinners.objects.filter(game_winner=2).count() games = {0: tie, 1: computer, 2: human} But I guess there must be a better way to do it. -
JavaScript: Problem accessing 'change' event for a file input
Aim I have two inputs: (1) a 'file-input', and (2) a 'text-input' I want to listen for a 'change' in 'file-input' (i.e. successful choice of file), and upon such a change set the 'text-input' value to the name of the file. Problem The 'change' event is not triggering when I use addEventListener When I use the input's 'onchange' attribute, it does trigger, but I still don't get access to files Context: This is for a Django project, with Bootstrap 5 on the frontend (NO JQuery). I am using Django Crispy Forms where possible, though I have removed them from this file (to see whether that was what was causing the problem - alas, it wasn't). Attempted Solutions I know this should be easy. I have seen lots of similar posts about this, and I set up a 'dummy' HTML script to ensure I'm not going mad. This is posted below and it works perfectly. <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <input type="file" name="file" id="file-input" accept=".mp3,.mp4,.mpeg,.mpga,.m4a,.wav,.webm"> <input type="text" name="text" id="text-input"> <script> const fileInput = document.getElementById("file-input"); const textInput = document.getElementById("text-input"); console.log(fileInput); console.log(textInput); fileInput.addEventListener('change', () => { console.log('change registered'); if (fileInput.files.length > 0) { console.log(fileInput.files); console.log(fileInput.files[0].name); textInput.value = fileInput.files[0].name; } }); … -
How to show the ForeignKey' content in Django template
I am beginner in django, there is a question i am fronting is that how to show the content of ForeignKey item, for example i have a table called company, there is a field "parentcompany" for storage the ForeignKey(UID) with the parentcompany, all the company is created on the this company table. I already been success to create this relationship, but I can not show the parentcompany's name in the template. I already tried using this {{company.parentcompany_id.companyName}}, but nothing is shown. -
How can I delete ManyToManyField on Django Model (used in Wagtail Page inheritor)?
I have such field: from wagtail.models import Page class MyModel(Page): ... many_to_many_field = models.ManyToManyField(ToClass, blank=False, related_name='+', verbose_name=_("My models")) ... I tried simply to comment it like this: from wagtail.models import Page class MyModel(Page): ... # many_to_many_field = models.ManyToManyField(ToClass, blank=False, related_name='+', verbose_name=_("My models")) But I've got 'django.core.exceptions.FieldError' while was executing 'python manage.py makemigrations': Traceback (most recent call last): File "D:\projects\myapp\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "D:\Python311\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Python311\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 443, in execute self.check() File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\checks.py", line 70, in get_form_class_check if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\panels\base.py", line 162, in get_form_class return get_form_for_model( ^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\panels\base.py", line 48, in get_form_for_model return metaclass(class_name, tuple(bases), form_class_attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\forms\models.py", line 124, in __new__ new_class = super(WagtailAdminModelFormMetaclass, cls).__new__( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ new_class = super().__new__(mcs, name, bases, attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\modelcluster\forms.py", line 259, in __new__ new_class = super().__new__(cls, name, bases, attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\django\forms\models.py", line 327, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (many_to_many_field) specified for MyModel What is wrong? How can I delete it? -
post name, email and role in django backend, react frontend
i want to the admin to post name, email and role of a user using frontend, and its stored in backend of django, please note that i dont want the admin to store the password, the user will later on add it djangocode: class UserSerializer(serializers.ModelSerializer): class Meta: model = UserAccount fields = ['email', 'name', 'username', 'password', 'role'] def create(self, validated_data): password = validated_data('password') username = validated_data('username') user = UserAccount( email=validated_data['email'], role=validated_data['role'], name=validated_data['name'] ) if username is not None: username=validated_data['username'], if password is not None: user.set_password(validated_data['password']) user.save() return user react code: const handleSubmit = (event) => { event.preventDefault(); const data = { name : name, email : email, role: role }; console.log("data is "+data); axios.post('http://127.0.0.1:8000/api/register/', data) .then(response => console.log("got it"+response.data)) .catch(error => console.log(error)); console.log('name:', name); console.log('email:', email); console.log('role:', role); -
How to store an object id in django admin
I got a top model like Project, and many sub models like Store, Task, Bug, TestCase. I want to seprate project as isolated workspace in admin. when I select a project, store the current project id, and when I create sub model objects or view change list, all object is belong to this project. -
Unable to read django table in admin or through API
I've added few tables to django app, and two of them are acting weird. I'm unable to read these 2 tables through django admin or postman API however, I'm able to read these table through postgres(pg admin). I'm getting index error in django-admin and postman on these two tables(or django models). These tables has data in them as verified using pgAdmin. The tables are stored in postgres, and the DB is connected to django aplication. Any idea why this could be happening and possible solutions? -
Bad Request (400) on adding new domain from hostinger on vercel hosting
I have purchased domain from hostinger after adding the domain in the domain and changing the nameserver of hostinger to ns1.vercel-dns.com ns2.vercel-dns.com i validated the configuration but when i look the site it gives Bad Request (400) error . pushpblogs.fun Valid Configuration Redirects to www.pushpblogs.fun www.pushpblogs.fun Production Valid Configuration Assigned to main i waited for the dns to apply for 24 hours but still no change made. -
Mayan EDMS ,Calling the API remotely using AJAX getting CORS error
I am creating a new webapp that is going to be making calls to the Mayan EDMS API with javascript/ajax Currently i am getting a CORS error. My mayan installation is running inside a docker container. I did find in the settings for Django in the admin->settings-> Django there is a ALLOWED_HOSTS but there is a green checkmark which indicates it is overwritten by a env var. Any Idea what env var that would be. there is nothing obvious in the .env for the docker file It appears that django-cors-headers is there as well. Just not sure how to config How are other people dealing with this? Thanks randy