Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model is truncating a decimal place when passed to the view when DecimalField is set
Django Model: class TwoDecimal(models.Model): two_decimal = models.DecimalField(decimal_places=2, max_digits=10) View: def two_decimal(request): test = TwoDecimal( two_decimal = 30.00 ) test.save() return render( request, "test-template.html", {"test": test} ) Template: {{ test.two_decimal }} #==> Displays as 30.0 instead of 30.00 (Despite it being a two decimal field.) This displays properly if it is a query from already saved data. Why is django truncating this decimal place? -
How to display all the data of a CSV file in a HTML page?
I have a code in django that reads a csv file and stores its data in a database, what I intend to do is show that data in an HTML page, this is my view: def addbulkuser(request): prompt = { 'order': 'Order of the file should be: Username, First name, Last name, Email & Password' } if request.method == "GET": return render(request, 'andon/user_form_bulk.html', prompt) data_file = request.FILES['file'] if not data_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') if data_file.name.endswith('.csv'): data_set = data_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): created = User.objects.update_or_create( username=column[0], first_name=column[1], last_name=column[2], email=column[3], password=column[4], last_login=datetime.now(), ) user = User.objects.get(username=column[0]) user.set_password(user.password) user.save() andon_user_group = Group.objects.get(name='andon_user') andon_user_group.user_set.add(user) col = column colu = messages.success(request, 'Users added successfully') context = {'col': col, 'colu': colu } return render(request, 'andon/user_form_bulk.html', context) return render(request, 'andon/user_form_bulk.html') The variable "col" contains all the data in the csv file and I have it called this way in the HTML: {% for column in col %} {{ column }} {% endfor %} But it only shows me in the html the last data in the CSV file, how could I show all the data? Regards. -
djang oscar voucher and offers
if i have a single offer that gives 10% off and also i have a voucher that give 10% off in same products. when i add these two offers to my basket, voucher discount not applied. if i change the priority of offers i can add voucher but single offer discount not applied. i need to apply these two offers to the basket. i created a custom condition for voucher offers. then i tried to consume 0 quantity to that offer. but it's not working as i expected class CustomCouponCondition(CountCondition): ''' oscar_customize.offer.models.CustomCouponCondition ''' name = "Custom Coupon Conditions" class Meta: proxy = True def consume_items(self, offer, basket, affected_lines): for __, line in self.get_applicable_lines(offer, basket, most_expensive_first=True): line.consume(0, offer=offer) -
How to extract href link from this given code using bettersoup. i have tried other results on stack overflow
i am trying to scrap magnetic link from website. I am trying Beautifulsoup. I'm using pycharm with env. This is how the href elements I need look like: -
Drag and Drop a folder with submit button using jQuery and Ajax
I am working on a project where I have to drag and drop folder to upload into the database. I am using Django, jQuery and ajax for this purpose. But the problem is whenever I am trying to submit the form, I am getting this error: CSRF verification failed. Request aborted. Moreover, it's not working in chrome, showing this problem: This site can’t be reached Here is my code: View.py: class BasicUploadView(View): def get(self, request): file_list = file_information.objects.all() return render(self.request, 'fileupload_app/basic_upload/index.html',{'files':file_list}) def post(self, request): file_obj = file_store() zipfile = ZipFile('test1.zip','a',ZIP_DEFLATED) #need to zip folder before storing if request.method == "POST": for upload_file in request.FILES.getlist('file'): for chunk in upload_file.chunks(): zipfile.writestr(upload_file.name,chunk) zipfile.close() file_obj.file = File(open(zipfile.filename,'rb')) file_obj.fileName = os.path.basename(zipfile.filename) file_obj.save() data = {'name':file_obj.fileName, 'url':file_obj.fileName} return JsonResponse(data) HTML: <div style="margin-bottom: 20px;"> <form id="my-form" method="POST" action="{% url 'fileupload_app:basic_upload' %}" enctype="multipart/form-data"> {% csrf_token %} <div id="file-wrap"> <p>Drag and drop file here</p> <input id="my-file" type="file" name="file" multiple draggable="true"> </div> <div> <input type="submit" value="upload"> </div> </form> </div> JS: $(function () { var csrftoken = $.cookie('csrftoken'); $("#my-file").on('change', function (e) { $("#file-wrap p").html('Now click on Upload button'); }); $("#my-form").on('change', function (e) { var eventType = $(this).attr("method"); var eventLink = $(this).attr("action"); $.ajax({ type: eventType, url: eventLink, data: new FormData( this ), … -
Defaut password reset form error: with Django and gmail
I am currently trying to create a password reset form for my site.I have looked on several questions simmilar to this one but none provide the answer for me. I have also created an app password on the gmail website and I am using that as I have 2FA. I am getting the error: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError n8sm12016723wrm.46 - gsmtp', 'webmaster@localhost') . My settings.py code: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAL_HOST_USER = '***********' EMAIL_HOST_PASSWORD = '*********' urls.py file, where the view has been instanciated: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), ] -
Date field not appearing in a Django form
I have created a Django form which almost works correctly All of the fields appear with their Labels and Help Text. If I define the Field type as Dropdown it works perfectly, But if I define a field as Date it just seems to act as a normal Single line text. (A form with html <input type="date" id="today" name="today"> works perfectly in the browser so that isn't the problem) Am I missing something? -
Redirect button to django admin auth views
That could be a stupid question... But I am trying to create a button in my django navbar to redirect to the admin authentication views, and did not manage to find the answer to my question when googling. I manage to do: <li><a href="{% url 'admin:appname_model_perm' %}">Manage XYZ</a></li> and: <li><a href="{% url 'admin:index' %}">Main view</a></li> but I cannot find a way to create one for admin:auth... Here is what I tried: <li><a href="{% url 'admin:auth' %}">Manage auth</a></li> <li><a href="{% url 'admin:authentication' %}">Manage auth</a></li> <li><a href="{% url 'admin:authenticate' %}">Manage auth</a></li> Also, and because I feel stupid to ask the above question, is there a way in django to get a list of all available registered urls? Instead of having this quite useless error message: Reverse for 'auth' not found. 'auth' is not a valid view function or pattern name. Thank you for your help -
How to remove some elements of list input in django admin
i have a list like this in my django admin : Do you know if it's possible to remove some elements of that list ? for example i would like to remove all "gateway" that have the status "inactive" ( status=False ). Here gateway model : class Gateway(models.Model): def __str__(self): return self.name name = models.CharField(max_length=255) logo = models.TextField() status = models.Boolean() I don't even know if it's possible to do some filter on a list in django admin ... thank for your help ! -
Django unresponsive after changing deployment environment to apache/mod_wsgi
I am moving a Django app from IIS (via FastCGI) to Apache on the same system (Windows Server 2016). The site runs fine on IIS and the development server, but when I spin it up in Apache, it is unresponsive (Waiting on 127.0.0.1…). No error messages (despite debug logging in Django and httpd), no useful logs, just unresponsiveness. I added some debug statements throughout the code and it looks like settings.py loads successfully, but wsgi doesn’t return the application. If I comment out all of the apps from settings.py and urls.py, I am greeted with the default login page, so I don’t think that it is a mod_wsgi configuration issue. I am using the latest 64-bit Apache from Apache Lounge (built with VC16), mod_wsgi built from source using pip and VC16, Django 3.0 and Python3.7 (64-bit). My relevant lines from httpd –M, httpd –V, python –V, etc. below. Full output, vhost config and settings.py are on pastebin. $httpd.exe -V Server version: Apache/2.4.41 (Win64) Apache Lounge VS16 Server built: Aug 9 2019 16:46:32 Server's Module Magic Number: 20120211:88 Server loaded: APR 1.7.0, APR-UTIL 1.6.1 Compiled using: APR 1.7.0, APR-UTIL 1.6.1 Architecture: 64-bit Server MPM: WinNT threaded: yes (fixed thread count) forked: … -
Django .objects,get for merged querysets from different models
I have an abstract base model ('Base') from which two models inherit: 'Movie' and 'Cartoon'. I display a list of both movies and cartoons to the user (with the help of itertools.chain). Then I want to give the user the opportunity to delete any of these items, without knowing in advance whether it is a movie or a cartoon. I am trying to do it like this: ... movies = Movie.objects.filter(user_created=userlist).order_by('title') cartoons = Cartoon.objects.filter(user_created=userlist).order_by('title') all_items = list(chain(movies, cartoons)) item = all_items.get(id=item_id) item.delete() But then PyCharm states, Unresolved attribute reference 'get' for class 'list' I understand why this happens but I don't know how to avoid it. Is there any way to merge two querysets from different models and apply get or filter without removing the abstract base model and creating a physical parent model? -
How to add taxonomy models like Drupal in Wagtail?
How to add taxonomy models like Drupal in Wagtail? Like this: - Sports --- Baseball --- Basketball --- Footbal - Technology --- Computers --- Videogames --- Software ----- Development ----- Apps ..... And create url pattern based in taxonomy terms with a serial number at the end Like this: www.myweb.com/technology/software/development/post-title-slug-54321 -
Right serializer relations between two models
I'm trying to create two interlinked instances of models in the database and I get an error. TypeError: Got a TypeError when calling Vendors.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Vendors.objects.create(). You may need to make the field read-only, or override the VendorsSerializer.create() method to handle this correctly. models.py class Vendors(models.Model): COUNTRY_CHOICES = tuple(COUNTRIES) vendorid = models.AutoField(primary_key=True) vendor_name = models.CharField(max_length=45, unique=True) country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) nda = models.DateField(blank=True, null=True) ... class VendorContacts(models.Model): contact_id = models.AutoField(primary_key=True) vendor = models.ForeignKey('Vendors', models.DO_NOTHING) contact_name = models.CharField(max_length=45, blank=True, null=True) email = models.CharField(max_length=80, blank=True, null=True) phone = models.CharField(max_length=45, blank=True) serializer.py class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( 'contact_name', 'phone', 'email',) class VendorsSerializer(serializers.ModelSerializer): vendor_contact = VendorContactSerializer() class Meta: model = Vendors fields = ('vendor_name', 'country', 'nda', 'vendor_contact',) views.py class VendorsCreateView(APIView): """Create new vendor instances from form""" serializer_class = (VendorsSerializer) def post(self, request, *args, **kwargs): vendor_serializer = VendorsSerializer(data=request.data) vendor_contact_serializer = VendorContactSerializer(data=request.data) try: vendor_serializer.is_valid(raise_exception=True) \ and vendor_contact_serializer.is_valid(raise_exception=True) # vendor = vendor_serializer.save(user_id=CustomUser.objects.get(id=2)) print(vendor_serializer.validated_data) vendor = vendor_serializer.save() vendor_contact_serializer.save(vendor=vendor) except ValidationError: return Response({"errors": (vendor_serializer.errors, vendor_contact_serializer.errors, )}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) I also tried to do in VendorsSerializer vendorcontact = VendorContactSerializer(source='vendor.vendorcontacts', many=True) but got the … -
How to implement paginations in function base views in django
i know how to implement pagination in class base views using ListView class ProductListView(ListView): model = product template_name = 'products/product_list.html' context_object_name = 'products' ordering = ['-pub_date'] paginate_by = 5 but i don't know how to implement paginations in function base views. i read that we have to import Paginator for django.core.paginator and use it in functions base view like this paginator = Paginator(qs, 5) but it's not working. def Productlistview(request): qs = product.objects.all() location_search = request.GET.get('location') print(location_search) categories = request.GET.get('categories') price = request.GET.get('price') ordering = ['-pub_date'] paginator = Paginator(qs, 5) if location_search != "" and location_search is not None: qs = qs.filter(location__contains=location_search) context = { 'posts': qs } return render(request, "products/product_list.html", context) -
How to access authenticated user in graphene-django resolve method?
I have added this to my Query class and it's returning null in response. me = graphene.Field(UserType) def resolve_user(root, info): logger.info("***** Inside resolve ****") return info.context.user and my UserType is defined like this. class UserType(DjangoObjectType): fields = ["id", "name", "email", "username"] class Meta: model = User I'm on Django==3.0 if it helps I'm authenticated and the cookies are present. It's not even printing the log which is confusing me. -
Django: search form does not work due to page not found error
I am new to Django. I am trying to implement a search function on a blog but it does not appear to work. I do not understand why. Could someone tell me what goes wrong. My code snippet in the HTML looks like this: <form action="{% url 'search' %}"> <div class="form-group"> <input type="search" name="q" id="search" placeholder="Enter search query"> <button type="submit" class="submit"><i class="icon-search-1"></i></button> </div> </form> My urls.py is setup like this: urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog, name= 'post-list'), path('search/', search, name='search'), path('post/<id>/', post, name= 'post-detail'), path(r'tinymce/', include('tinymce.urls')) ] And the Error looks like this: Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='post-list'] search/ [name='search'] post/<id>/ [name='post-detail'] tinymce/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, action=/search, didn't match any of these. As you can see: search is in the urls.py: does it have anything to do with the fact that somehow Django automatically puts a leading '/' in front of 'search'? As indicated: I am relatively new to Django so I hope this is enough information to be able to answer my question. If not, please indicate so. -
Django: separate sessions for admin and user
I have two React frontends (admin.example.com and www.example.com). My Django backend is located on backend.example.com. Right now I have one LoginView for both use cases (admin and end-user). I am using SessionMiddleware. What I want to achieve are two different sessions - so I can login as an admin and have access to admin.example.com and separately be logged in into www.example.com as a user. If I set SESSION_COOKIE_DOMAIN = '.example.com' I have just a single session for everything. Can anyone point me in the right direction on how could I achieve this? Any best practices? Any help is very much appreciated. -
Is it possible to define a field that auto-increments within the value of a foreign key?
Is it possible to define a field that auto-increments within the value of a foreign key? E.g. if we define Company and Department models in Django: class Company(models.Model): name = models.CharField(max_length=25) class Department(models.Model): company = models.ForeignKey(Company) department_number = ...? # should start from 1 for each company in a pure SQL implementation the pair (company_id, department_number) would be a composite primary key. I'm looking for solutions in Django or SQL that are safe (in terms of multiple processes creating departments simultaneously) and efficient. I'm using MySQL, but comparisons with other databases are also welcome. -
Django add specific attribute for form select options
I have a two models : class Font(models.Model): name = models.CharField(max_length=64) css_value = models.CharField(max_length=128) def __str__(self): return self.name class DesignOverride(models.Model): x_font = models.ForeignKey(Font, null=True, blank=True, on_delete=models.SET_NULL) In my ModelForm for 'DesignOverride' I am calling 'x_font' using the widget select : class DesignOverrideForm(forms.ModelForm): class Meta: model = DesignOverride fields = ['x_font'] widgets = { 'x_font': forms.Select(attrs={ 'class': 'form-control'}) } I wanted to know if there was a way from Django to customize my options by giving them the style 'font-family: X' where X is the css_value of the options Font. I tried to loop in the 'x_font' select field in the template but seems it's only having the options as string (and therefore lost the information about 'css_value'). -
Where did the error in the Django model come from?
I'm trying to add additional fields for the User model. The migrate and makemigrations commands worked. When I try to create createsuperuser, this error occurs . Postgresql Is Enabled . I tried to change upload_to, add "blank = True", "default" to the model parameters, but nothing changed. Trace: return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: ОШИБКА: отношение "blog_customuser" не существует LINE 1: ..._customuser"."age", "blog_customuser"."city" FROM "blog_cust... ^ The above exception was the direct cause of the following exception: 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 "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 95, in handle error_msg = self._validate_username(username, verbose_field_name, database) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 201, in _validate_username self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\base_user.py", line 44, in get_by_natural_key return self.get(**{self.model.USERNAME_FIELD: username}) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 402, in get num = len(clone) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 256, in __len__ self._fetch_all() File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line … -
Unbound Local Error while searching in Django
I'm trying to search advertisements by their locations. But For the following codes, I'm receiving: 'UnboundLocalError: local variable 'advertisements' referenced before assignment' I'm new to Django so any help would be appreciated. views.py: def Search(request): query = request.GET['query'] advertisements = advertisements.objects.filter(place__icontains=query) params = {'advertisements':advertisements} return render(request, 'search.html', params) html: <form method="get" action="/search" class="form-inline"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="query" id="query"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit"><i class="fas fa search"></i><a>Search</a></button> </form> <h2>Search Results:</h2> {% for advertisement in advertisements %} <div class="col-sm"> <div class="card" style="width: 16rem;"> <div class="card-body"> <h5 class="card-title">{{advertisement.place}}</h5> <p>House/Apartment Size: {{advertisement.size}} squarefeet</p> <p>Time Posted: {{advertisement.date_posted}}</p> <p>Rent per month: {{advertisement.rent}} taka</p> <a href='{% url 'advertisement_details' advertisement.id %}' class="card-link">Full Details</a> </div> </div> </div> {% endfor %} models.py: class advertisements(models.Model): place=models.CharField(max_length=30) address=models.CharField(max_length=50) bedroom=models.PositiveSmallIntegerField() bathroom=models.PositiveSmallIntegerField() rent=models.PositiveIntegerField() size=models.PositiveIntegerField() date_posted=models.DateTimeField(default=timezone.now) owner= models.ForeignKey(User,on_delete=models.CASCADE) -
Enable/Disable an HTML Element With Dynamically Generated Names/Tags
I have a table in HTML where the ID is dynamically generated from a row counter: $(table).find('tbody').append("<tr>name=\"tableRow\"</tr>" + "<td>" + "<select id=\"shapeSelect_" + rowCount + "></td>" + "<option onclick=\"sphereSelect()\" value=\"sphere\">Sphere</option>" + "<option onclick=\"cylinderSelect()\" value=\"cylinder\">Cylinder</option>" + "</select>" + "</td>" + "<td><input type=\"text\" id=\"altitude" + rowCount + "\"</td>" + "<td><input type=\"text\" name=\"maxAlt\" id=\"maxAltitude_" + rowCount + "></td>" + "</tr>" I need maxAltitude to become disabled for input when sphere is selected. When cylinder is selected, it should become enabled for input. Every example I find is pretty simple but requires knowing exactly what the ID is, where in my code it is dynamically generated. This is an example of what I'm finding: $(#maxAltitude).prop("disabled", true); How can I do this when maxAltitude will be something more like: maxAltitude_10? There may be 1-n rows in a table, and I need to specifically disable the max altitude in the row where the dropdown select was changed. I've tried jQuery and javascript but can't seem to find a good way to do this: <option onclick="shapeSelect()" value="sphere">Sphere</option> <option onclick="shapeSelect()" value="cylinder">Cylinder</option> function shapeSelect() { var shapeSelects = document.getElementsByName("shapeSelect"); var maxAlts = document.getElementsByName("maxAlt"); for(var i = 0; i < shapeSelects.length; i++) { switch(shapeSelects[i].value) { case "sphere": maxAlts[I].disabled = True; … -
1048, "Column 'user_id' cannot be null"
models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=30,blank=False,null=False) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10,blank=True) def __str__(self): return self.fullname forms.py class UserForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'})) password= forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'})) email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'})) password2 = None class Meta: model=User fields=['username','password','email'] class ProfileForm(forms.ModelForm): fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'})) class Meta: model=Profile fields=['fullname'] views.py def register(request): if request.method =='POST': form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): variable=form.save(commit=False) variable.password = pbkdf2_sha256.encrypt(request.POST['password'],rounds=12000,salt_size=32) variable.save() profile=profile_form.save(commit=False) profile.username=variable.username profile.save() username = form.cleaned_data.get('username') messages.success(request,f'account created for { username }') return redirect('login') else: form = UserForm() profile_form = ProfileForm() context={'form':form , 'profile_form':profile_form} return render(request, 'users/register.html',context) I have created two table auth_user (default) and users_profile.When i register the User default data goes into auth table but fullname is not inserted into user_profile. -
Django application structure,
I'm trying to deploy my Django project to Google AppEngine, however I can't figure out how to properly set up application entrypoint. This is my whole project structure: service-master: app.yaml main.py service: manage.py service-project: wsgi.py settings.py ... service-app-1: ... service-app-2: ... How can I make it work? I tried to move main.py to service and use entrypoint: gunicorn --chdir /service main:application in app.yaml but it results in Error: can't chdir to '/service', I guess AppEngine doesn't allow to change directory. -
Displaying title in the django administration instead of object
I have got a main table called Item and table Bike that is connected to Item with OneToOneField. When I add a new Bike using django administration page, it shows as Bike object (1). Is there a way to show the title of that Bike, that is stored in the Item table instead of that "Bike object (1)"? my models.py: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes')