Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ignore string after PK in URL
product urls.py urlpatterns = [ path('<int:pk>/', ProductDetailView.as_view(), name='detail'), ] Currently my url looks like this http://127.0.0.1:8001/product/11/ However I want to also append the slug of the product. http://127.0.0.1:8001/product/11/example-slug/ But it shouldn't matter what the string is behind it, it should just use the pk in order to display the page. It should ignore the string after /11/ how can I do that? -
How to run Pygame on website using Django?
Info: I would like to make a website with Django which runs pygame, displays a screen, and plays sounds. I have seen this done on repl.it where you are able to write a python program using pygame and it will all run very smoothly. Question: How does repl.it run python graphics in the browser and how would I replicate it using Django? Or is there another way to run pygame in the browser in a similar way to how repl.it does it? What I have tried: I have done this before by using javascript to call a python program that would return an image array that would be displayed using HTML. The problem with this is that it was relatively complex and not very fast. What I am NOT looking for: I have seen a lot of python to javascript converters like skulpt which will not help me since I need to run many other libraries along with pygame which are not supported in javascript. I am also not looking for a way to do the visuals in javascript and the processing in python. And please do not tell me that I should not use python for visuals on a … -
What is the correct way of storing sensitive third-party tokens and keys in a Django project?
I am building a Django project. Something I realized is that a really useful feature for my users would be able to connect to Google Sheets through my application. While of course oAuth is an option, for my use case, setting service accounts for users would be a much nicer solution. In case you are unfamiliar, service accounts in Google have keys that come in JSON files. With a service account, connecting to the Google APIs becomes a breeze. So in this situation, let's say I want to store the service account keys of my users. Is this feasible in any way in terms of security? How does one go about storing these sensitive user credentials (from third party software and companies) in a Django project? -
Postgresql visualization with django
I have a big model in django which makes a lot of tables in postgresql. How can I visualize it in django? any idea? -
map function won't work after d3 (Uncaught TypeError data.map is not a function) - Javascript [duplicate]
In the example below, if I define myself the var "station" I can normally use the stations.map (method 1). But when I try to read exactly the same data from a csv file using d3 (method 2), stations2.map gives me an error. {% load static %} <!DOCTYPE HTML> <meta charset="utf-8"> <head> </head> <body> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script> --> <script> // METHOD 1 var stations = [ { lat: 52.35500, lng: -8.68400, name: 'Station 1' }, { lat: 52.40242, lng: -8.51132, name: 'Station 2' }, { lat: 52.55827, lng: -8.27802, name: 'Station 3' }, { lat: 52.55139, lng: -8.24667, name: 'Station 4' }, { lat: 52.56262, lng: -8.26170, name: 'Station 5' }, // ... as many other stations as you need ]; var lngs = stations.map(function (station) { return station.lng; }); var lats = stations.map(function (station) { return station.lat; }); console.log(stations); // METHOD 2 var stations2 = d3.csv("{% static 'data/sample_output2.csv' %}", function (d) { return { lat: parseFloat(d.lat), lng: parseFloat(d.long), name: d.supplier }; }, function (error, rows) { console.log(rows); }); console.log(stations2); var lngs2 = stations2.map(function (station) { return station2.lng; }); var lats2 = stations2.map(function (station) { return station2.lat; }); </script> </body> </html> When I console.log stations and stations2 look … -
How to get Django ModelForm to accept a date in a particular format (or convert to an acceptable fomat)?
I have a model with a datefield. I am using this model to create a form using the ModelForm class. The problem is that the user can enter the date in multiple formats (d-m-yy, dd-mm-yy, dd-mm-yyyy) (not thinking about locales for now). After the form is submitted. Django form.is_valid() fails because of the date format. I need to handle different formats but can't figure out how to do that. Here is a minimal Form and Model class: (assume correct imports) class MyForm(forms.ModelForm): class Meta: model = models.MyDateModel fields = ["date"] widgets = { "date": forms.DateInput(), } Model Class class MyDateModel(models.Model): date = models.DateField() -
Wagtail: possible to pass parent page to structblock when creating a new page?
I'm creating a website that needs to be available in multiple languages. For most pages this is not a problem since we just duplicate the page tree. There are however, some components (think ModelAdmin but also some pages that are used in a similar way) that can't be translated this way. I have a few structblocks that reference a model like this, here is one: class StoriesSection(blocks.StructBlock): sub_title = blocks.CharBlock(required=True, help_text='Sub-title displayed at the very top') stories = blocks.ListBlock( blocks.StructBlock( [ ('image', APIImageChooserBlock(required=True)), ('cta_copy', blocks.CharBlock(required=True, default='Read the article')), ('story', blocks.ChoiceBlock(required=True, choices=get_stories, help_text='Linked story')), ] ) ) Now I can pass all of the stories with the method get_stories like I'm doing now: def get_stories(): # use get model to prevent circular import (pages.models <-> streams.blocks) model = apps.get_model('pages', 'StoryPage') return [(story.id, story.title) for story in model.objects.all()] The problem is that a story has a specific language. When creating a new page, I would like to only display stories that match the language of the parent page in the 'story' field. In this case that is: /en/ /stories/ /story-1/ <- would like to only pass story pages that are in here /some-other-page/ <- creating this page /fr/ /stories/ /a-french-story/ ... Is … -
server error while trying to post / put, but not while remove / get in django + vue js
I get this error while trying to add / update value in the database, I Can add / update values in postman, but on the website, I cant update/add new todo! here is my code in the frontend: (im using Vue JS in the frontend) import axios from 'axios'; async function add(todo) { try { return axios.post(`http://127.0.0.1:8000/api/${TODO_API}/`, todo) // return await httpService.post(TODO_API, todo); } catch (err) { throw err; }; }; async function update(todo) { try { return axios.post(`http://127.0.0.1:8000/api/${TODO_API}/`, todo; // return await httpService.post(`${TODO_API}/${todo._id}`, todo); } catch (err) { throw err; }; }; THIS IS THE ERROR I GET IN THE BACK END TERMINAL: Internal Server Error: /api/todo/5 Traceback (most recent call last): File "/Users/nofarpeled/Documents/Projects/Not Done/django-tutorial/backend/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/nofarpeled/Documents/Projects/Not Done/django-tutorial/backend/venv/lib/python3.8/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/Users/nofarpeled/Documents/Projects/Not Done/django-tutorial/backend/venv/lib/python3.8/site-packages/django/middleware/common.py", line 54, in process_request path = self.get_full_path_with_slash(request) File "/Users/nofarpeled/Documents/Projects/Not Done/django-tutorial/backend/venv/lib/python3.8/site-packages/django/middleware/common.py", line 87, in get_full_path_with_slash raise RuntimeError( RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/api/todo/5/ (note the trailing slash), or set APPEND_SLASH=False in your Django … -
DateTimeField along with bootstrap_datepicker_plus problem
I have a problem with saving data from form created with bootstrap_datepicker_plus (https://pypi.org/project/django-bootstrap-datepicker-plus/) I use Django 3.0.7 here is my model class: class NightWindowPlatfrom(models.Model): start_timestamp = models.DateTimeField( null=True, blank=True, verbose_name=_('Start datetime'), help_text=_('Night window start time') ) end_timestamp = models.DateTimeField( null=True, blank=True, verbose_name=_('End datetime'), help_text=_('Night window end time') ) platform = models.ForeignKey( Platform, blank=True, null=True, related_name='platform', verbose_name=_('Platform NightWindow'), help_text=_('Platform NightWindow for'), on_delete=models.CASCADE ) def __str__(self): return self.platform.name class Meta: verbose_name = _('Night Window Not Alarmed to Heimdall') verbose_name_plural = _('Night Windows') and my form class class NightWindowForm(forms.ModelForm): class Meta: model = NightWindowPlatfrom fields = ['start_timestamp', 'end_timestamp'] widgets = { 'start_timestamp': DateTimePickerInput(format='%Y-%m-%d %H:%M:%S'), 'end_timestamp': DateTimePickerInput(format='%Y-%m-%d %H:%M:%S'), } def clean(self): cleaned_data = super(NightWindowForm, self).clean() start_timestamp = cleaned_data.get("start_timestamp") end_timestamp = cleaned_data.get("end_timestamp") if start_timestamp and end_timestamp: if end_timestamp < start_timestamp: msg = u"End datetime cannot be earlier than start datetime!" self.add_error('end_timestamp', msg) return cleaned_data The DateTimePickerInput renders correctly. But when I save, I get following error I looked into Chrome devtools and I figured out that there is a difference in what was passed from forms earlier, when I used django-datetime-widget (https://pypi.org/project/django-datetime-widget/). I stopped using it, since it is incompatible with Django 3. Here are the differences. What was earlier, with django-datetime-widget: What I get … -
Next JS changes session key on browser key each time
We use Next JS for front-end and Django for back-end. Session is automatically handled from server and i myself don't save cookie or session key on browser. The problem is each time i send a request with Axios from Next JS, Session key is changed on my browser cookie. But when we get or post data with Postman, our session is not changed we get correct data. Thanks! -
Generic detail view StoreInfoView must be called with either an object pk or a slug in the URLconf
I am getting this error Generic detail view StoreInfoView must be called with either an object pk or a slug in the URLconf. even though I have provided the id in the url and I am using UpdateView and not DetailView. What can be the reason? view. class StoreInfoView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Store template_name = 'store/store_information.html' form_class = StoreInfoForm success_message = 'Updated' success_url = reverse_lazy('store:store_home') def get(self, *args, **kwargs): self.object = Store.objects.get(id=self.kwargs['id']) form_class = self.get_form_class() form = self.get_form(form_class) context = self.get_context_data(object=self.object, form=form) return self.render_to_response(context) def test_func(self): obj = Store.objects.get(id=self.kwargs['id']) if self.request.user == obj.user: return True return False url. path('ecom/<int:id>/store_info/', StoreInfoView.as_view(), name='store_information') Thanks -
Django upload two same structure record to database with ONE submit button . DJANGO
I have tried all ways to save to database two same structure records suing django. I do not know why, but it is always saving only the last one record. I am creating web for recipes. And now i am trying with one button save all menu of one day, what is for breakfast, for dinner.... And i can't imagine how to make i work. Help [my user interface][1] tripdishes_form.html {% if form.instance.id %} {% endif %} <form class="form" action=" {% if form.instance.id %} {% url 'dishes:update' form.instance.id %} {% endif %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-3"> <input type="hidden" name="date" value="{{ trip_date }}"><br><br> <input type="hidden" name="trip_id" value="{{ trip_pk }}"><br><br> </div> </div> <div class="row"> <div class="col-3"> {{ form1.dish_id|as_crispy_field }} </div> <div class="col-3"> {{ form1.meal_time_type|as_crispy_field }} </div> </div> <div class="row"> <div class="col-3"> {{ form2.dish_id|as_crispy_field }} </div> <div class="col-3"> {{ form2.meal_time_type|as_crispy_field }} </div> </div> </div> <br> <button class="button" type="submit"> {% if form.instance.id %} Update {% else %} Create {% endif %} </button> </form> <div> {% endblock %} forms.py from django import forms from .models import TripDishes class TripDishForm(forms.ModelForm): class Meta: model=TripDishes fields=['trip_id','dish_id','date','meal_time_type',] widgets = { } views.py class TripDishesCreateView(LoginRequiredMixin, CreateView): model = TripDishes fields = ['date', 'meal_time_type', 'trip_id', 'dish_id'] … -
user.save() not working properly when used in overriding serializer class's save() method
what i wanted was to send a post request with body containing email , username , password and password 2. the serializer class has a save method which has been overriden so that it checks password1 is equal to password2 or not . if equal i wanted a user object to be created with email username and a password . and wanted it to be saved . im using User model of django. error: TypeError: Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class tha t is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the RegistrationSerializer.create() method to handle this correctly. Serializer Class: class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['email', 'username', 'password','password2'] extra_kwargs = {'password': {'write_only': True}} # override one of its method to check if passwords match def save(self): user = User() #cant create user py passing into constructor user.email=self.validated_data['email'] user.username=self.validated_data['username'] password=self.validated_data['password'] password2=self.validated_data['password2'] if password!=password2: raise serializers.ValidationError({'password':'password must match'}) user.set_password(password) user.save() return user the view called: @api_view(['POST', ]) def registration_view(request): serializer=RegistrationSerializer(data=request.data) data={} if serializer.is_valid(): user=serializer.save() data['response']="successfully created" data['email']=user.email data['username']=user.username else: data=serializer.errors return … -
Django form data into multiple dictionaries
In my HTML form i have multiple form fields: <div class="row form-group"> <div class="col-md-6"> <label for="label1">Label1</label> <input type="text" value="Card Number", name="card_number" class="form-control" id="label1"> </div> <div class="col-md-6"> <label for="placeholder1">Placeholder</label> <input type="text" value="Enter Card Number" name="card_number_placeholder" class="form-control" id="placeholder1"> </div> </div> <div class="row form-group"> <div class="col-md-4 mb-3"> <label for="label2">Label2</label> <input type="text" value="Expiration" name="expiration" class="form-control" id="label2"> </div> <div class="col-md-3 mb-3"> <label for="placeholder2">Placeholder</label> <input type="text" value="MM/YY" name="expiration_placeholder" class="form-control" id="placeholder2"> </div> </div> In my Django View when i convert the form data into dictionary using data = request.POST.dict() i get all the form field values as one single dictionary: {'expiration_placeholder': ['MM/YY'], 'card_number_placeholder': ['Enter Card Number'], 'expiration': ['Expiration'], 'card_number': ['Card Number']} How can i get these as multiple dictionaries on form submit as something below: {{'expiration': ['Expiration'],'expiration_placeholder': ['MM/YY']}, {'card_number': ['Card Number'] 'card_number_placeholder': ['Enter Card Number']}} If this structure is maintained it will be easier for me to parse and store as multiple rows in my database table -
Django: Place a Python function into all pages with neat code
I am new to Python and Django, So I have these codes: urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about', views.about, name='about'), path('contact', views.contact, name='contact') ] views.py menus = [ { "name": "Home", "link": "/" }, { "name": "About", "link": "/about" }, { "name": "Contact", "link": "/contact" }, ] def gnavi(): return {'menus': menus} gnavi.html <nav class="gnavi"> <ul> {% for menu in menus %} <li> <a href="{{menu.link}}"> {{menu.name}} </a> </li> {% endfor %} </ul> </nav> base.html {% load static %}<!DOCTYPE html> <html lang="en"> <head>...</head> <body> <header class="header"> {% include 'inc/gnavi.html' %} </header> <main> {% block content %} {% endblock content %} </main> <footer>...</footer> </body> </html> Template Structure: + templates + inc - base.html - gnavi.html - home.html - about.html - contact.html - ... How to place "gnavi.html" to every page without calling it every time in "def" ? # ! Problem: This code works but needs to be called each time a new page is added ! # -> Which is not very nice ! from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'home.html', gnavi()) def about(request): return render(request, 'about.html', gnavi()) def contact(request): return render(request, 'contact.html', gnavi()) 👉 … -
CRUD for child model in django
I have a Course model and also I have a Module model which have many-to-one relationship with course and actually module is the child of course. Now I want to do CRUD proccess for module which every time I create an instance of module model it can recognise its relevant course. but I dont know how to do that in views. Here is models: class Course(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, related_name='courses', on_delete=models.CASCADE) students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='courses_joined', blank=True) title = models.CharField(max_length=200) slug = models.SlugField(default=slugify(title, allow_unicode=True), unique=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Module(models.Model): created = models.DateTimeField(auto_now_add=True) course = models.ForeignKey(Course, related_name='modules', on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True) def __str__(self): return self.title -
How do I fail the booking if the booked boolean field is set to True in django?
I am having trouble making if/else work in my django app, I want to check if a listing is booked, booked is a boolean field and the listing is a foreign key to the Booking class where the user selects a listing to book. Now I just want to know how that foreign key can be checked if the listing is booked so it fails to book and gives an error. views.py @login_required def profile(request): if request.method == "GET": tickets = models.Booking.objects.all().filter(user=request.user) return render(request, "profile.html", {'form': forms.BookingForm(), 'tickets': tickets}) else: try: form = forms.BookingForm(request.POST) new_ticket = form.save(commit=False) new_ticket.user = request.user new_ticket.save() messages.success(request, 'Booking Created Successfully') return redirect('profile') except ValueError: return render(request, 'profile.html', {'form': forms.BookingForm()}) models.py class Listing(models.Model): title = models.CharField(max_length=50) content = models.TextField(max_length=755) price = MoneyField(max_digits=5, decimal_places=2) booked = models.BooleanField(default=False) seller = models.ForeignKey(User, on_delete=models.CASCADE) # avail_days = models.ForeignKey(Days, on_delete=models.CASCADE) def __str__(self): return self.title class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) # how to check if listing is booked and deny if it is True ? # day = models.OneToOneField(Days, on_delete=models.CASCADE) date_booked = models.DateField(auto_now_add=True) def __str__(self): return self.user.username -
Unable to create super user in multi-database in djnago
I have used this part in setting file. DATABASES = { 'default': {}, 'user_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user_db', 'USER': 'postgres', 'PASSWORD': 'test123', 'HOST' :'localhost', 'PORT':'' }, 'wallet_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'wallet_db', 'USER': 'postgres', 'PASSWORD': 'test123', 'HOST' :'localhost', 'PORT':'' }, } DATABASE_ROUTERS = ['userservice.dbRouter.UserRouter', 'walletservice.dbRouter.WalletRouter'] and this is my router.py file class WalletRouter: route_app_labels = {'walletservice'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'wallet_db' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'wallet_db' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'wallet_db' return None and similarly i have created in other app. When i am doing migrations and doing migrate its working fine as it suppose to be. but when i am trying to create superuser its showing the error and i am not getting anything to solve this issue. I have done all the research but didn't found any solution. here the error python manage.py createsuperuser --database=wallet_db Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File … -
i want to add upload image to store in database using django
i want to live my app in heroku.But after sometimes all my uploaded images vanishes as the heroku dyno restart.So now i want to add the static files in database so that they never vanishes. models.py from django.db import models # About Model class About(models.Model): short_description = models.TextField() description = models.TextField() image = models.ImageField(upload_to="about") class Meta: verbose_name = "About me" verbose_name_plural = "About me" def __str__(self): return "About me" # Service Model class Service(models.Model): name = models.CharField(max_length=100, verbose_name="Service name") description = models.TextField(verbose_name="About service") def __str__(self): return self.name # Recent Work Model class RecentWork(models.Model): title = models.CharField(max_length=100, verbose_name="Work title") image = models.ImageField(upload_to="works") def __str__(self): return self.title -
Ajax returning `none` in django
I Have this form in a table with two button. Code: index.html <form action="{% url 'Prediction' %}" method="post"> {% csrf_token %} <table class="table table-striped table-dark" cellspacing="0"> <thead class="bg-info"> <tr> <th>Company's Symbol</th> <th>Current Price</th> <th>View Current chart</th> <th>Action</th> </tr> </thead> <tbody> {% for a,b in stocks %} <tr> <th scope="row" class="comp_name">{{ a }}</th> <td>{{ b }}</td> <td> <input type="submit" class="btn graph-btn" formaction="{% url 'Graph' %}" name="_graph" value="View Graph"> </td> <td> <input type="submit" class="btn predict-btn" name="_predict" value="Predict Closing Price"> </td> </tr> {% endfor %} </tbody> </table> </form> By clicking .graph-btn I need to pass the data of row that button is clicked on. Here is code that's working. <script> $(".graph-btn").click(function() { var $row = $(this).closest("tr"); var $text = $row.find(".comp_name").text(); console.log($text); $.ajax({ type:'POST', url:'{% url 'Graph' %}', data:{ text: $text, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(json){ console.log($text); }, error : function(xhr,errmsg,err) { } }); }); </script> But Problem is that In views.py returning none: views.py def graph(request): if request.method == 'POST' and '_graph' in request.POST: print(request.POST.get('text')) # context = {'name': name} # # print(name) return render(request, 'StockPrediction/chart.html') else: return render(request, 'StockPrediction/greet.html') urls.py urlpatterns = [ path("", views.greet, name='greet'), path("index/", views.index, name='Stock Prediction'), path("prediction/", views.prediction, name='Prediction'), path("view/", views.graph, name='Graph'), ] Please help -
Django import-export - letting users import data
I am trying to use django import-export to let users import their own data. I've integrated it with the admin, and that works well, but I'm having trouble getting the user import side to work. Here are my views: from .models import WordResource from tablib import Dataset from .models import Word from django.contrib import messages # Word import def import_words(request): if request.method == 'POST': file_format = request.POST['file-format'] word_resource = WordResource() dataset = Dataset() new_words = request.FILES['importData'] if file_format == 'CSV': imported_data = dataset.load(new_words.read().decode('utf-8'),format='csv') result = word_resource.import_data(dataset, dry_run=True) elif file_format == 'XLSX': imported_data = dataset.load(new_words.read(),format='xlsx') result = word_resource.import_data(dataset, dry_run=True) if result.has_errors(): messages.error(request, 'Uh oh! Something went wrong...') if not result.has_errors(): # Import now word_resource.import_data(dataset, dry_run=False) messages.success(request, 'Your words were successfully imported') return render(request, 'vocab/import.html') And my import.html template: {% extends "vocab/vocab_base.html" %} {% load bootstrap %} {% block content %} {% if messages %} <div class="messages"> {% for message in messages %} <h3 {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </h3> {% endfor %} </div> {% else %} <h1> Import your words</h1> <p>Here you can import your words from a csv or excel file.</p> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="importData"> … -
Auto fill update form
I have a date model and a Order model. The date model is connected to Order model by a foreignkey, I'm trying to update the date model feilds in Order model with a form. I want the form to autofill the fields with saved data in admin database. I tried a lot to find the solution but I couldn't find it. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100, null=True, blank=True) scheduled_date = models.DateField(max_length=100, null=True, blank=True) service_period = models.DateField(max_length=100, null=True, blank=True) modified_date = models.DateField(max_length=100, null=True, blank=True) finish_date = models.DateField(max_length=100, null=True, blank=True) views.py def dateDetailView(request, pk): order = Order.objects.filter(pk=pk) form = DateForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('/orderlist') context = { 'order': order, 'form':form } return render(request, "date_list.html", context) forms.py class DateForm(ModelForm): class Meta: model … -
import error no module django in apache wsgi.py
I'm running into an issue where, when trying to access my django website served by apache, I get a 500 error and in the log it says that in my wsgi.py file module django does not exist. I suspect this has something to do with my wsgidaemon in my conf file so I've included that as well. I suspect its having trouble with my virtual environment. I think I am setting it correctly with python-home but maybe I am wrong. my virtual environment is located at /home/bitnami/geodjangobackend1/venv and my wsgi.py file is located at /home/bitnami/geodjangobackend1/kapany/kapany/apache/wsgi.py Any help is appreciated and please let me know if I can provide any more information. This is my first apache setup and although I've seen that this error message I have tried following the steps in those questions and haven't been able to fix it. Thank you error.log [Thu Jun 18 05:22:11.574684 2020] [wsgi:error] [pid 5485:tid 140428143658752] [remote 195.54.160.135:39416] mod_wsgi (pid=5485): Target WSGI script '/home/bitnami/geodjang obackend1/kapany/kapany/apache/wsgi.py' cannot be loaded as Python module. [Thu Jun 18 05:22:11.574759 2020] [wsgi:error] [pid 5485:tid 140428143658752] [remote 195.54.160.135:39416] mod_wsgi (pid=5485): Exception occurred processing WSGI script '/home/bitnami/geodjangobackend1/kapany/kapany/apache/wsgi.py'. [Thu Jun 18 05:22:11.574845 2020] [wsgi:error] [pid 5485:tid 140428143658752] [remote 195.54.160.135:39416] Traceback (most … -
django reverse function import
I've seen the following imports for function reverse(). All of them work, why? which one should I use? from django.urls import reverse from django.urls.base import reverse from django.core.urlresolver import reverse from django.shortcuts import reverse -
how to put default user who is creating a session
I want to add user as a default user who is creating the session, class User(models.Model): user_name=models.CharField(max_length=30) def __str__(self): return self.user_name class Session(models.Model): session=models.CharField(max_length=20) user=models.ForeignKey(User,on_delete=models.CASCADE) player_participitating=models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.session