Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prevent django form from subtracting values again upon submission
This is my update function, where I can update my order details. In this form, when I update the status field to shipped values from other model fields get subtracted. But the problem I facing with my code is that every time I change other fields and update the form. The values get subtracted again. def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': if form.is_valid(): box = form.cleaned_data.get('box') product = form.cleaned_data.get('product') if order.status =='Shipped': Supplement.objects.filter(supplement_name=product).update(quantity=F('quantity') - box*30) Material.objects.filter(material_name='Packs').update(quantity=F('quantity')-box) Material.objects.filter(material_name='Dispenser').update(quantity=F('quantity')-box) Material.objects.filter(material_name='Cargo Box').update(quantity=F('quantity')-box) order = form.save(commit=False) order.updated_by = request.user order.date_updated = timezone.now() if order.scheduled_date is not None and order.status == 'In Progress': order.status = 'Scheduled' order.save() form.save() return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) -
How to delete an image from the database in django
I have a database that contains images as posts and want the functionality, for images in the database to get deleted once the post gets deleted. I am using the pillow module to handle images in the database. Is there any way I could do that? In my models.py this is the code I use to save images. Just in case it was needed def save(self): super().save() img = Image.open(self.picture.path) width, height = img.size ratio = width/height if img.height > 500: outputsize = (500, (height/ratio)) img.thumbnail(outputsize) img.save(self.picture.path) Thanks a lot! -
Class not being created
I'm trying to create a Menu class that is comprised of a list of dishes coming from the Dish class. When a Restaurant is created, I want to also create the Menu which initially has no Dishes to start off. When I run the code though, model_create.py, I'm getting an error that Menu is not created which halts everything. #models.py from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=100) open_time = models.CharField(max_length=10) close_time = models.CharField(max_length=10) address = models.CharField(max_length=100) phone = models.CharField(max_length=20) email = models.CharField(max_length=30) class Dish(models.Model): name = models.CharField(max_length=100) cook_time = models.IntegerField(default=0) fresh_time = models.IntegerField(default=0) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) image = models.BinaryField(blank=True) #description = models.CharField(max_length=100) serve = models.BooleanField(default=False) class Menu(models.Model): dish = models.ForeignKey(Dish, on_delete=models.SET_NULL, default=None, null=True) last_served = models.DateTimeField(null=True) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE,default = None) #model_create.py from ..models import User, Restaurant, Dish, Menu def create_restaurant(): restaurant = Restaurant() restaurant.save() create_menu(restaurant.id) return restaurant.id def create_menu(res_id): menu = Menu(restaurant_id = res_id) #restaurant_id var name in database menu.save() return -
Django: Uploading Images in a Specific location
I have a created a function for my items model where there are images to be uploaded according to the name of the user and the title of the item. Now I am trying to add more images to this item and there is a foreign key with the image, but now instead of creating randomly uploading the new images to another folder I want to upload these images to the same folder that was previously determined according to the same item. The functions below will be more descriptive: Here is the models and the function where the images is uploaded to a location as per the users name and the title of the item: class Item(models.Model): def upload_design_to(self, filename): return f'{self.designer}/{self.title}/{filename}' designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) Now I have created a new mImage model to add more images to this item and want them to be uploaded to the very same folder class Images(models.Model): #Todo fix this item = models.ForeignKey(Item, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True) image = models.ImageField(blank=True, upload_to='upload_design_to') -
Wagtail: Multiple reusable elements on one Page
I need to create a reusable element (cta button) that I can include in many places throughout the page. These cta buttons are used ~8 times throughout the design. How can I do this without copy-pasting? Similar to this: Ways to create reusable sets of fields in Wagtail? Except I must be able to use the set several times on a single page. This is what I am trying to do: class CTAButton(models.Model): text = RichTextField(max_length=25, features=["bold"]) url = models.URLField(null=True, blank=True) page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels = [ FieldPanel("text"), FieldPanel("url"), PageChooserPanel("page"), ] class Meta: abstract = True class HomePage(Page): template = "home/home_page.html" hero_heading = models.CharField(max_length=50) hero_subheading = models.CharField(max_length=255) hero_cta1 = CTAButton hero_cta2 = CTAButton content_panels = Page.content_panels + [ FieldPanel("hero_heading"), FieldPanel("hero_subheading"), ] -
no reverse matching at / and crawler is not a registered namespace
I am trying to make a codeforces crawler and i am just adding user authentication in the somehow failed to implement.Reverse not match and crawler is not a registered namespace are the errors am getting . PS I am a beginner crawler/urls.py app_name = 'crawler' urlpatterns =[ path('',views.index,name='index'), path('formpage/',views.search_form_view , name='searchform'), path('formpage/<str:handle>',views.person, name= 'person'), path('user_login/',views.user_login,name ="user_login"), path('logout/',views.user_logout,name="logout"), base.html <body> <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <!-- Brand --> <a class="navbar-brand" href="{% url 'crawler:index'%}">Crawler</a> <!-- Links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'crawler:searchform'%}">Search</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link 2</a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{%url 'crawler : logout'%}">Log Out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{%url 'crawler :user_login'%}">Login</a> {% endif %} </li> </li> </ul> </nav> <br> {% block body_block %} {% endblock %} </body> views.py @login_required def user_logout(request): logout(request) return HttpResponse(reverse('index')) -
In Django, I wonder why import UserAdmin as BaseUserAdmin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin Isn't it just a name? I have become curious to use it conventionally. Thank you for your kind reply in advance. -
Render the User model relationship field on Django template
it was supposed to be simple but I'm not able to solve it so far. I got a Profile model which is a OneToOneField with the User model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) rua = models.CharField(max_length=254) numero = models.CharField(max_length=20) bairro = models.CharField(max_length=254) complemento = models.CharField(max_length=254) cidade = models.CharField(max_length=200) estado = models.CharField(max_length=2) cep = models.CharField(max_length=9) def __str__(self): return self.rua What I'm trying to do is render some Profile fields on Django template using the {{ user.profile.rua }} but it's not working. Any help? Thank you! -
Error "can only concatenate tuple (not "list") to tuple" when adding heroku line
I'm trying to deploy my project, but when I try to compile with the "django_heroku.settings (locals ())" line to my settings.py, it returns the following error: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/anderson.maronato/Desktop/proj/django-finale/choiceshoes/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/anderson.maronato/Desktop/proj/django-finale/choiceshoes/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/Users/anderson.maronato/Desktop/proj/django-finale/choiceshoes/env/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/anderson.maronato/Desktop/proj/django-finale/choiceshoes/env/lib/python3.8/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/anderson.maronato/Desktop/proj/django-finale/choiceshoes/env/lib/python3.8/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/anderson.maronato/Desktop/proj/cc2/choiceshoes/djecommerce/settings/development.py", line 10, in <module> MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ] TypeError: can only concatenate tuple (not "list") to tuple My Settings.py with the configuration import os from decouple import config import django_heroku BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = config('SECRET_KEY') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'crispy_forms', 'django_countries', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
How to reach find an Image in the Static File
I have a beginner's question, I have images which are basically arrows, and I have located them in the media folder but I can't reach them and the images are not appearing on the page. I have tried several things like copying the paths but still, there is something incorrect. The image absolute path is: C:\Users\Ahmed\Desktop\Project 4.3\media\arrow-left.png Here is the Template <img id="slideLeft" class="arrow" src= {% static "media\arrow-left.png" % } > I have tried everything but it is still not working. -
Render Python Console output on HTML while running functions at same time
So, I'm using Django/Python to build a HTML. In the html, I have a simple form, and the user can enter data. When the user submits the form, I redirect to a function that performs some 'jobs' and returns the same URL. The problem is that this 'job' is actually a lot of functions and, during the process, I have several prints on the console, which I would like to show to the user, so that he could see what is going on while the program is executed. So, how to render, the console output in html, at the same moment that it appears? I know that I could pass it on, when I render/return the view function, but that way, I would only show the console print, to the user, when the view function was already finalized. However, I wanted to show the print during the process. Is there a way to do this? Below is an example: Backend function (views.py) def index_view(request, *args, **kwargs): form= MyForm() if request.method == 'POST': if form.is_valid(): test_function_a() test_function_b() test_function_c() else: print(form.errors) return render(request, 'index.html', {'form': form}) Funcitions Example (views.py) def test_function_a(): print('this') print('is') print('function') print('a') def test_function_b(): print('this') print('is') print('function') print('b') def … -
Custom field validation in Django Rest Framework
I am coding an app with DRF where ab User can write a review and add pictures to it. Here are my models: class Restaurant(models.Model): maps = models.CharField(max_length=140, unique=True) adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) class StarterPic(models.Model): restaurant_review = models.OneToOneField(RestaurantReview, on_delete=models.CASCADE) name = models.CharField(max_length=40) picture = models.ImageField() I have one model for each type of pictures (inside, outside, starter, main course, dessert...) but didn't put them for the sake of readability. My serializers: class RestaurantIdSerializer(serializers.ModelSerializer): class Meta: model = Restaurant field = fields = '__all__' class RestaurantReviewSerializer(serializers.ModelSerializer): class Meta: model = RestaurantReview field = fields = '__all__' class StarterPicsSerializer(serializers.ModelSerializer): class Meta: model = StarterPic fields = '__all__' def validate_restaurant_review(self, value): user = self.context['request'].user if not value in user.restaurantreview_set.values_list('restaurant_id', flat=True): raise serializers.ValidationError('User has not reviewed the restaurant') return value My views: class RestaurantIdViewset(viewsets.ModelViewSet): queryset = models.Restaurant.objects.all() serializer_class = serializers.RestaurantIdSerializer class RestaurantReviewViewset(viewsets.ModelViewSet): queryset = models.RestaurantReview.objects.all() serializer_class = serializers.RestaurantReviewSerializer permission_classes = [IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly] def perform_create(self, serializer): serializer.save(review_author=self.request.user) class StarterPicsViewset(viewsets.ModelViewSet): queryset = models.StarterPic.objects.all() serializer_class = serializers.StarterPicsSerializer permission_classes = [IsAuthenticatedOrReadOnly] My issue is that I want only the author of the review to post a picture on the review. With the validate_restaurant_review I am using, no … -
Django: How to fix NoReverseMatch
I have a minor issue and I am stuck about how to fix it. In my project, a user can add a post article and add an item product each is a different app with different models and they can be the same user. I am trying to add a link to go to Item model related to a specific user (designer) if available from a page with the list of Posts of this particular user (designer). So, in the 1st app called Score with a Post model, there is UserPostListView list view, I have my posts looped related only to a designer name. I want to add a link another page related to the items of this particular designer. My goal is to check if there is an item related to the designer in the User Post list page, I keep getting NoReverseMatch Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here is the item models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return … -
how could I change the language of Google map api according to user's selector
here is my code in HTML: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select id="sel_id" name="language" onchange="this.form.submit();"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option class="option" value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %} > {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> </form> this is aimed to make Django internationalization(change the language of my webpages). Now I want to change the language of my Google map api at the same time. I have tried this.my code: document.getElementById('sel_id').addEventListener('change', () => { let lang = $(this).find('option:selected').val(); // console.log(lang); // alert("You have selected the language code: " + lang); but the problem is : when I choose one option from the dropdown list, the page will be refresh imediately. and then I couldnot get the value of "lang" in JS. [which means 'alert' could work before refreshing pages, however there is nothing about the 'console.log'. So how could I let my pages wait for my JS? -
Error: unhashable type: 'dict' with Django and API data
I am trying to pass data from an api through Django views.py into my html page. I have the error above, have read similar threads ie tuple() the data, however I cannot pass it no matter what I try. If anyone is aware of a solution - thanks. views.py: def forces(request): import requests import json api_request = requests.get("https://data.police.uk/api/forces") try: api = json.loads(api_request.content) api = tuple(api) except Exception as e: api = "Error getting api forces data, sorry!" return render(request,'forces.html', {'api', api}) The data sample: [{"id":"avon-and-somerset","name":"Avon and Somerset Constabulary"},{"id":"bedfordshire","name":"Bedfordshire Police"},{"id":"cambridgeshire","name":"Cambridgeshire Constabulary"},{"id":"cheshire","name":"Cheshire Constabulary"},{"id":"city-of-london","name":"City of London Police"},{"id":"cleveland","name":"Cleveland Police"},{"id":"cumbria","name":"Cumbria Constabulary"},{"id":"derbyshire","name":"Derbyshire Constabulary"},{"id":"devon-and-cornwall","name":"Devon & Cornwall Police"},{"id":"dorset","name":"Dorset Police"},{"id":"durham","name":"Durham Constabulary"},{"id":"dyfed-powys","name":"Dyfed-Powys Police"},{"id":"essex","name":"Essex Police"},{"id":"gloucestershire","name":"Gloucestershire Constabulary"},{"id":"greater-manchester","name":"Greater Manchester Police"},{"id":"gwent","name":"Gwent Police"},{"id":"hampshire","name":"Hampshire Constabulary"},{"id":"hertfordshire","name":"Hertfordshire Constabulary"},{"id":"humberside","name":"Humberside Police"},{"id":"kent","name":"Kent Police"},{"id":"lancashire","name":"Lancashire Constabulary"},{"id":"leicestershire","name":"Leicestershire Police"},{"id":"lincolnshire","name":"Lincolnshire Police"},{"id":"merseyside","name":"Merseyside Police"},{"id":"metropolitan","name":"Metropolitan Police Service"},{"id":"norfolk","name":"Norfolk Constabulary"},{"id":"north-wales","name":"North Wales Police"},{"id":"north-yorkshire","name":"North Yorkshire Police"},{"id":"northamptonshire","name":"Northamptonshire Police"},{"id":"northumbria","name":"Northumbria Police"},{"id":"nottinghamshire","name":"Nottinghamshire Police"},{"id":"northern-ireland","name":"Police Service of Northern Ireland"},{"id":"south-wales","name":"South Wales Police"},{"id":"south-yorkshire","name":"South Yorkshire Police"},{"id":"staffordshire","name":"Staffordshire Police"},{"id":"suffolk","name":"Suffolk Constabulary"},{"id":"surrey","name":"Surrey Police"},{"id":"sussex","name":"Sussex Police"},{"id":"thames-valley","name":"Thames Valley Police"},{"id":"warwickshire","name":"Warwickshire Police"},{"id":"west-mercia","name":"West Mercia Police"},{"id":"west-midlands","name":"West Midlands Police"},{"id":"west-yorkshire","name":"West Yorkshire Police"},{"id":"wiltshire","name":"Wiltshire Police"}] -
How can I change the view site link in Django admin, depending on which app is used?
I am making a project where each client have their own app. This is because they have similar pages but not exactly the same so I think it's a good approach(I may be wrong) to just copy one app for each new client. I have not tried it yet, I am still planning for it. I see one problem with the view site link in the admin. I will let the clients use the admin. How can I set the view site link to the main page for the client? One way to solve it would be to leave it as is and have a function checking their user name and redirecting to the right app. But is there any other way to solve this problem? -
Django concurrently insert non-unique fields?
I'm trying to concurrently insert data into my database using the Django methods, I found the get_or_create method and use it like below: record, created = MyModel.objects.get_or_create( start='A', end='B', model_b=model_b, defaults={"description": "some description", "other_model": other_model) However, I understand that this only works if the start, end and model_b fields are unique_together - as per the Django documentation. This causes a problem as unique data is not enough, my code detects overlapping elements, so if one record is start=A and end=C, then the second record of start=B and end=D should not insert as they overlap. I've already built all the code to detect the overlapping and it all works perfectly, however when you run the method concurrently, the overlapping entries are being inserted as they are still unique. So how can I overcome this? I am guessing I need a way of making sure that each thread locks the DB table (but not preferred option as I know the problems that can cause later on) or some other mechanism to make sure that two or more threads don't read and insert the DB at the same time. -
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.customuser', but app 'users' isn't installed
I have been trying to make an basic Blog application using CRUD operation with the help of Django web framework, I have this code in models.py file of my blog application. `from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=250) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', args=(str(self.id)))` And now, when I tried to migrate, I am getting this error saying that "ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.customuser', but app 'users' isn't installed." And because of that, I am not able to see Users link inside the admin account at "http://127.0.0.1:8000/admin/" -
Django: Average of Subqueries as Multiple Annotations on a Query Result
I have three Django models: class Review(models.Model): rating = models.FloatField() reviewer = models.ForeignKey('Reviewer') movie = models.ForeignKey('Movie') class Movie(models.Model): release_date = models.DateTimeField(auto_now_add=True) class Reviewer(models.Model): ... I would like to write a query that returns the following for each reviewer: The reviewer's id Their average rating for the 5 most recently released movies Their average rating for the 10 most recently released movies The release date for the most recent movie they rated a 3 (out of 5) or lower The result would be formatted: <Queryset [{'id': 1, 'average_5': 4.7, 'average_10': 4.3, 'most_recent_bad_review': '2018-07-27'}, ...]> I'm familiar with using .annotate(Avg(...)), but I can't figure out how to write a query that averages just a subset of the potential values. Similarly, I'm lost on how to annotate a query for the most recent <3 rating. -
Acces a model/class attribute by filtering fields
I'm trying to pass a row from my database by doing: def index(request): current_user = request.user username = User.objects.get(username=current_user.username) listing = Listing.objects.filter(owner=username).all() return render(request, "auctions/index.html", { "listing":listing }) But if then i try to access by doing listing.title I get the following error: 'QuerySet' object has no attribute 'title' How could I access listing.title? I only want the row where owner=username -
Refused in Django project
I have some error when get css file using javascript in django I can't guess it If you can do it, please help me Thanks enter image description here -
Resetting Django Form
When the user submits the registration form, I want the page to be refreshed. And the form to be empty. In the past I have achieved this with code similar to the following - form=RegisterForm() But on this occasion, the username and email fields are not being reset. I think I could achieve my objective with AJAX but I am baffled why a solution that has worked previously is not working now. def register_page(request): form=RegisterForm(request.POST or None, request.FILES or None) context = { "form": form } if form.is_valid(): username = form.cleaned_data.get("full_name") emailbatman = form.cleaned_data.get("email") profilepictureironman = form.cleaned_data.get("profilepicture") thanospassword = form.cleaned_data.get("password2") new_user = User.objectsbatman.create_user(username, emailbatman, thanospassword, profilepictureironman) form=RegisterForm() return render(request, "accounts/register.html", context) Before I press submit After I press submit -
Django annotate aggregation issue
I'm building a site that uses django-tables2 and django-filters to return a table of data. I've figured all of that out (for the most part) and figured out how to use a query to populate the table. I'm struggling with successfully aggregating my data in the queryset. I want to show average earnings by major, and am getting multiple lines rather than aggregating. Here is the code. I appreciate any help you can offer! Bonus points if anyone knows why there is a square showing in some of the degree type values, it is not showing in the CSV I'm using to populate my database. Thank you! models.py class MajorData(models.Model): unitid = models.IntegerField() opeid6 = models.IntegerField() instname = models.CharField(max_length=255, verbose_name='Name of Institution') control = models.CharField(max_length=255,null=True, blank=True) main = models.IntegerField(null=True, blank=True) cipcode = models.IntegerField(null=True, blank=True) cipdesc = models.CharField(max_length=255,null=True, blank=True, verbose_name='Degree Description') credlevel = models.IntegerField(null=True, blank=True) creddesc = models.CharField(max_length=255,null=True, blank=True, verbose_name='Degree Type') count = models.IntegerField(null=True, blank=True) debtmedian = models.IntegerField(null=True, blank=True, verbose_name='Median Debt') debtpayment10yr = models.IntegerField(null=True, blank=True) debtmean = models.IntegerField(null=True, blank=True) titleivcount = models.IntegerField(null=True, blank=True) earningscount = models.IntegerField(null=True, blank=True) mdearnwne = models.IntegerField(null=True, blank=True, verbose_name='Median Earnings') ipedscount1 = models.IntegerField(null=True, blank=True) ipedscount2 = models.IntegerField(null=True, blank=True) def __str__(self): return self.instname tables.py class MajorTable(tables.Table): class Meta: orderable=False … -
How do I render 3 related models in one page using inlineformset_factory?
admin page i want a "create.html" template and i need help making it look like the way it looks on the admin page(check image). And ideas? admin.py from nested_inline.admin import NestedModelAdmin, NestedTabularInline class CandidateInline(NestedTabularInline): model = Candidate list_display = ('office', 'name', 'vote_count') class OfficeInline(NestedTabularInline): model = Office inlines = [CandidateInline,] list_display = ('election', 'name') class ElectionAdmin(NestedModelAdmin): inlines = [OfficeInline] prepopulated_fields = {'slug' : ('name', )} list_display = ('name',) # Register your models here. admin.site.register(Election, ElectionAdmin) model.py class Election(models.Model): name = models.CharField(max_length = 30) slug = models.SlugField(max_length = 250, null = False, unique = True, primary_key = True) class Office(models.Model): election = models.ForeignKey(Election, on_delete=models.CASCADE, default=None) name = models.CharField(max_length = 30) class Candidate(models.Model): office = models.ForeignKey(Office, on_delete=models.CASCADE, default=None) name = models.CharField(max_length = 30) vote_count = models.IntegerField(default=0) -
Django REST Framework. How to set special permission on register users?
I set in global settings this permission classes: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', ], so admins can edit, users can see, others can nothing. But this rule doesn't share on registration module which is on POST auth/users. I can create new users even from the new users which i've just created and activated in admin panel. So how to setup special permission rule for it?