Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i get min value in array from JSONField
i have a model and this model have a JSONField class Book(models.Model): data = JSONField() And this field have an array. data = { 'outlet':[ {'price': 100}, {'price': 200}, {'price': 300} ]} I want to get min value of outlet price.I've tried use KeyTextTransform and Min func. I can do easily if outlet not an array. But unfortunately i have to work on array in this case. -
Convert django view to django rest framework APIView
I am trying to convert a django view to APIView, here's the normal view and below is what I tried. Django View @method_decorator([login_required, teacher_required], name='dispatch') class QuizResultsView(DetailView): model = Quiz context_object_name = 'quiz' template_name = 'classroom/teachers/quiz_results.html' def get_context_data (self, **kwargs): quiz = self.get_object() if (quiz.status == 'Assigned'): """Some Code""" cursor = connection.cursor() def dictfetchall (cursor): desc = cursor.description return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] """ Some More Code """ extra_context = {'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes, 'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids, 'driver_num': driver_num, 'lat_lon_orig': lat_lon_orig, 'lat_lon_dest': lat_lon_dest, 'user_pass': user_pass, 'username': username, 'password': password, } kwargs.update(extra_context) return super().get_context_data(**kwargs) else: cursor = connection.cursor() def dictfetchall (cursor): desc = cursor.description return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] cursor.execute('''SELECT STATEMENT''', [quiz.id]) """ Some More Code """ extra_context = {'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes, 'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids} kwargs.update(extra_context) return super().get_context_data(**kwargs) def get_queryset (self): return self.request.user.quizzes.all() According to the documentation I added : REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] } in my settings.py and instead of return super().get_context_data(**kwargs) i used return Response(extra_content) but it doesn't seem to work. What is it that I am doing wrong? Please, help!! -
Django model setup on existing Oracle table
I have a particular situation which I need help clarifying. I have an existing Oracle table with an auto increment ID as a primary key I am creating a django model to sync with that table so i can make use of django's ORM methods such as save(), filter() etc. I read from the django docs the .save() method can perform both a UPDATE and INSERT depending on if the values passed to the primary key results in a True value (i.e. not a None or null). In my table I have two columns which together will form a composite primary key. If I specify primary_key = True on the two attributes on the django model, do I need to remove the primary key tag from oracle table? Also, do i need to specify the unique_together to tell the django model that they are unique or will it be able to derive the index i created in the django oracle table? Thanks. -
Is there any method to connect Vue JS and Django together without using Django REST API
I am a newbie to programming world. I know how to integrate Vue JS and Django by creating the Django REST API and Vue JS(with Axios). Is there any other way I can use the Django and Vue JS together ? Because I felt it hard to make a secure Django Rest API but normal Django templating system comes with in build user authentication and creating web app is super easy. I have used normal Django templating system and added Vue JS through CDN links, it works fine for each page. My real intention was to create a website that do not reload when user clicks each page. Do you recommend AJAX for this purpose ? -
Auto fill the text field after one text field is filled django
Now I am having two text field and I would like to do the following function: Name: Name ID: If I enter the name, then the name id will be auto filled with the corresponding id in my database. Which I already have all the name and name id in my model. my model: Name: xxx abc hehe haha Name ID: 123 456 789 525 Name: xxx Name ID: 123 <--- Auto insert after the xxx is filled -
Why column containing some of the django fields in html table collapsing when rendered to pdf using xhtml2pdf?
I am trying to generate pdf in Django using xhtml2pf. The HTML template consists mostly of HTML table. Django PhoneField and EmailField are getting collapsed while pdf is rendered. Below is the image of pdf generated when passing Django PhoneField and EmailField in context- The context for html template is as follows- user_dict = { "full_name": user.full_name, "email": str(user.email), "phone_number": str(user.phone_number), "emergency_number": "very very long header", "id_proof_number": user.id_proof_number } When I am using the plain string in place of django field it is rendered correctly as below- Context used is as follows- user_dict = { "full_name": user.full_name, "email": "joe@gmail.com", "phone_number": "+14151234567", "emergency_number": "very very long header", "id_proof_number": user.id_proof_number } Django Model- class User(models.Model): trip = models.ForeignKey( Trip, on_delete=models.CASCADE, related_name="users") id_proof_number = models.CharField( _("Id Proof"), max_length=100, null=True, blank=True) full_name = models.CharField(_("Full name"), max_length=255) email = models.EmailField(_("email"), max_length=70) phone_number = PhoneNumberField(_("Phone Number")) emergency_number = PhoneNumberField(_("Emergency Number"), default=None, null=True) HTML Template- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User Details</title> <style type="text/css"> @page { size: A4; margin: 1cm; } .card-header{ text-align: center; } .table{ border: 0.5px solid #ababab; text-align: center; width: 100%; max-width: 100%; margin-bottom: 5px; table-layout:fixed; } .table tr th td{ white-space: nowrap; } .table th { padding: 5px; vertical-align: top; background-color: … -
alter option automatically in search bar according to another option
I want that when we change the value of the state the value of the city also changes according to the values in this state search.html <div class="form-row"> <div class="col-md-6 mb-3"> <label class="sr-only">State</label> <select name="city" class="form-control"> <option selected="true" disabled="disabled">State</option> {% for key,value in state_choices.items %} <option name="state" value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-md-6 mb-3"> <label class="sr-only">City</label> <select name="city" class="form-control"> <option selected="true" disabled="disabled">Cité</option> {% if state.value == "Nabeul" %} {% for key,value in Nabeul_Choices.items %} <option name="city" value="{{ key }}">{{ value }}</option> {% endfor %} {% endif %} </select> </div> </div> choices.py state_choices = { 'Tunis':'Tunis', 'Nabeul':'Nabeul', } tunis_choices = { 'Tunis':'Tunis', 'Le Bardo':'Le Bardo', 'Le Kram':'Le Kram', } Nabeul_Choices = { 'Nabeul':'Nabeul', 'Hammamet':'Hammamet', 'Dar Chaabane':'Dar Chaabane', } view.py def search(request): queryset_list = Listing.objects.order_by('-list_date').filter(is_published=True, type='Vendre') if 'state' in request.GET: state = request.GET['state'] if state: queryset_list = queryset_list.filter(state__iexact=state) if 'city' in request.GET: city = request.GET['city'] if city: queryset_list = queryset_list.filter(city__iexact=city) context = { 'Nabeul_Choices' : Nabeul_Choices, 'tunis_choices' : tunis_choices, 'state_choices' : state_choices, } return render (request, 'listings/search.html', context) the code works but when I change state the cities do not change automatically -
How to send email to official account from logged in user in django?
I am trying to send email from the user who is logged in to an account which I have given bilalkhangood4@gmail.com. But I have typed it manually. There could be more accounts means more users from which I want to send. But how could I send email from just those users who are logged in? Basically it is an APP where a user will click on withdraw button to request and send mail to official admin account. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False views.py from django.contrib.auth.models import User def ViewSendEmail(request): send_mail('Hello from Bilal Khan', 'Hello there, This is an automated message.', 'bilalkhangood6@gmail.com', #FROM ['bilalkhangood4@gmail.com'], #TO fail_silently=False) return render(request, 'nextone/email_send.html') -
How to make Self hosted Blogging platform like medium?
i want to make blogging platform like medium, with my own custom features this features include. . 1.user can have self hosted blog inside my website 2.i want to make easy to understand tools for cms, like image gallery,code snippet,video player(it must very robust and seamless,not complex at all) 3.to reader i want to make highlight feature,and comment section,bookmark,reading reminder 4.i want to track reader behavior, like how much they spent in reading, track how much people read your blog 5.have a follow system 6.publisher can get revenue from my own ads service,(like youtube ads system,they make ads work seamlessly with their content) 7.make advance search with machine learning . should i use php for my own cms ? -
What is the difference between using brackets "[]" and parentheses "()" for "fields" in django-rest-framework
I have seen fields in the django-rest-framework initialized/declared with parentheses () and brackets [] and I am wondering if there is a difference. I have only been using () but I see [] in the documentation everywhere. Say we have a model Dog. class Dog(models.Model): favorite_food = models.CharField(max_length=255) Now would it be correct to say that these two serializers below for this Dog model are the same? Even though the field is declared with different ASCII characters. class DogSerializer(serializers.ModelSerializer): class Meta: model = Dog fields = ('id', 'favorite_food') class DogSerializer(serializers.ModelSerializer): class Meta: model = Dog fields = ['id', 'favorite_food'] -
How do you create a deferred field if your field is a SerializerMethodField?
I want to create a deferred method field in a model serializer using drf-flexfields. I am using Django Rest Framework and drf-flexfields. I want to create a method field in my model serializer to make a complex query. Because retrieving this field will incur extra database lookups, I want this to be a deferred field, i.e. it will only be retrieved if the client specifically asks for it. The DRF-Flexfields documentation seems to infer that a field can be deferred by only listing it in "expanded_fields" and not in the normal "fields" list, but gives no further explanation or example. https://github.com/rsinger86/drf-flex-fields#deferred-fields I have tried creating a simple SerializerMethodField to test this: class Phase(models.Model): name = models.CharField(max_length=100) assigned = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="phases_assigned") class PhaseSerializer(FlexFieldsModelSerializer): assignable_users = serializers.SerializerMethodField("get_assignable_users") expandable_fields = { 'assignable_users': (UserSerializer, {'source': 'assignable_users', 'many': True}), } class Meta: model = Phase fields = ['name', 'assigned'] def get_assignable_users(self, phase): return User.objects.all() I get the following error : "The field 'assignable_users' was declared on serializer PhaseSerializer, but has not been included in the 'fields' option." What is the correct way to go about accomplishing this? -
ValueError: invalid literal for int() with base 10: 'glassdoor' while creating a user object from custom user model
I have a custom user model called User. I tried to populate some data. I successfully created a superuser. However, when I try to create a normal user, this Error appears:" ValueError: invalid literal for int() with base 10: 'glassdoor'" where glassdoor is the password. Anyone know how to fix this? In my custom user model, I only made email as my login requirements and omit username, also added some other attributes. I did not override default django password settings. models.py class User(AbstractUser): #use email as authentication username = None email = models.EmailField(_('email address'), unique=True) objects = CustomUserManager() # id = models.AutoField(primary_key=True) USER_TYPE_CHOICES = ( (1, 'doctor'), (2, 'labPeople'), (3, 'receptionist'), (4, 'patient'), (5, 'admin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,null=True) sex = models.BooleanField(blank=True, null=True) tel_no = models.CharField(max_length=255, blank=True, null=True) dob = models.DateField(db_column='DOB', blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_type',] def __str__(self): return self.email managers.py for managing my custom user model from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.db import models import django class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ use_in_migrations = True def _create_user(self, email, user_type, password, **extra_fields): """ … -
How to change hidden-input value then send it using django forms?
Good evening, I have a problem with ajax in django forms, it refuses to change value of a hidden input send the views.py class. The page configuration.html contains a form that selects number of parameters. In addition, i need to create a new variable using the previous ones called list_items that changes its value according to the selected parameters, to send it i used a hidden input tag <input id="combo" name="combinaison" class="btn btn-success col-lg-12" type="hidden" value="test"> The variables are send to views.py but the problem is that the value of the hidden input doesn't changed, it always shows the default value. I tried using document.getElementsByName("combinaison").value = list_items; in the form but the value never changes. Here is configuration.html {% extends "base.html" %} {% load staticfiles %} {% block body_block %} <!-- Bootstrap core JavaScript--> <script src="{% static 'staticfiles/vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'staticfiles/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Core plugin JavaScript--> <script src="staticfiles/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="staticfiles/js/sb-admin-2.min.js"></script> <script src="staticfiles/vendor/app/app_config.js"></script> <!-- Begin Page Content --> <div class="container-fluid"> <!-- Grow In Utility --> <div class="col-lg-7"> <div class="card position-relative"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Parametres</h6> </div> <div class="card-body"> <form action="/try" method="GET"> <script> var i = 0; var list_items = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; </script> … -
How do I dynamically set timezones in Django?
So I have been creating a simple site where I need to display the timezones of the time a post was created. So far I have set it to Victoria, Australian time, because it is my timezone, but I want people from other countries to have their own timezones on the posts. I know it sounds silly, but I tried to add multiple timezones to the TIME_ZONE variable in settings.py, but I learnt that does nothing but cast errors. LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Australia/Victoria' So when I put multiple timezones in, I expected it to dynamically show the time based on where you are, but it didn't, I just got a syntax error. -
Why is command prompt returning a gdal not found error
I am trying to add geodjango to an already existing django project. I have installed everything that is request e.g postgressql proj geos e.t.c. I can't seem to install gdal on my system though. Everytime I try to run the project in local host it throws back a gdal not found error. I have tried using Osgeo4w, the .whl and the .msi file to try and install gdal. Can't seem to figure out what I'm doing wrong here. -
vscode debug suite all of a sudden can not find Django module
I've had my vscode integrated with my Django project perfectly fine for about a month now. I went home for the weekend and all of a sudden this morning my vscode debug suite is not working. I could almost swear that I have not touched anything since last time it was working, but I suppose it's possible I may have done something. NOTE: The following command fails when I have vscode run it, but when I open python manage.py shell, I can do from django.core.management import execute_from_command_line perfectly fine. I'm trying to run the test suite on all my tests, but after running the command (I put on separate lines for readability) /Users/hgducharme/Programming/webapp ; env DJANGO_SETTINGS_MODULE=webapp.settings.development PYTHONIOENCODING=UTF-8 PYTHONUNBUFFERED=1 /usr/local/bin/python3-32 /Users/hgducharme/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/ptvsd_launcher.py --default --client --host localhost --port 52944 /Users/hgducharme/Programming/webapp/manage.py test apps/tests/ I get the error: Traceback (most recent call last): File "/Users/hgducharme/Programming/webapp/manage.py", line 10, in main from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/hgducharme/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/ptvsd_launcher.py", line 43, in <module> main(ptvsdArgs) File "/Users/hgducharme/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/lib/python/ptvsd/__main__.py", line 432, in main run() File "/Users/hgducharme/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/lib/python/ptvsd/__main__.py", line 316, in run_file runpy.run_path(target, run_name='__main__') File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/runpy.py", line 240, in run_path pkg_name=pkg_name, script_name=fname) File … -
Missing admin page when Mezzanine site deployed to Heroku
The admin page does not appear for whatever reason when i navigate to the associated URL. Instead I get a page not found page. With the default message "error: an error occured" The weird thing is that the page shows up when i run heroku local or when I run the app locally without heroku. I suspect this is an issue with mezzanine URLS. But im not sure how they work :| . My database setting in settings.py DATABASES = {'default': dj_database_url.parse('postgres://blahblahtheurl')} I also made some changes to the static settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Full filesystem path to the project. PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__)) PROJECT_APP = os.path.basename(PROJECT_APP_PATH) PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH) # Every cache key will get prefixed with this value - here we set it to # the name of the directory the project is in to try and use something # project specific. CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_APP # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = "/static/" # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" # STATIC_ROOT = os.path.join(PROJECT_ROOT, … -
Timestamp "2019-08-15T18:00:21.042255-07:00" is postfixed with -07:00 when i run this piece of code
Timestamp=datetime.utcfromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S.%f") when I run the above piece of code I see the time zone(-07:00)but I don't want the timezone to be displayed, so what I can I do to not display the timezone. -
Add custom field to ModelSerializer and fill it in post save signal
In my API I have a route to add a resource named Video. I have a post_save signal to this Model where I proccess this video and I generate a string. I want a custom field in my serializer to be able to fill it with this text that was generated. So, in my response I can have this value. class VideoSerializer(serializers.ModelSerializer): class Meta: model = Video fields = ('id', 'owner', 'description', 'file') @receiver(post_save, sender=Video) def encode_video(sender, instance=None, created=False, **kwargs): string_generated = do_stuff() Right now what I am getting in my response is: { "id": 17, "owner": "b424bc3c-5792-470f-bac4-bab92e906b92", "description": "", "file": "https://z.s3.amazonaws.com/videos/sample.mkv" } I expect a new key "string" with the value generated by the signal. -
How to solve NOT NULL constraint failed: transactions_withdrawal.user_id
I'm fairly new to django and i've been trying to solve this problem for over 4 days, i've surfed the web and read a lot of documentation. i know this might be a trivial problem but i need help. This is my code accounts\models.py class User(AbstractUser): username = None # first_name = None # last_name = None account_no = models.PositiveIntegerField( unique=True, validators=[ MinValueValidator(1000000000), MaxValueValidator(9999999999) ] ) first_name = models.CharField( max_length=256, blank=False, validators=[ RegexValidator( regex=NAME_REGEX, message='Name must be Alphabetic', code='invalid_first_name' ) ] ) last_name = models.CharField( max_length=256, blank=False, validators=[ RegexValidator( regex=NAME_REGEX, message='Name must be Alphabetic', code='invalid_last_name' ) ] ) gender = models.CharField(max_length=6, choices=GENDER_CHOICE) birth_date = models.DateField(null=True, blank=True) balance = models.DecimalField( default=0, max_digits=12, decimal_places=2 ) objects = UserManager() # USERNAME_FIELD = 'email' # use email to log in USERNAME_FIELD = 'account_no' # use email to log in REQUIRED_FIELDS = ['email'] # required when user is created def __str__(self): return str(self.account_no) transactions\forms.py class WithdrawalForm(forms.ModelForm): class Meta: model = Withdrawal fields = ["amount",] transactions\models.py class Withdrawal(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) amount = models.DecimalField( decimal_places=2, max_digits=12, validators=[ MinValueValidator(Decimal('10.00')) ] ) def __str__(self): return str(self.user) transactions\views.py class FormWizard(SessionWizardView): template_name = "transactions/form.html" def dispatch(self, request, *args, **kwargs): return super(FormWizard,self).dispatch(request, *args, **kwargs) def get_form_instance(self,step): return self.instance_dict.get(step, None) def … -
Date not rendering in Django template
I am attempting to pass date values from views.py (passed in from managers.py), but they are not rendering in my template. I made sure that the date value is correct by printing it to the console and adding it to my template. It renders fine without any filters, but when I used the exact same syntax from earlier in my project—where it worked—all I get are blank values. managers.py tz = pytz.timezone('America/Chicago') class ProfileManager(Manager): def index(self, request): … return { … 'date': datetime.now(tz), } views.py def index(request): response = Profile.objects.index(request) return render(request, 'users/index.html', response) index.html <div id="datePickerDate"> {{ date }} <input type="hidden" name="year" value="{{ date|date:'Y' }}" autocomplete="off"> <input type="hidden" name="month" value="{{ date|date:'n' }}" autocomplete="off"> </div> Result <div id="datePickerDate"> Aug. 19, 2019, 4:27 p.m. <input name="year" value="" autocomplete="off" type="hidden"> <input name="month" value="" autocomplete="off" type="hidden"> </div> I can't think of what I'm missing. Any help is appreciated. -
Static files not being utilized by Django on docker with nginx
Background I am working on a docker-compose app made of 4 services: a django app, a wagtail django app, nginx, and postgresql. My main issue is with static files: they work fine with the development server, but not with nginx. The really strange part is that nginx shows that it is serving the static files, and they are accessible through their URL on a browser. How can I get them to show up? From settings.py in wagtail app STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), '' ] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' From settings.py in django app STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') docker-compose.yml version: '3.7' services: nginx: image: nginx:latest container_name: production_nginx volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./nginx/error.log:/etc/nginx/error_log.log #- /etc/letsencrypt/:/etc/letsencrypt/ - cms_static_volume:/usr/src/cms/static - core_static_volume:/usr/src/core/static ports: - 80:80 - 443:443 depends_on: - core - cms core: build: context: ./cirrus_core dockerfile: Dockerfile.prod command: gunicorn cirrus_core.wsgi:application --bind 0.0.0.0:8000 volumes: - core_static_volume:/usr/src/core/static expose: - "8000" env_file: .env depends_on: - db cms: build: context: ./cirrus_cms dockerfile: Dockerfile.prod command: gunicorn cirrus_cms.wsgi:application --bind 0.0.0.0:8001 volumes: - cms_static_volume:/usr/src/cms/static expose: - '8001' env_file: .env depends_on: - db db: image: postgres:11.5-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: .env.db volumes: postgres_data: core_static_volume: cms_static_volume: nginx.conf … -
Can i render VueJS with Django?
I would like to add Vue to my Django project, but i'm having troubles understanding some parts of it. At the actual moment, my project already has a bunch of templates and views. Everything is rendered by the views, the only JS i'm using is for Jquery. The need to add Vue comes to improve my UI. I don't need Vue to be my frontend, i only want to add some Vue components to my templates here and there. After making some research, i found about the Webpack + Vue approach. It's not the right approach for my project since it should be used for a project where the frontend is entirely built on Vue and is divided from the Django backend, so it is not the right way for me. At this point, the only way to go would be to add it using the CDN on my django html template: <script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script> Would this approach be possible? -
Django User OnetoOneField Form - Fails Validation
I am using OneToOne Fields to connect a UserProfile form model to the default django user model. Using this to extend the user information to include more than the user model has to offer. Currently the post request is failing the is.valid() command and will not allow me to process the data and commit to the DB. Have looked all over for the solution with no luck, scratching my head. Here is my current models.py: from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User # User Profile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_bio = models.CharField(max_length=1000) user_photo = models.CharField(max_length=1000) user_level = models.CharField(default="Novice", max_length=256) Here is my current models.py: from django.contrib.auth.models import User from django import forms from .models import UserProfile # Django Default User Class class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] # User Profile Class class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['user_bio', 'user_photo'] Here is the UserFromView created to serve the form and then commit once posted: views.py Imported modules... class UserFromView(View): user_form_class = UserForm user_profile_form_class = UserProfileForm template_name = 'home/registration_form.html' # Display blank form def get(self, request): user_form = self.user_form_class(None) user_profile_form = self.user_profile_form_class(None) … -
How to Pass Parameters to View When Form Is Valid
I have a view which renders a form where all lines of 'manifest' information are displayed after a user selects an order # from a dropdown and submits. This form should allow for the user to enter a new line, and after doing so (and refreshing) the view should display the form again but with that updated line. My problem is that my view consumes a parameter 'Reference_Nos' from the dropdown that initially displays the view and form. After a user enters a new value, that dropdown isn't used again so the view doesn't display the correct info. In place of that, I am trying to use one of the fields from the form 'reference' which is the same as that dropdown value. I am getting an integrity error "Orders matching query does not exist" I don't understand why that query does not exist because the same query is used when request method isn't "post" and it works then. Any help? forms.py class CreateManifestForm(forms.ModelForm): cases = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter Cases'})) class Meta: model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') widgets={ 'product_name': forms.Select(attrs={'style': 'width:170px'}) } views.py def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() …