Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reference a model within a model in HTML for Django
I am trying to make a survey tool that has many questions within a model. Here's what I embedded in my models page: class Survey(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Question(models.Model): title = models.CharField(max_length=100) content = models.TextField() survey = models.ForeignKey(Survey, on_delete=models.CASCADE) Here is my survey view class SurveyDetailView(DetailView): model = Survey And here is the HTML code for the survey detail view {% for question in questions %} <h2><a class="article-title" href="#">{{ question.title }}</a></h2> {% endfor %} While in my admin, there are several questions associated with a survey, it doesn't show this in the HTML when loaded. What am I missing here? -
SystemError: ('Error calling Moodle API\n', {'exception': 'invalid_parameter_exception', 'errorcode': 'invalidparameter',
I'm trying to create users on moodle in bulk by given command: value=[username, firstname, lastname, email,password] #values = {key: self.__dict__[key] for key in value} call('core_user_create_users', users=value) Can anyone please tell me how to fix it. -
How can i use Mongoengine with Django 3.0?
I'm using MongoDB on my Django project, and i've recently moved to Django 3.0. Unfortunately, Djongo does not support Django 3.0 yet, so i want to make it work with Mongoengine, but i don't really know how to do it, here is what i have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ... } }, 'secondDB': { 'ENGINE': 'djongo', 'NAME': 'myDB', 'HOST': 'mongodb+srv://user:mypass@test-2liju.mongodb.net/test?retryWrites=true', } } How can i move the current configuration to Mongoengine? -
Vertica as Django Backend
I am trying to connect vertica as Django backend. I am upgrading the code in the below repository so that it works for the latest version of Django and Vertica. Github Link: https://github.com/rutube/django_vertica_backend I get the below error when i am trying to run the Django server. Can anyone help me or point me in the right direction? C:\Users\HMARUKALA\Desktop\Django\django_vertica_backend-master>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HMARUKALA\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", … -
why list of users are not shown in the django template?
my goal is to show user list on the template in django. but it's not rendering the users. accounts/models.py: class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) name = models.CharField(max_length=200, blank=True) accounts/admin.py: class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'age', 'is_staff', ] admin.site.register(CustomUser, CustomUserAdmin) accounts/form.py: class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = UserCreationForm.Meta.fields + ('age',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields accounts/views.py: class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class UsersView(TemplateView): template_name='homepage.html' def get_context_data(self,**kwargs): context = super(UsersView,self).get_context_data(**kwargs) context['object_list'] = CustomUser.objects.all() return context and blogapp/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/',include('accounts.urls')), path('accounts/',include('django.contrib.auth.urls')), path('',TemplateView.as_view(template_name='homepage.html'),name='homepage'), ] templates/homepage.html: {% block content %} <h1>Online users</h1> <ul> {% for user in object_list %} <li class="user">{{ user }}</li> {% endfor %} </ul> {% endblock content %} when i execute python manage.py runserver it is just showing the head line Online users but there is no list of users. i have created three users in admin but it is not showing anything in the template and there is no error. will you please help me on this please? -
How to disable "Django Login" page when trying to access swagger api in browser?
I am getting a blank page with just a "Django Login" link when trying to access generated swagger docs. I am using drf_yasg library to render swagger documentation. Code to generate swagger docs is similar to mentioned in swagger docs. schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) -
`forms.ValidationError` returns error: 'bool' object has no attribute 'get'
Validation works fine, but if all fields are fill with correct data, error appears. models.py: class Venue(models.Model): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, blank=True) title = models.CharField(max_length=300, blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True) address = models.CharField(max_length=300, blank=True) phone = models.CharField(max_length=20, default='', blank=True) email = models.CharField(max_length=100, default='', blank=True) site = models.CharField(max_length=100, default='', blank=True) facebook = models.CharField(max_length=100, default='', blank=True) instagram = models.CharField(max_length=100, default='', blank=True) content = models.TextField(blank=True) rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2, blank=True) created_date = models.DateTimeField(default=timezone.now) approved_venue = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) forms.py: class VenueForm(forms.ModelForm): class Meta: model = Venue fields = [ 'title', 'content', 'city', 'address', 'phone', 'email', 'site', 'facebook', 'instagram', ] def clean(self): error_dict = {} title_data = self.cleaned_data.get('title') content_data = self.cleaned_data.get('content') city_data = self.cleaned_data.get('city') address_data = self.cleaned_data.get('address') phone_data = self.cleaned_data.get('phone') email_data = self.cleaned_data.get('email') if title_data is None or len(title_data) < 3: error_dict['title'] = forms.ValidationError('Моля, въведете име от поне 3 символа!') if content_data is None or len(content_data) < 10: error_dict['content'] = forms.ValidationError('Моля, въведете описание от поне 10 символа!') if city_data is None: error_dict['city'] = forms.ValidationError('Моля, изберете валиден град!') if address_data is None or len(address_data) < 5: error_dict['address'] = forms.ValidationError('Моля, въведете валиден адрес!') if phone_data is None or len(phone_data) != 10: error_dict['phone'] = forms.ValidationError('Моля, въведете валиден телефонен номер във … -
Adding MongoDB to Django 3.0
I'm trying to add MongoDB to my Django 3.0 project, i'm already using MySQL as the first DB, this would be the second. 'secondDB': { 'ENGINE': 'django_mongodb_engine', 'NAME': 'mydb', 'HOST': 'mongodb+srv://user:pass@test-2liju.mongodb.net/test?retryWrites=true', } But this configuration will throw the following error: Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' How can i fix this? Using djongo is not an option, since it doesn't support Django 3.0 -
How to check for a substring in Django update_or_create() method?
Let's say I have the following object that I want to push to my database using the according model: Object { 'object_name': 'Foo', 'value': 100,00 } and want to update the value of Foo Bar in the database. How to make Django check for Foo being a substring of a database object (in this case Foo Bar) to avoid duplicates? obj, created = foo_model.objects.update_or_create( object_name=object_name, defaults={ 'value': value, } ) (so the goal is to update the value of the object Foo Bar instead of creating a new object Foo since it is a substring of an already existing object). -
Getting: This backend doesn't support absolute paths when deploying Django App on Azure
I am using Azure App Service (Linux) to deploy my Django app. The app is very simple it ask user to upload the file and then I go through parsing the file. I follow through tutorial link, which is very descriptive and helpful. But it does not help to resolve error when my code is trying to access the file which is uploaded by user, I can see the file is uploaded in Media container but when following code is trying to access the file it gives an error: Django Version: 3.0.6 Exception Type: NotImplementedError Exception Value: This backend doesn't support absolute paths. Exception Location: /antenv/lib/python3.8/site-packages/django/core/files/storage.py in path, line 116 Here is the view where I am getting this error: def parse_upload_file(request, pk, *args, **kwargs): form = DocumentForm() context = { 'form': form } if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): fileform = form.save(commit=False) fileform.UploadedDate = date.today() fileform.save() fl = Document.objects.get(pk=fileform.Id) up_files = [] up_files.append({'Type': fl.DocumentType, 'Directory': os.path.dirname(fl.DocumentContent.path), 'FileName': os.path.basename(fl.DocumentContent.path), 'Path': fl.DocumentContent.path} ) #Initialize The Reconcilation Instance insRecon = ParseFile() (fl_one, fl_two) = insRecon.StartParsing(up_files) if (os.path.isfile(fl_one) and os.path.isfile(fl_two)): wrkdir = os.path.dirname(fl_one) storeRecs = storeRecs(wrkdir) storeRecs.copyDataToDatabase() else: form=DocumentForm() return redirect('Upload:dashboard') return render(request, "upload/dashboard.html", context) Any help in this … -
Adding user restrictions on who can edit posts in Django
I'm trying to add restrictions on my site so that only the person who added a product or post can edit/delete that product or post. Currently, the edit button is visible to anyone so it's not ideal. I've had a good crack at it, but something is still wrong as the edit button still shows up even when I'm not the post creator. The edit_forum_post view I've created: @login_required def edit_forum_post(request, post_id): """ Create a view that allows us to edit a post """ post = get_object_or_404(Post, pk=pk) registered_user = request.user.id creator = post.creator.id if not logged_user == creator: messages.error(request, 'You are unable to edit this post') return redirect('get_forum') if request.method == "POST": edit_post = ForumPostForm(request.POST, request.FILES, instance=post) if edit_post.is_valid(): edit_post.save() messages.success(request, 'You have successfully updated your post') return redirect('forum_post_details', post_id) edit_post = CreatePost(instance=post) context = { 'form': edit_post, 'post': post } return render(request, 'forum_post_form.html', context) The clause I have added onto the Edit post button: {% if registered_user == post.creator %} <a href="{% url 'edit_forum_post' post.id %}" class="btn btn-outline-warning">Edit Post</a> {% endif %} Any feedback is greatly appreciated! -
How to enable logging for deployed Django app running on GAE (Google App Engine)
When using DEBUG = False for settings.py, Django will not output any errors even when severe (Http status 500) errors occur. I've tried to add a LOGGING entry for my settings.py, but it seems like when it is deployed on GAE, the server fail instantly upon every request. How do you enable error logging (with traceback) for a deployed django app running on GAE that is visible in the GAE interface? -
Django CSS buggy
I've configured django to serve static files. In my html templates, if the css is inline (<style>), it works fine. If put into the static css file, only some of it works. After updating static files, python manage.py collectstatic is run. My files are in a virtual environment css file inside of static/ll_app_static/css /* cross site */ a:hover { text-decoration: none; } /* override bootstrap */ .jumbotron { background-image: linear-gradient(-90deg, #a4d4f5, #4da2f1,#5474df); border-radius: 12px; } .alert-danger { color: #af5959 ; text-align: center; } .wrap { word-wrap: break-word; min-width: 160px; max-width: 160px; white-space: normal; overflow: hidden; text-overflow: ellipsis; } table{ max-width: 100%; table-layout:fixed; overflow-wrap: break-word; } table .tsm{ width: 5%; } /* buttons */ .btn-gray { border: none; background-color: rgb(225, 234, 238) ; color: rgb(106, 125, 150); } .btn-gray:hover { background-color: rgb(225, 239, 245); color: rgb(75, 117, 138); } .btn-red { border: none; background-color: #d45c5c; color: #fdf3f3; } .btn-red:hover { text-decoration: none; background-color: #e27b7b; color: #fdf3f3; } /* specific buttons, as otherwise there is flicker delay when overriding primary/success */ .btn-green { background-color: rgb(104, 228, 80); border: none; color: rgb(58, 134, 38); padding: 0.5em 2em; } .btn-green:hover { text-decoration: none; background-color: rgb(126, 236, 104); color: rgb(58, 134, 38); } .btn-blue { … -
getting error while restting password with gmail in django
i'm getting error when i'm doing password reset with gmail in django. The error is SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/? p=WantAuthError n85sm521229qkn.31 - gsmtp', 'webmaster@localhost') my settings.py: LOGIN_URL = 'login' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') my urls.py: urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), ] -
How can I get an ID value from a hidden input in Django?
When I create a populated form with the id in a hidden input, it looks alright. When checking the source, I see this rendered: <input type="hidden" name="id" value="61" id="id_id"> But when submitting the form, the id is not coming through. I am using the ModelForm. I got all other fields on the next page but not id. What is the reason for that? Am I creating the hidden field in wrong way? id = forms.CharField(widget=forms.HiddenInput) -
Como pegar uma função javascript com django ? How i get a function javascript with django?
Eu tenho um campo input que eu pego o mês digitado com uma função javascript, e eu quero compará-la com um atributo de um model do django // I have a field I capture the month typed with a javascript function, and I want to compare with an attribute of a django model eu consigo pegar meu todos meus objetos com django, exemplo: // I can to get all my objects with django, example: view.py def produtoPorMes(request): produtos = Produto.objects.all() return render(request, 'app_controlProduct/mensalControl.html', {'produtos':produtos}) Nessa funcao eu pego todos os objetos do produto // In this function I can to get all products' object. mensalControl.html minha função javascript: // my javascript function: function verificaMes(){ var mes = document.getElementById('mes').value; if (mes == "" || mes == null) { alert('Digite um mês válido'); } return mes; } mes é um input que digito // mes is a input i typed {% for produto in produtos %} {% if produto.date.month == verificaMes() %} ?? Como faço para comparar / how did i do to compare ??? {% endif %} {% endfor %} Eu quero comparar o mês do meu produto com o mês que eu digitei no input // I want to compare … -
How can i use MongoDB with Django 3.0?
I've always been using MongoDB on my Django project, but now that i updated my Django version to 3.0, i can no longer make queries to my database. Every time i try to make a query, my code will just freeze. I tried to update my Djongo version, but every time i do it, my Django version will be downgraded to Django 2. I made some research and found that Djongo has compatibility problems with Django 3. However, on the github repository i'm seeing support for django 3.0. Can i use it with Django 3.0, then? And if i can't, is there any way to use MongoDB without Djongo and without having to change my whole code? -
Having trouble with Serializing a Project and Images (Images don't show up in the api view list)
I am very new to Django and decided to create a project to increase my skills/gain experience. I'm having trouble with images link or name not showing up in the api view list using Django-rest-framework. As seen below api_view So far I was able to create two models one that contains the project information and another model that allows multiple images to be associated with the project. model You can upload the images through the admin page. As seen below admin_page I think the main culprit is my serializers and the way it was setup. serializers Here is my view if it helps view (The red underline is from my linter thinking there is an error) Any help will be appreciated! Sorry if I the way the question was phrased was weird (need to work on asking the right question) -
How Does Django Createsuperuser Know How To Parse My Date Field
I created a customized User module that adds a few extra fields: class User(AbstractUser): """User modle for staff, clients and customers""" username = None # remove username from the model email = models.EmailField("email address", unique=True) # """Email of user this will be used for login""" address = models.OneToOneField(Address, on_delete = models.PROTECT, null=True, blank=True) """:class:`Postal Address` associated with the User""" birth_date = models.DateField() """Date of birth of User""" phone = models.CharField(max_length=15) """Phone number of User""" org = models.ForeignKey(Organization, on_delete=models.PROTECT, null=True, blank=True) """:class:`Organization` User is associated with""" # changes for using email instead of username USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'birth_date', 'phone'] objects = UserManager() def __str__(self): return F"{self.email} {self.first_name} {self.last_name}" When I ran the createsuperuser command it asked me for birth_date (and knew how to parse it). I entered 2020-01-01 for the value. Curious, I then temporarily put these statements in the createsuperuser function: print("*****") print(extra_fields) print("*****")``` and got: {'first_name': 'super', 'last_name': 'user', 'birth_date': datetime.date(2020, 1, 1), 'phone': '12345', 'is_staff': True, 'is_superuser': True, 'is_active': True} How did it know to use datetime.date and how to parse it correctly? More importantly, how can I make similar behavior for a custom related object? -
Django annotation with filter ignoring primary key resutling in too many annotated items
Using Django 3.0.6 and python3.8, given following models class Plants(models.Model): plantid = models.TextField(primary_key=True, unique=True) class Pollutions(models.Model): pollutionsid = models.IntegerField(unique=True, primary_key=True) year = models.IntegerField() plantid = models.ForeignKey(Plants, models.DO_NOTHING, db_column='plantid') pollutant = models.TextField() releasesto = models.TextField(blank=True, null=True) amount = models.FloatField(db_column="amount", blank=True, null=True) class Meta: managed = False db_table = 'pollutions' unique_together = (('plantid', 'releasesto', 'pollutant', 'year')) class Monthp(models.Model): monthpid = models.IntegerField(unique=True, primary_key=True) year = models.IntegerField() month = models.IntegerField() plantid = models.ForeignKey(Plants, models.DO_NOTHING, db_column='plantid') power = models.IntegerField(null=False) class Meta: managed = False db_table = 'monthp' unique_together = ('plantid', 'year', 'month') I'd like to annotate - based on a foreign key relationship and a fiter a value, particulary - to each plant the amount of co2 and the Sum of its power for a given year. For sake of debugging having replaced Sum by Count using the following query: annotated = tmp.all().annotate( energy=Count('monthp__power', filter=Q(monthp__year=YEAR)), co2=Count('pollutions__amount', filter=Q(pollutions__year=YEAR, pollutions__pollutant="CO2", pollutions__releasesto="Air"))) However this returns too many items (a wrong number using Sum, respectively) annotated.first().co2 # 60, but it should be 1 annotated.first().energy # 252, but it should be 1 although my database guarantees - as denoted, that (plantid, year, month) and (plantid, releasesto, pollutant, year) are unique together, which can easily be demonstrated: pl = annotated.first().plantid testplant … -
How can I set inputs dynamically in Django using JavaScript?
I have the following models.py file which has the table and modelform. I'm working with has and the HTML template and I want some JavaScript code to multiply the value of rate input and quantity input then set it dynamically into total cost input before I click on submit. ModelForm: class ExpenseBasedTransactionForm(ModelForm): def __init__(self, *args, **kwargs): super(ExpenseBasedTransactionForm, self).__init__(*args, **kwargs) eb_client = Clientele.objects.filter(clientele_type__icontains='eb client').values_list("id", "clientele_name") eb_main = [] for i in eb_client: k = list(i) k[0] = str(k[0]) l = (tuple(k)) eb_main.append(l) self.fields['eb_client'] = ChoiceField(choices=eb_main, label='EB Client', ) class Meta: model = ExpenseBasedTransaction # fields = '__all__' #to include all the fields in the form # specify what fields to be included in the form fields = ['date_initiated', 'eb_client', 'rate', 'quantity', 'total_cost'] widgets = { 'date_initiated': AdminDateWidget(), 'rate': NumberInput(attrs={'class': 'form-control', 'id': 'rate'}), 'quantity': NumberInput(attrs={'class': 'form-control', 'id': 'quantity'}), 'total_cost': NumberInput(attrs={'class': 'form-control', 'id': 'total'}), } html: {% extends "base.html" %} {% load bootstrap3%} {% block content %} <div class="content-wrapper" id="tab"> <div class="content"> <div class="head"> <div class="row"> <div class="col-sm-7 title" > <span><i class="fa fa-pencil"></i> Record An Expense</span> </div> </div> </div> <div class="content padding table-responsive" > <div class="wrapper"> <form method="post"> {% csrf_token %} {% bootstrap_form form %} <br> <button type="reset" class="btn btn-warning m-sm-right"><i class="fa fa-trash-o … -
django form.is_valid returns false after adding fields dynamically to the form
I have a form like this, class UniqueUrlForm(forms.ModelForm): cc_number = cc_form.CardNumberField(label='Card Number') cc_expiry = cc_form.CardExpiryField(label='Expiration Date') cc_code = cc_form.SecurityCodeField(label='CVV/CVC') class Meta: model = Transactions fields = ['customer_name', 'customer_phone', 'customer_email', 'total_amount', 'cc_number', 'cc_expiry', 'cc_code'] def __init__(self, *args, **kwargs): super().__init__() store_id = kwargs.get("store_id", "1") payment_page = get_object_or_404( PaymentPageDisplayDetails.objects.filter(store_id=store_id).values("payment_fields_visible")) with urllib.request.urlopen(payment_page['payment_fields_visible']) as url: display_fields = json.loads(url.read().decode()) for field_name in display_fields: self.fields[field_name] = forms.CharField(required=False) and a view like this, def getpaymentpage(request, store_identifier): uniqueurl_form = UniqueUrlForm(request.POST or None, request.FILES or None, {"store_id": 1}) if uniqueurl_form.is_valid(): trx_details = { "amount": uniqueurl_form.cleaned_data['amount'], "customer_email": uniqueurl_form.cleaned_data['customer_email'], "customer_phone": uniqueurl_form.cleaned_data['customer_phone'], "cc_number": uniqueurl_form.cleaned_data['cc_number'], "cc_name": uniqueurl_form.cleaned_data['customer_name'], "cc_month": uniqueurl_form.cleaned_data['cc_month'], "cc_year": uniqueurl_form.cleaned_data['cc_year'], "cvv": uniqueurl_form.cleaned_data['cvv'], } return HttpResponse(trx_details) context = { 'form': { uniqueurl_form, }, "page": store_display, } return render(request, 'unique_url.html', context) I have tried print(uniqueurl_form.errors) it always returns empty and uniqueurl_form.is_valid() as false. Is it because I'm adding dynamic fields to the form. I have referred the following, dynamically add field to a form What am I doing wrong here? Thank you for your suggestions. -
how could upload apidoc in django to server and run it by nginx
I have django project deployed to digitalocean with nginx server & gunicorn it's totally perfect with website domain (myprojectex.com) . Just now I use apidoc service which could generate fully API documentation by node.js, till this moment everything perfect as it's should be in localhost , I tried to upload this update to server but I faced a problem with how could i show a HTML page from outside project ? my project structure like following : ProjectFolder/ │ └── app1/ │ └── app2/ │ └── projectFolder/ │ └── settings.py │ └── urls.py │ └── manage.py │ └── templates/ │ └── page1.html │ └── page2.html │ └── apidoc/ (apidoc service) │ └── index.html │ └── static/ │ └── media/ │ └── main.js │ └── api_project.json │ └── api_data.js │ └── other folders/ example for apidoc/index.html: page As shown apidoc is under django project folder but it's not a part of django project, it's totally separate, it's auto generate from node.js (by npm). Even when I open apidoc/index.html page in browser it's open as static path like this : (/user/folder/folder/apidoc/index.html) after upload (apidoc) folder to server i faced an issue how could open apidoc/index.html page ? I tried to change template … -
DRF- Error when creating a new instance in an M2M through model
I have the following two models: class User(models.Model): user_id = models.CharField( max_length=129, unique=True, ) user_resource = models.ManyToManyField( Resource, through="UserResource", ) occupation = models.CharField(max_length=100, default='null') def __str__(self): return self.user_id and class Article(models.Model): uuid = models.UUIDField(editable=False, unique=True) company = models.ForeignKey( Company, on_delete=models.PROTECT, related_name='article_company_id', ) articleType = models.ForeignKey( ArticleType, on_delete=models.PROTECT, related_name='type', ) date_inserted = models.DateField() def __str__(self): return self.uuid which are modeled with a many-to-many relationship, using this through model: class UserArticle(models.Model): user = models.ForeignKey(User, to_field='user_id', on_delete=models.PROTECT,) article = models.ForeignKey(Article, to_field='uuid', on_delete=models.PROTECT,) posted_as = ArrayField( models.CharField(max_length=100, blank=True),) post_date = models.DateField() class Meta: db_table = "core_user_articles" Here's my view: class BatchUserArticleList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = UserArticle.objects.all() serializer_class = BatchUserArticleSerializer def create(self, request, *args, **kwargs): serializer = BatchUserArticleSerializer(data=request.data) if not serializer.is_valid(): return response.Response({'Message': 'POST failed', 'Errors': serializer.errors}, status.HTTP_400_BAD_REQUEST) self.perform_create(serializer) # equal to serializer.save() return response.Response(serializer.data, status.HTTP_201_CREATED) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) The problem I'm facing is when I want to POST data, of the following format, in the M2M table: { "posted_as": ["news"], "post_date": "2020-05-26", "user": "jhtpo9jkj4WVQc0000GXk0zkkhv7u", "article": [ "11111111", "22222222" ] } The above contains a list of many articles so I used a custom field in my serializer in order to extract each article, create a new UserArticle object … -
Is there something wrong with the way I am calling .makedsn or .cx_Oracle?
My errors consistently point to the cx_oracle line, but I don't see where my code is wrong. I'm working on a remote server, which is why I haven't found much help on other posts about the same error. Any help would be appreciated. Error message : "ORA-12541: TNS: no listener" My code snippet: try: dsn_Oracle = cx_Oracle.makedsn(queryset.first().Host, queryset.first().Port, queryset.first().Database) conn_Oracle = cx_Oracle.connect(queryset.first().UserID, queryset.first().Password, dsn_Oracle) c = conn_Oracle.cursor() except DatabaseError: connected = False self.message_user(request, "Failed to connect.") else: connected = True self.message_user(request, "Succesful connection!") conn_Oracle.close()