Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Click on username and get redirected to the profile
I'm writing an application and I want to be able to click on the username and go to the profile of the user. I have searched a lot around and didn't find anything that I wanted. I have something like this: I want that when I press on Admin, I will be redirected to the profile with all the information that is saved through the Model that I created. class Farmer(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=50) age = models.IntegerField() province = models.CharField(max_length=100) company_name = models.CharField(max_length=30) phone_number = PhoneNumberField(null=False, blank=False, unique=True) products = models.CharField(max_length=200) def __str__(self): return self.name.username How can I achieve something like this? I thought that I need to write a function inside my views.py but I'm stuck and don't know how to go further. def profile(request): # something here.. return render(request, 'home_page/profile.html') -
Automate Elasticsearch index creation on django app startup
I want to automatically check and create (if not existing) the elasticsearch index of my app on startup, this is my current situation which is not working: echo "Checking if Elasticsearch index is setup" { cat <<EOF | python /manage.py shell from elasticsearch import Elasticsearch HOST_URLS = ["elasticsearch:9200"] es_conn = Elasticsearch(HOST_URLS) INDEX_NAME = "posts" res = es_conn.indices.exists(index=INDEX_NAME) if res == True: print("Elasicsearch index seems already setup, skipping") else: print("Elasicsearch index not setup yet, creating ...") import subprocess subprocess.Popen("y | python manage.py search_index --rebuild", shell=True, stdout=subprocess.PIPE).communicate()[ 0].decode('utf-8').strip() EOF }>/dev/null which again results in: "the '{}' indexes? [n/Y]: ".format(", ".join(index_names))) | EOFError: EOF when reading a line python manage.py search_index --rebuild comes from: https://github.com/sabricot/django-elasticsearch-dsl/ -
Django migrate value invalid literal
I have problem with Django migrate function. I was trying to add new field to my user model and it looks like this. class UserProfile(models.Model): """ Model to represent additional information about user """ user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile' ) bio = models.TextField( max_length=2000, blank=True, default='' ) # we use URL instead of imagefield because we'll use 3rd party img hosting later on avatar = models.URLField(default='', blank=True) status = models.CharField(max_length=16, default='', blank=True) name = models.CharField(max_length=32, default='') balance = models.BigIntegerField(default='0') def __str__(self): return self.user.username balance is new what I added, and after that I'm receving messages like Operations to perform: Apply all migrations: accounts, admin, auth, authtoken, contenttypes, forums, posts, sessions, threads Running migrations: Applying accounts.0005_userprofile_balance...Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) … -
problem writing/understanding Django Custom managers
I have problems with Django's custom managers. It may be simple but I did not understand the managers very well. here is my code : class Season(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING) created = models.DateTimeField(auto_now_add=True) objects = models.Manager() # Default Manager custom_obj = SeasonManager() # Custom Manager in (managers.py) def __str__(self): return self.title class Lesson(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) content = models.TextField() season = models.ForeignKey(Season, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Video(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) content = models.TextField() view = models.PositiveIntegerField(default=0) lesson = models.ForeignKey(Lesson, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) video_file = models.FileField(upload_to='tutorialApp/videos') video_length = models.CharField(max_length=32) def __str__(self): return self.title The structure is like this: every season has some lessons, each lesson has some videos and each video has a length. I want to write a manager that shows the sum of video lengths in a season. ( a manager that shows how many minutes of videos there are in a season … -
Is there documentation for class option for Django fieldset?
In the Django admin docs, it mentions fieldsets. The example they specify a class collapse. This class will make the fieldset collapsible in the admin page. I found 2 other examples of a classes one could use. I found looking for a list of other classes I can use is wide or extrapretty. Other than these examples I have not been able to find anything else about the class option in the fieldset. -
How to get the price, duration of the twilio call?
I am trying to implement my programmable voice using TwiML, and I am unable to get the JSON API response, as shown in the tutorial. # views.py def start_campaign(request, campaign_id): try: campaign = Campaign.objects.get(pk=campaign_id) account_sid = 'XXXX' auth_token = 'XXXX' client = Client(account_sid, auth_token) phone_numbers = Contact.objects.filter(phone_book=campaign.phone_book) custom_url = 'http://XXXX.ngrok.io/assets/' + str(campaign_id) for phone_number in phone_numbers: call = client.calls.create( method='GET', url=str(custom_url), to=str(phone_number), from_='+12563804721' ) # I don't want to print it I just wanted to see if this works print("Call Status: {}\nCall Duration:{}\nCall Cost:{}".format(call.status, call.duration, call.price)) except Campaign.DoesNotExist: raise Http404("Campaign Does Not Exist") context = { 'campaign': campaign } return render(request, "CallCenter/start_campaign.html", context) def view_assets(request, campaign_id): try: campaign = Campaign.objects.get(pk=campaign_id) except Campaign.DoesNotExist: raise Http404("Campaign Does Not Exist") context = { 'campaign_text': campaign.campaign_text } return render(request, "CallCenter/create_xml.xml", context, content_type='application/xml') # urls.py urlpatterns = [ path('', index, name="index"), path('view-campaigns', view_campaigns, name='view-campaigns'), path('detail-campaign/<int:campaign_id>', detail_view_campaign, name='detail-campaign-view'), path('start-campaign/<int:campaign_id>', start_campaign, name='start-campaign'), path('assets/<int:campaign_id>', view_assets) ] I want a JSON response, as shown in the docs, but I am unable to figure out how to approach it. The output comes as Call Status: queued Call Duration: None Call Cost: None The output shown above comes right after the call is initiated and after I disconnect the call I … -
Django using default db for unit tests instead of test db
When I run manage.py test django is using my default database instead of a test one. Am I misunderstanding something from the docs? According to the docs, the default behaviour is that, "separate, blank databases are created for the tests". I set the "TEST: NAME" value just to make sure, but the docs state that's only needed if I want to configure the test database name instead of the default test_{dbname} DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "HOST": "0.0.0.0", "NAME": "mydb_db", "USER": "postgres", "PASSWORD": "postgres", "PORT": 5432, "TEST": {"NAME": "test_mydb_db"}, } } class SimpleTest(unittest.TestCase): def test_get_user_authorized(self): client = Client() breakpoint() >>> (Pdb) from django.db import connection >>> (Pdb) connection.settings_dict['NAME'] 'mydb_db' If I read or create data in the unit test, data is from mydb_db and not test_mydb_db as I expected. Additional Notes Database is being setup using docker compose. Not sure if that affects anything: services: db: container_name: postgres image: postgres:9.6 restart: always volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" environment: POSTGRES_DB: mydb_db POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres PGPASSWORD: postgres -
how to filter two foreign keys in django
int() argument must be a string, a bytes-like object or a number, not 'ForwardManyToOneDescriptor' class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,blank=True,null=True) Remarks = models.TextField(max_length=500,null=True,blank=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) def __str__(self): suser = '{0.Employee_Users}' return suser.format(self) can you guys help me on how to filter the StudentsEnrollmentRecord(Education_Levels) to SubjectSectionTeacher(Education_Levels) because it is really hard to understand the django-filter, i waste already 2 days for this error. -
Prepop fields with values when another field is checked in Django
In my Django database I have the following: skipUserPII = models.BooleanField(default=False) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) address1 = models.CharField(max_length=100) Sometimes, I will create a user manually. In that case, I won't want to fill in their PII every time. So I have created a new variable "skipUserPII" that if checked fills in all PII values with "na" (as compared to having to manually fill in all my PII fields with some default value, allowing me to save the form in Django admin). I'm trying to accomplish this by using the following code below, however it is giving me a "Please correct the errors below" error. def clean(self): if self.skipUserPII == True: def checkNone(field, value): if field == None: field = value checkNone(self.first_name, 'NA') checkNone(self.last_name, 'NA') checkNone(self.address1, 'NA') I've tried putting this in clean and in save -- neither work. Is there another place this code should go? -
heroku works locally but not in server shows "ERROR: connecting to localhost:5037"
In my project Iam referring to "pure python ADB client" which is working fine locally. But after deployment when I try to run the application using "Heroku open" it shows ERROR: Connecting to localhost:5037 [Errno 111] Connection refused. Is adb running on your computer? I tried with 127.0.0.1 but still, it shows error. def getConnected_devices(request): """Connect the devices via usb or WIFI through adb and get the device details dynamically and update the status of device""" client = AdbClient(host="localhost", port=5037) devices = client.devices() usb connected device should be recognized properly in the heroku cloud. -
Django - Getting specific data from model
I'm trying to make a booking system (for apartments). The idea is that users can pick a start date and an end date and book the apartment if it isnt alrdy booked. I have a Reservation model with a "start_date" and a "end_date" that I use to determine the dates for the apartment booking. Users the JQuery Ui Date Picker (a small calendar) to pick dates. The "unavailable" dates are grayed out. This is how I did that : <script type="text/javascript"> var unavailableDates = ['{{ reservation.all.0.start_date|date:"d-m-Y" }}', '{{ reservation.all.0.end_date|date:"d-m-Y" }}']; console.log(unavailableDates); function unavailable(date) { dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear(); if ($.inArray(dmy, unavailableDates) == -1) { return [true, ""]; } else { return [false, "", "Unavailable"]; } } $(function () { $("#datepicker").datepicker({ dateFormat: 'MM-dd-yy', beforeShowDay: unavailable }); }); </script> I am using ... {{ reservation.all.0.start_date|date:"d-m-Y" }} ...to gray out the date in the calendar. My reservation model looks like this: class Reservation(models.Model): apartment = models.ForeignKey(Apartment, related_name='reservations', on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateField(blank=True, null=True, unique=True) end_date = models.DateField(blank=True, null=True, unique=True) name = models.CharField(default="", max_length=200, unique=True) def __str__(self): return self.name And in my view I have: reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) Since I … -
How to create and update model with multiple "ManyToMany" and "through" relations?
Im creating a Rest API for my mobile app in django-rest-framework. My app is similar to MyFitnessPal, so my users have their own food history, where are their meals and each meal have list of food products. For now when I register user I'm creating a new, empty FoodHistory for him. So as next I want to add option to add/update those meals. When user wants to add food products to "Breakfast" with date 10-10.2019 I want to check if meal "Breakfast" with that date already exist in user's history. If not, create it (and set "meal_date" parameter to date from request), if yes, take Food product form DB using it's ID (it's already created) and add it to user's history with "food_weight" parameter. I dont know how to do it when I have multiple ManyToMany and through relations. I know that I have to override "create" and "update" methods in serializers.py and "post" method in my "api.py" but now Im even not sure which serializer should be in my APIView (api.py) class as "serializer_class". models.py class Food(models.Model): name = models.CharField(max_length=255) brand = models.CharField(max_length=255, default="") energy_value = models.DecimalField(max_digits=6, decimal_places=3) fats = models.DecimalField(max_digits=6, decimal_places=3) saturated_fats = models.DecimalField( max_digits=6, decimal_places=3, default=0) carbohydrates … -
AttributeError: module 'django.db.models' has no attribute 'TextFeild'
I was using it with 2.0.7 django , then i tried with 2.2.6 also, this seems to persist. from django.db import models # Create your models here. class Product(models.Model): title=models.TextFeild() description=models.TextFeild() price=models.TextFeild() -
Django-allauth - form with additional registration fields
I'm using django-allauth to authenticate the user. The configuration of my project looks something like this: INSTALLED_APPS = [ [...] 'authentication', 'django.contrib.sites', # 3rd party 'allauth', 'allauth.account', 'allauth.socialaccount', ] #<======================================================DJANGO ALLAUTH=================================================> AUTH_USER_MODEL = 'authentication.CustomUser' # emaillogin_project/settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", ) SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True # ocpjonalnie emaillogin_project/settings.py LOGIN_REDIRECT_URL = 'seller:home' #redirect ACCOUNT_LOGOUT_REDIRECT_URL = 'seller:home' #rediect #login form ACCOUNT_FORMS = {'signup': 'authentication.forms.SimpleSignupForm'} My custom user model: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): age = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return self.email template.html (I use standard fields for crispy field as in the example) [...] {{ form.email|as_crispy_field }} [...] And my forms.py file for which I have questions (I don't understand how it works). 1.) The form in this configuration creates the user and writes the first name (in object), saving the age does not work. Why? class SimpleSignupForm(SignupForm): age = forms.CharField(max_length=30, label='First Name') first_name = forms.CharField(max_length=30, label='First Name') def __init__(self, *args, **kwargs): super(SimpleSignupForm, … -
build login using Django and Angular error credential not provided
i'm try to build a basic login app using Django backend and Angular like fronted, when i use the login component and write the correct credential username and password in the form, then redirect to another component sendme this error, Important: the login giveme the token but then after the login and redirect to another component ,error error Authentication credentials login form with correct credentials username passowrd settings .py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser', ), 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ], 'NON_FIELD_ERRORS_KEY': 'global', } url .py path('auth/login/', obtain_jwt_token), path('auth/refresh-token/', refresh_jwt_token), login component.ts and .html constructor( private authService: AuthService, private router: Router, ) { } login(username: string, password: string) { this.authService.login(username, password).subscribe( success => this.router.navigate(['categorias']), error => alert('Error al Conectar Datos ') ); } <input class="form-control form-control-sm" #username type='text' placeholder='username'> <input class="form-control form-control-sm" #password type='password' placeholder='password'> <button class="btn btn-primary" (click)="login(username.value, password.value)">login</button> -
How to fix SystemCheck Error in Django 2.2.5
I'm setting a simple Python web app. The example comes from https://www.codementor.io/rogargon/simple-django-web-application-tutorial-du107rmn4. Why is the code breaking? I tried adding the following code: from django.contrib.contenttypes.fields import GenericForeignKey && from django.contrib.contenttypes.models import ContentType class Review(models.Model): RATING_CHOICES = ((1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')) rating = models.PositiveSmallIntegerField('Rating (stars)', blank=False, default=3, choices=RATING_CHOICES) comment = models.TextField(blank=True, null=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) date = models.DateField(default=date.today) class Meta: abstract = True class ShopReview(Review): restaurant = models.ForeignKey(ShopInfo, on_delete=models.CASCADE) class Article(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) title = models.CharField(max_length=55) # ... def __str__(self): return self.title -
Django Simplified EAV Implementation, similar to Google Form
I am trying to implement a project, similar to Google forms. We have multiple ActivityType (analogous to a Google form). For example, home verification is an ActivityType. Each ActivityType can have multiple question. Like "What is the home address?", "How many neighbours?". Each question can have a different type, like TextField, ChoiceField etc. Each ActivityType can have multiple submissions. Each submission can have answers to some or all questions in the activity. How do I implement it most logically and succinctly? My Approach (and Questions) Using Django admin, several ActivityType can be defined. Each ActivityType contains several questions using StackedInline. Questions are stored as a json array in the ActivityType model itself. How do I show model's JSON array into a StackedInline? The Response model contains submissions. It just contains a ForeignKey to ActivityType. Response form should be rendered, conforming to the structure defined by question JSON array. How to use a custom form for this? My code models.py class ActivityType(models.Model): activity_name = models.CharField(max_length=200) questions_json = JSONField() class ActivityAnswers(models.Model): activity_event = models.ForeignKey("ActivityEvent", on_delete=models.SET_NULL) user = models.ForeignKey(User, on_delete=models.SET_NULL) answers = JSONField() forms.py class ActivityTypeQuestionForm(forms.ModelForm): Q_TYPES = ( ('multiple_choice', 'Multiple Choice'), ('text_field', 'Text Field'), ('integer_field', 'Integer Field'), ) question_name = forms.CharField(max_length=200) question_type … -
Django / Bootstrap Error: Parameter "form" should contain a valid Django Form
I have a Django app called 'Accounts' that extends the Django default User model. I want each user to be able to update their account, which is a model called UserProfile using the generic.UpdateView. I get the following error when I go to the UpdateView URL: BootstrapError at /accounts/user-profile/5/edit/ Parameter "form" should contain a valid Django Form. I've included my code below. Thank you! models.py from django.db import models from django.contrib import auth # Create your models here. class User(auth.models.User,auth.models.PermissionsMixin): readonly_fields = ('id','pk') def __str__(self): return self.username class UserProfile(models.Model): user = models.OneToOneField(auth.models.User,on_delete=models.CASCADE) join_date = models.DateTimeField(auto_now=True) profile_pic = models.ImageField(upload_to='profile_pics',default='media/block-m.png') skills = models.TextField() major = models.CharField(max_length=128) grad_year = models.CharField(max_length=4) clubs = models.TextField() #make FK to Clubs opt_in = models.BooleanField(default=True) def __str__(self): return self.user.username forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile from django import forms class UserCreateForm(UserCreationForm): class Meta: model = get_user_model() fields = ('first_name','last_name','username','email','password1','password2') def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) # self.fields['username'].label = 'Username' # self.fields['email'].label = 'Email Address' # self.fields['password1'].label = 'Password' # self.fields['password2'].label = 'Confirm Password' class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('profile_pic','grad_year','opt_in') views.py from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.mixins import( LoginRequiredMixin, PermissionRequiredMixin ) from django.urls … -
Django CharField TypeError: __init__() got an unexpected keyword argument 'empty_value'
The Django suggest that I can set the empty_value for a CharField: https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.CharField.empty_value I'm trying to change my field from: my_field = models.CharField(max_length=80, blank=True) to: my_field = models.CharField(max_length=80, blank=True, null=True, empty_value=None) I'm getting this error when I try to create the migration: File "/Virtualenv/python3.7/site-packages/django/db/models/fields/init.py", line 1039, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'empty_value' The reason is because I want to set a unique_together on the model that includes my_field and other fields, with the following behavior: If my_field is NULL, I want the unique_together clause to always allow other combinations because NULL != NULL in SQL. If my_field is not NULL, I want the unique_together clause to check for uniqueness against the other field(s). I do not want validation that is not database validation like a clean or validate_my_field method or similar. -
How to deploy django project on Centos 7?
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7 I followed the tutorial above to deploy my django project on my CentOs 7 VPS. But at the end when I enter my web site I encounter default Apache welcom page. Is there something missing in this tutorial ? -
Where is gunicorn config file likely to be located in a redhat server?
And no this is not a duplicate of Where is the Gunicorn config file?. While the title is, none of the answers answer the question of where this file is located in the file system or how to find it. I'm having difficulty getting a fully working and functional django site deployed. -
How to use dates in Django model?
When using DateField, I keep getting this error after running migrate: django.db.utils.ProgrammingError: cannot cast type date to time without time zone LINE 1: ...TER COLUMN "create_time" TYPE time USING "create_time"::time I tried to use create_time = models.DateField(auto_now_add=True) I've also tried create_time = models.DateField(default=datetime.date.today()) And get the same error. Some answers I've read suggest editing my postgres database. However I did not get this error before - I originally had auto_now=True instead of auto_now_add=True. This error only came up after I changed that. I tried to change it back to auto_now=True, and I still get this error upon running migrate. I also removed the DateField entirely from my model, and when running migrate I STILL get the error. Is it possible I need to reset something, so that I'm migrating the most updated model? Thanks for any tips. -
Trying to understand Model relationships in Django
I am fairly new to Django and am working on a project that will do the following: Employee will fill out form to create a ticket That ticket will be assigned to the employee and other team members The ticket is associated with a specific person or persons within the organization (I'll call them customers) Once the ticket is complete, we will run reports to show how many tickets a specific person with the organization has created tickets as well as other stats related to the tickets themselves My multi-part question is as follows: What is the best way for me structure my Django models in this scenario? Should I have one app created for employees, one app created for the customer database and one app created for the tickets themselves? Which then is the master ID holder? Is it the employee or the customer? Is there a boilerplate template for a system like this already created that I should be utilizing? Thanks for your time! -
Django looking for index.html after deploying to server
I have just deployed new code to server after upgrading all the relevant packages on the server to match what I have on my development server. I know that the models.py file has changed and that the migration files won't match, but I can trash the current database as it's not needed and doesn't need to be archived on this occasion. Server was running previous website fine, so I am hoping that Gunicorn and Nginx configs should hopefully not be part of this issue (I'm mentioning this explicitly in case it is). So now my site which ran fine on my laptop with django's dev server has now been deployed to the server using git pull, which worked fine, the code on the server is now what matches the master branch. I'm running a virtual environment (virtualenv) which has python 3.6 on it, but for an unknown reason there is python 2.7 on there as well which I am not aware of installing on the environment (I have never programmed in python2.7 so never install it, though I know it is part of the OS so expect it there, just not in the virtual env. but now when I click … -
How to redirect a user based on his choice in drop down?
I've made a form that has a gander Dropdown with two options, how can I redirect a user based on his option if he choices (1) and submit the form will redirect him to a URL and if his choices (2) will redirect him to a different URL. i want to solve it in views or form not in template. forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'second_name', 'E_mail', 'country', 'phone', 'phone_code','birthday', 'Gander',) widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'الاسم الاول'}), 'second_name': forms.TextInput(attrs={'placeholder': 'الاسم الثاني'}), 'E_mail': forms.EmailInput(attrs={'placeholder': 'joe@schmoe.com'}), } views.py def form_page(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('LandingPage:thank_you') else: form = UserForm() posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'LandingPage/form_page.html', {'form': form, 'posts': posts,})