Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
circular import error in django
PS C:\Users\Shirish\Desktop\carwebsite> python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x061CB078> Traceback (most recent call last): File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 538, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 398, in check warnings.extend(check_resolver(pattern)) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 397, in check for pattern in self.url_patterns: File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 545, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'home.urls' from 'C:\\Users\\Shirish\\Desktop\\carwebsite\\home\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Django signal conditionally update one table based on another
I'm working on my first django project that is a sports betting game. Here are my models: class Game(models.Model): home_team = models.CharField(max_length=200) away_team = models.CharField(max_length=200) home_goals = models.IntegerField(default=None) away_goals = models.IntegerField(default=None) class Bet(models.Model): gameid = models.ForeignKey(Game, on_delete=models.CASCADE) userid = models.ForeignKey(User, on_delete=models.CASCADE) home_goals = models.IntegerField() away_goals = models.IntegerField() score = models.IntegerField(default=None, null=True) First I create a game instance with null values in goals fields, then users make their bets. Once the game is over, I update game goals fields. Now I need to assign points for each user like this: WHEN bet.home_goals = game.home_goals AND bet.away_goals = game.away_goals THEN 2 WHEN game.home_goals > game.away_goals AND bet.home_goals > bet.away_goals THEN 1 WHEN game.home_goals < game.away_goals AND bet.home_goals < bet.away_goals THEN 1 WHEN bet.home_goals = bet.away_goals AND game.home_goals = game.away_goals THEN 1 ELSE 0 It seems that I should create a POST_SAVE singal to update Bet.score for each user based on update of Game.home_goals and Game.away_goals? But I have no idea how to do this -
Getting RIGHT JOIN with intermediate table with Django ORM?
I have these models: class Region(models.Model): region_name = models.CharField(max_length=64) def __str__(self): return self.region_name class GameRegionRelease(models.Model): region = models.ForeignKey( Region, on_delete=models.CASCADE, verbose_name='region' ) game = models.ForeignKey( Game, on_delete=models.CASCADE, verbose_name='game' ) release_date = models.DateField( verbose_name='release date', default=None ) class Game(models.Model): game_name = models.CharField(max_length=512) release_dates = models.ManyToManyField( Region, related_name='game_release_dates', through='GameRegionRelease' ) What I'm looking to get is every region listed for every game, even if there is no region data for that game. So the results would be Game x Region, with the region data filled in by GameRegionRelease where available. I'd want something similar to what the following would produce: SELECT * FROM gameslist_region gr CROSS JOIN gameslist_game gg LEFT JOIN gameslist_gameregionrelease grr ON gg.game_name = grr.game_id AND gr.region_name = grr.region_id; But I don't know how to express this in Django using native ORM constructs. Is this possible? I'm using Python 3.6.4 and Django 2.0.2. -
Multiple pagination in Django not working
I have 4 models: faculties, departments, studies and courses. I wanted a pagination for all the courses available and that was easy to achieve. But now I'm stuck because I wanted pagination for faculties also, that will show specific courses of the accessed faculty. The pagination will show for faculties as well, but problem is that if I try to go to the second page, it will redirect me to the second page of all courses list. Or, if I change page on all courses and then try to access a faculty, no course will show at all in the faculty. This is working: <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if courses.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ courses.previous_page_number }}">{{ courses.previous_page_number }}</a> {% endif %} <span class="current"> Page {{ courses.number }} of {{ courses.paginator.num_pages }} </span> {% if courses.has_next %} <a href="?page={{ courses.next_page_number }}">{{ courses.next_page_number }}</a> <a href="?page={{ courses.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> This is not working: <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} Courses</h3> <ul> {% for department in faculty.department_set.all %} {% for … -
Django channels for relatively large files ~10mb, is it a good idea?
I am trying to set up an infrastructure to upload test result data, part of it should be a django application that should handle the data transfer from a different source (typically txt files around 3 to 10 mb). I am considering both the api and django channels approach, but going through the documentation of django channels I read that it is only good for interoperability and not complex applications. Api seems a safe choice but it might not be as fast as django channels which use websockets. Should django channels be used to transfer files (txt, csv etc) ~10 mb? Does it work well or should I fall back in api choice? -
Get Current Url Without Parameters in Django
I have a url like below: url(r'^board/(?P<pk>\d+)$', board_crud, name='board_update'), I want to get current view 'board' without parameters so that i can redirect to it. I want to redirect to current view(without param) in same view(with param). Thanks in Advance. -
How to apply two different mock.patches to one unit test?
When I'm trying to run this test: from unittest import mock @mock.patch('requests.get', side_effect=mocked_requests_get) @mock.patch('requests.post', side_effect=mocked_requests_post) def test_zeros(self, response): self.assertEqual(0, 0) it says TypeError: test_zeros() takes 2 positional arguments but 3 were given. So, how can I mock two different methods (I need requests.get and requests.post) in one test? -
Django restrict access to TemplateView
I'm using TemplateView to display swagger pages (local files). However, now I need to restrict access. Using a normal view, I could use @login_required mixin on the view. Is there a way to do that with TemplateViews? Or should I be using some other way of displaying these swagger pages? url(r'^swagger/', TemplateView.as_view(template_name='swagger.html'), name='swagger'), -
Django post-office: unable to open email attachement
I've written a django view that loads a number of PDF files and combines them into a .zipfile. I dont want to save the object on the server, so I am using StringIO() This is done with the following code: zip_buffer = StringIO.StringIO() summary_filename = 'summary' + str(user) + '.pdf' with zipfile.ZipFile(zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED) as zf: for file in attachements: zf.write(str(settings.MEDIA_ROOT) + '/' + str(file[0].file), file[1] + '.' + str(file[0].file).split('.')[-1]) zf.writestr(summary_filename, pdf) When I was debugging the code I had it return the object as a download in the browser through the following code response = HttpResponse(zip_buffer.getvalue(), 'application/x-zip-compressed') return response This all works as intended, when I click the button a .zip file is downloaded by the browser that contains all of the information. The problems started when I wanted to email the file as well. I am using Django post-office And intitally tried sending the email with the following command: attachment_file = zip_buffer.getvalue() send_email([requester.email], email_template context, attachments={'summary.pdf': attachment_file}) The attachement file is exactly the same as the one I supplied to the browser, yet this causes the following exception: file() argument 1 must be encoded string without NULL bytes, not str I then tried something different: send_email([requester.email], 'userprofile_summary', requester.profile.tenant, … -
Create multiple Django model instances using for loop
I have three Django models namely User, Project and Hourly. User model: which represents a standard Django user, which can start a new project. Project model: Represents a project, containing project specifc constants such as Time Zone, site latitude, site longitude, etc… Hourly model: Which represents all the hourly values (clock-time, solar time, solar hour angle, etc…) for a certain project. To simplify the problem the Hourly model has only two fields, namely project and clock_time. Eventually I would like to use fields to store these to the database. In addition I override the Project.objects.create(….) method using the ProjectManager() class. The meaning of this is that I would like to generate 8760 new hourly instances whenever a new project is created. How to implement this? At the moment every time only one Hourly object is created, whener Projects.object.create() is called. The Project and Hourly models and the ProjectManager are defined as follows: User = settings.AUTH_USER_MODEL class ProjectManager(models.Manager): """""" def create(self, owner, project_name, TMZ, lat, lon): project = super().create(owner=owner, project_name="CREATED BY PROJECTMANAGER", TMZ=TMZ, lat=lat, lon=lon) project.save() # Next I would like to delete all existing Hourly objects tied to this project hourly = Hourly.objects.filter(project=project) hourly.delete() # Next I would like to … -
Django formset , queries for relational field for every form
Models.py class Material(BaseModelClass): material = models.CharField(max_length=25, verbose_name='Material') def __str__(self): return self.material class PurOrder(BaseModelClass): order_number = models.CharField(max_length=25) class PurOrderItem(BaseModelClass): order = models.ForeignKey(PurOrder, on_delete=models.CASCADE) material = models.ForeignKey(Material, on_delete=models.PROTECT) I created a PurOrder form and PurOrderItem formset PurOrderForm = modelform_factory(PurOrder, fields=('order_number',)) PurOrderFormset = inlineformset_factory(PurOrder, PurOrderItem,fields=('material',)) Initialized them as follows. form = PurOrderForm(instance=order_instance) queryset = order_instance.purorderitem_set.all().select_related('material',) formset = PurOrderFormset(instance=order_instance, queryset=queryset) This setup costs me 22 queries if there is 20 PurOrderItem for selected purorder. 1 for PurOrder instance, 1 for PurOrderItem instance 20 for selected materials for those PurOrderItem's. Think of it, it there is 1000 PurOrderItem With the provided select_related, it add's material to PurOrderItemselect, but when it comes to display it I think, it query again. I use django-autocomplete-light, so it saves me from quering all material instances, but it keeps quering selected material, to display it even though I select_related material. Ideally, I would select PurOrder instance with prefetched purorderitem and related materials, these means 3 queries. Prefetched purorderitem's and material's will be used, when it's their turn. Please advice me a way to avoid selected choices query. Note: Caching is not an option, if possible. -
Show and Edit M2M filelds in both Admin Panel Models (django-select2)
I have some problem with ModelSelect2MultipleWidget when I set him for custom field. models.py class Product(GenerateUniuqSlugMixin, BaseAbstractModel): name = models.CharField( verbose_name='Имя', max_length=255 ) slug = models.SlugField( verbose_name='Url', max_length=100 ) description = models.TextField( verbose_name='Описание', blank=True ) price = models.ManyToManyField( 'Price', verbose_name='Цена', blank=True, related_name='products' ) class Price(BaseAbstractModel): code = models.CharField( verbose_name='Уникальный Код', max_length=100, unique=True, db_index=True ) price = models.DecimalField( verbose_name='Цена', max_digits=16, decimal_places=2 ) creation_date = models.DateField( verbose_name='Дата добавления', auto_now_add=True ) update_date = models.DateField( verbose_name='Дата обновления', auto_now=True ) I want have opportunity for searching and connecting products from Price Admin Panel. And I added for forms next code: class PriceAdminForm(forms.ModelForm): products = forms.ModelMultipleChoiceField( queryset=Product.objects.all(), widget=ModelSelect2MultipleWidget( model=Product, queryset=Product.objects.all(), search_fields=['name__icontains'], attrs={'data-placeholder': 'Поиск в товарах', 'data-width': '50em'} ), required=False ) class Meta: model = Price fields = ( 'code', 'name', 'price', 'products', ) But it's not working and I don't know why, where my mistake? If I remove ModelSelect2MultipleWidget from widget attr I see default choice field, but he don't remeber my save choice he just show all queryset. It will be great if I can see input field which offer ModelSelect2MultipleWidget. Thank's. My environment: Django==2.0.2 django-select2==6.0.1 -
Django: Include template with variables rendered from views.py into another template
I have a template plot.html inside app plot: <div> {{ plot|safe }} </div> some other divs here The plot variable is calculated from views.py inside app plot: class RenderView(TemplateView): def __init__(self): self.template_name = "plot.html" def get_context_data(self, **kwargs): context = super(RenderView, self).get_context_data(**kwargs) context['plot'] = PlotView().make_plot() return context Now I want to include this template with the generated plot and other divs into another template from another app, another.html: {% include "plot.html" %} of course this does not generate the plot and other info from the views.py file. I've been reading about template tags (https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/), but I'm unsure what goes into poll_extras.py there or if tags is the right solution. -
automatically changing model field in Django
Consider a Blog model as below: class Blog(models.Model): text = ... stage = ... # ChoiceField Blog.stage describes the current stage the blog is in which can take many values like edit, content verification, tag etc. Transition from one stage to another is based on a condition. In content verification stage, a user verifies the content of the model and corresponding entries are recorded in the following model. class ContentVerificationModel(models.Model): user = ... #verifier blog = ... # blog being verified do_you_verify_blog_content = ... # BooleanField To move from content_verification_stage to next stage, say, edit stage, following conditions must be satisfied: Blog must be verified by some minimum number of people (Say, 10) Percentage of people who voted for the blog must be greater than some minimum value (say, 60 i.e. 6 out 10 entries for a blog must have do_you_verify_blog_content value as True) How do I manipulate my code so that a model field can be changed automatically when some conditions are met? -
Prevent/allow a hyperlink click conditionally through Ajax in Django
I'm trying to implement a hyperlink on a page which when clicked, will submit through ajax first, run a couple checks determining whether or not the user has the authority to visit the hyperlink-page, and then either allow them to go through or prevent the hyperlink's default action(and raise errors). I've set up the code, and the ajax request will go through, but will not be handled server-side. Here is the template code: <a class='btn btn-primary pairing-CTA-btn' href="{% url 'profile:request' object.user %}">Send {{object.user | upper}} a Request</a> The js: $(document).ready(function(){ var $myButton = $('.pairing-CTA-btn') $myButton.click(function(event){ var $buttonData = $(this).serialize() var $endpoint = $myButton.attr('data-url') || window.location.href // or set your own url $.ajax({ method: "GET", url: $endpoint, data: $buttonData, success: handleSuccess, error: handleError, }) }) function handleSuccess(data, textStatus, jqXHR){ // No need to do anything here. Allow link click. console.log(data) console.log(textStatus) console.log(jqXHR) } function handleError(jqXHR, textStatus, errorThrown){ // on error, prevent default, bring up errors event.preventDefault() // $('.pairing-CTA-btn-errors').text("YOU SHALL NOT CLICK BUTTON"); // $('.pairing-CTA-btn-errors').show(); console.log(jqXHR) console.log(textStatus) console.log(errorThrown) } }) The View where this link exists: class ProfileDetailView(AjaxRequestButtonMixin, DetailView): template_name = 'user_profile/profile_detail.html' And the ajax mixin referenced above: class AjaxRequestButtonMixin(object): def button_allowed(self): print("AJAX") # response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): # PERMISSION-TO-CLICK-LINK … -
Run Angular App, Django Backend and MySql on separate servers
We are trying to build a system with Angular as frontend, Django as backend and MySql as database. We want all three to run on separate servers (standalone angular app and django back end). Have gone through various blogs/docs/questions-answers on internet but have not found similar setup. Our question basically is if we develop separate angular app and django back end the How Angular App will communicate with Django Backend (how routing would be done? or simply by using DRF rest services?) and How Django would communicate to MySql. If someone could point to few examples? -
Django Form submissions - from source code
Hello I'm using the plugin FORMS in Dajngo. In admin panel I have access to Form submissions. I need get access to Form submissions from the source code, like: fs = FormSubmissions.objects.all() I can't find information how can I do it. Thank you for help. -
How to dynamically assign values to a Django model from a dictionary? [duplicate]
This question already has an answer here: How do you programmatically set an attribute? 3 answers I have following attributes for a Django model: charfields = [ 'title','author','rating' ] for f in charfields: locals()[f] = models.CharField(max_length=30, blank=True) I want to assign the values from item in the following function: def process_item(self, item, spider): post = Post() for f in post.charfields: setattr(post, str(f), str(item[f])) print(post.author) #this works print(post) #this prints none .. post.save() -
Django many-to-many serialization
I want to create a model (Source) with many-to-many relation to the another model (Tag) and create a Source objects without duplicating Tag instance in database. Here is my models: class Tag(models.Model): name = models.CharField(max_length=50, null=False, default='source') def __unicode__(self): return self.name class Source(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) language = models.CharField(max_length=50) color = models.CharField(max_length=50, default='white') isFile = models.BooleanField(default=False) link = models.TextField(default='') file = models.FileField(upload_to='uploads/', null=True) tags = models.ManyToManyField('Tag') class Meta: ordering = ('title',) Here is my serializers: class TagSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Tag fields = ('name',) class SourceSerializers(serializers.ModelSerializer): tags = TagSerializers(many=True) class Meta: model = Source fields = ('title', 'author', 'language', 'color', 'isFile', 'link', 'file', 'tags') def create(self, validated_data): tags_data = validated_data.pop('tags') source = Source.objects.create(**validated_data) for tag in tags_data: t = Tag.objects.create() t.name = tag.get("name") t.save() source.tags.add(t) source.save() return source But when I try to create Source object via http request - the object is created, but without any references to Tags. After some researching I found that validated_data in create(self, validated_data) doesn't contains "tags" field, also I found that validate function of TagSerializer not invoked at any time. What I'am doing wrong? -
Django REST FrameWork JWT does not allow to provide data or decode itself
I have these endpoints: urlpatterns += [ path('api-token-auth/', obtain_jwt_token), path('api-token-verify/', verify_jwt_token), path('api-token-refresh/', refresh_jwt_token), path('api/', include(router.urls)), ] For example I have a User on backend, and let's say hey wants to login to the system. In login page he must provide his username and password, and login page will use "obtain_jwt_token" endpoint, which will automatically check if that user exists or not. If not, backend will return error message, if that User exists and username & password is correct than backend will return a Token, generated by JWT, and that token will live for let's say 1 hour. But the problem is that backend will not return additional data, it will return only Token itself, but not id of that user or something. And that is the problem. Am I understanding something wrong ? All I want is for backend to return not on the Token, but also id of that user. Or to decode the Token, and get id of User from it. -
Django: show OTP verification dialogue right after submitting form in a modal
First website. I am using Django. I am stuck with implementing this functionality. I right now am able to show a signup form in a modal dialogue and also I can save the details to backend. Now I want to add OTP step to the signup process. What I don't know is how do I move to OTP modal for phone number verification without losing user detail form in the modal. After user enters the correct code how do I save the details that were filled up in previous(signup) modal? So it is two steps: 1. Show Signup Modal. 2. Show OTP verification Modal. How to go to step 2 without losing data entered in step 1. Can anyone please give me an example or idea how it is done? Thank you. -
When a django project deploy on Nginx use uwsgi
I deploy my django project on the Nginx server use uwsgi, and it can access the static files,but when I input my domain on the browser,there is '400 Bad Request' -
Django 2 tables one view
I try to make a simple illustration of my question click to view I have a task to make a quiz. I try to solve a problem : Taking items in cycle by "Metrix" model there I get Questions for Quiz It is no way to get data from "User_metrix" model while using {% for item in metrix_list %} cycle by "Metrix" model. My models: from django.db import models from django.conf import settings class Metrix(models.Model): title = models.CharField(max_length=256, verbose_name='Question') metrix_category = models.ForeignKey( 'category', related_name='Question_category', on_delete=models.CASCADE, verbose_name='Category', ) is_published = models.BooleanField(default=False) def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=256, verbose_name='Question_category') is_published = models.BooleanField(default=False) def __str__(self): return self.title class User_metrix(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_metrix", verbose_name='User') metrix = models.ForeignKey('Metrix', on_delete=models.CASCADE, verbose_name='Question') value = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Value') My view: from django.shortcuts import render from django.contrib.auth.decorators import login_required from metrix.models import Metrix, User_metrix @login_required def metrix_view(request, pk=None): metrix_category = { 'pk': 4 } #Get questions by category metrix_list = Metrix.objects.filter(is_published=True, metrix_category__pk=pk) context = { 'metrix_list': metrix_list } return render(request, 'metrix/metrix.html', context) Template: I list the questions in template, by cycle "metrix_list" How to save answers to values and if answers exists return values to template? <!--cycle for metrix--> {% for item in … -
Extend Django Admin UserCreationForm with OneToOneField
I'm trying to extend the django admin UserCreationForm to include a field from another table related on a OneToOneField. This is my related table: class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) supervisor = models.ForeignKey( User, related_name='supervisor', on_delete=models.DO_NOTHING, blank = True, null = True ) And my admin form: from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from django import forms class EmailRequiredMixin(object): def __init__(self, *args, **kwargs): super(EmailRequiredMixin, self).__init__(*args, **kwargs) # make user email field required self.fields['email'].required = True class MyUserCreationForm(EmailRequiredMixin, UserCreationForm): supervisor = forms.Select() class Meta: model = User fields = ['username',] def save(self, commit=True): if not commit: raise NotImplementedError("Can't create User and UserProfile without database save") user = super(MyUserCreationForm, self).save(commit=True) profile = Profile(user=user, supervisor=self.cleaned_data['supervisor']) profile.save() return user, profile class EmailRequiredUserAdmin(UserAdmin): inlines = [ProfileInline, ] list_display = ['username', 'email', 'first_name', 'last_name', 'is_staff', 'get_supervisor', 'get_is_supervisor', 'get_is_project_manager'] form = MyUserChangeForm add_form = MyUserCreationForm add_fieldsets = ((None, {'fields': ('username', 'email', 'password1', 'password2'), 'classes': ('wide',)}),) def get_supervisor(self, instance): return instance.profile.supervisor get_supervisor.short_description = 'Supervisor' def get_is_supervisor(self, instance): return instance.profile.is_supervisor() get_is_supervisor.short_description = 'Is Supervisor' def get_is_project_manager(self, instance): return instance.profile.is_project_manager() get_is_project_manager.short_description = 'Is Project Manager' def get_inline_instances(self, request, obj=None): if not obj: return list() return super(EmailRequiredUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, EmailRequiredUserAdmin) … -
How to write primary key in django 2.0.2
the below code is working only for index page but it's not working for my DetailView. Please help me to fix (Using Django 2.0.2) The below is my class for view: from django.views import generic from .models import Album class IndexView(generic.ListView): template_name = "newboston/index.html" context_object_name = "all_album" def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'newboston/detail.html' The below is my urls.py under my application. from . import views from django.urls import path urlpatterns = [ path('', views.IndexView.as_view(), name='home'), path('<slug:slug>/', views.DetailView.as_view(), name='detail'), ]