Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django .annotate with When
I am trying to do a query and get a sum of values based on a conditions. I need all the 'shares" when the 'action' == '+' I have to group by the issues. qs = Trades.objects.all ().filter ( id = id ) .annotate ( d_shrs = Sum ( When ( action = '+', then = 'shares' ) ) ).order_by ( 'issue' ) where am I going wrong? Thanks. -
django views.py avoid duplicate code in views
hello I have crate a simple blog using DJANGO with three class in views.py views.py def blog(request): posts=blog.objects.filter(createddate__lte=timezone.now()).order_by('-createddate') if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'base.html'{'posts':posts}) def blog_details(request,slug): posts=blog..objects.filter(createddate__lte=timezone.now()).order_by('-createddate') pos=get_object_or_404(app_descripts, slug_title=slug) if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'blog_details.html'{'posts':posts,'pos':pos}) def about(request): posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'about.html'{'posts':posts}) in the html I use this way because I have some code: {% extends 'blog/base.html' %} {% block content %} ....................... {% endblock %} In the base.html out of block content I have a simple contaim where I have code for all post ( posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') ). but to view the tthat posts in all pages(blog,blog_details,about) must write this code ( posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate')) in all views to work fine. that happen and for my html contact form because is out of content. how can avoid to execute some code in all views ? -
Django Queryset One to Many list output
I am trying to make the following magic happen: I'm grabbing a HUGE queryset via values, making it into a list, then consuming it by a page. BUT, I want to consume the manys in the one to many relationship (via a parent model) they have with another model, and have them as a list in the list. Is this even a thing? So say I have: # models.py class Game(Odd): type = models.ForeignKey(Type, on_delete=models.PROTECT, null=True, default=1) book = models.ForeignKey(Bookmaker, on_delete=models.PROTECT, null=True, default=23) amount = models.DecimalField(max_digits=10, decimal_places=2, null=True) class TipFromHuman(TimestampModel): tipper = models.ForeignKey(Human, on_delete=models.CASCADE, null=True) odds = models.ForeignKey(Odd, on_delete=models.CASCADE, null=True) tip_against = models.NullBooleanField(default=False) and in a script I'm running: # snippet qs = Game.objects.all().values('id', 'type__name', 'book__name', 'TipFromHuman__tipper__name').distinct() qsList = list(qs) return qs And in the template I can do: {% for q in qsList %} Type {{ q.type__name }} with {{ q.book__name }} from {{ q.TipFromHuman__tipper__name }} {% endfor %} and have it output as: Type Alpha with Green Eggs and Ham from Dr. Seuss, Potatoes, and Green Eggs where there are three associated TipFromHuman records with the tipper names "Dr. Seuss", "Potatoes", and "Green Eggs" Currently, instead of teh desired behavior, I get three different entries in the list … -
Google OAuth with Django
I am following How to sign in with the Google+ API using Django? to use Google Sign In for my Django app. I am on the step that says Add the SOCIAL_AUTH_GOOGLE_OAUTH2_KEY and SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET settings with the client key and secret you created earlier. I am wary of adding these directly to settings.py because they will then be committed to my git repo. How can I make these values available in my app without exposing them unnecessarily? I think environment variables are common for this purpose. I also see that I can download a JSON file from my Google Developer Console. -
Django-tables2 breaking a table after 25 rows for ads
In django-tables2, I have a table loading 50 rows per page but I would like to break the table at every 25 rows into its own table with its own headers so I can insert a script tag to load ads in between and then continue the row counter from the last table. How can I do this using django-tables2? views.py: from .tables import TrackTable def profile_list(request): track_list = Track.objects.all() table = TrackTable(track_list) RequestConfig(request, paginate={"per_page": 50}).configure(table) context = { "track_list": track_list, "table": table, } return render(request, "profile_detail.html", context) profile_detail.html <div id="div-ads"></div> <script data-cfasync='false' type="text/javascript"> /* ad js code */ </script> <div class="row"> <div class="col-xs-12"> {% if track_list %} {% render_table table "django_tables2/bootstrap.html" %} {% else %} <p>No records found</p> {% endif %} </div> bootstrap.html {% load querystring from django_tables2 %} {% load trans blocktrans from i18n %} {% load bootstrap3 %} {% if table.page %} <div class="table-responsive"> {% endif %} {% block table %} <table{% if table.attrs %} {{ table.attrs.as_html }}{% endif %}> {% block table.thead %} <thead> <tr> {% for column in table.columns %} {% if column.orderable %} <th {{ column.attrs.th.as_html }}><a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}">{{ column.header }}</a></th> {% else %} <th {{ column.attrs.th.as_html }}>{{ column.header }}</th> {% endif … -
Django api call in view unable to save for foreign key userId
I am trying to save the data from api call to an api using view. Everything else works but however, the foreign key to user model userId give me this error : ValueError: Cannot assign "4": "BookAppt.patientId" must be a "MyUser" instance. I don't know what is the problem as i did say same post with the same value to that BookAppt table API and it works normally. But when saving using the API call, it gave me this error. And also, is there a way to take the date(datefield) and time(timefield) from Appointment table and save it into scheduleTime(datetimefield) ? Here is my code: Do note that im combining all the code so that is it easier for you guys to see. Appointments is in django project 2 and BookAppt is in django project 1. model class Appointments (models.Model): patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) clinicId = models.CharField(max_length=10) date = models.DateField() time = models.TimeField() created = models.DateTimeField(auto_now_add=True) ticketNo = models.IntegerField() STATUS_CHOICES = ( ("Booked", "Booked"), ("Done", "Done"), ("Cancelled", "Cancelled"), ) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="Booked") class BookAppt(models.Model): clinicId = models.CharField(max_length=20) patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) scheduleTime = models.DateTimeField() ticketNo = models.CharField(max_length=5) status = models.CharField(max_length=20) serializer class AppointmentsSerializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M … -
Django ModelForm not Saving to Database
I am new to Django. I am trying to save a form to Database. It doesn't show any error but just won't save it to the DB. Any help would be much appreciated! Here is my code: models.py class Estate(models.Model): type = models.CharField(max_length=100) net_area = models.CharField(max_length=10) total_area = models.CharField(max_length=10) price = models.CharField(max_length=10) cep = models.CharField(max_length=8) state = models.CharField(max_length=30) city = models.CharField(max_length=30) neighborhood = models.CharField(max_length=30) street = models.CharField(max_length=250) number = models.CharField(max_length=10) complement = models.CharField(max_length=100) rooms = models.CharField(max_length=3) suits = models.CharField(max_length=3) parking_spots = models.CharField(max_length=3) bathrooms = models.CharField(max_length=3) description = models.CharField(max_length=1000) logo = models.FileField() def get_absolute_url(self): return reverse('register:create2') def __str__(self): return self.type + ' ' + self.neighborhood views.py class CreateView1 (TemplateView): template_name = 'register/estate_form1.html' def get(self, request): form1 = AddForm() return render(request, self.template_name, {'form1': form1}) def post(self, request): form1 = AddForm(request.POST) text = None if form1.is_valid(): text = form1.cleaned_data() form1.save() args = {'form1': form1, 'text':text} return render(request, self.template_name, args) forms.py class AddForm(forms.ModelForm): class Meta: model = Estate fields = ('type','net_area','total -
How do I get the user's email after signing up with Django All Auth?
I have a django project that uses django all auth for signing up users. After the user enters username, email and password, a confirmatiion emal is sent and it redirects to a page displaying that they should check their inbox for the link. I want in that page, before clicking the link, to display the email that the user has used to sign up. -
Why my form doesn't return all the errors?
My form.py: class PostForm(forms.ModelForm): title_it = forms.CharField(label='Titolo (it)', widget=forms.TextInput()) title_en = forms.CharField(label='Title (en)', widget=forms.TextInput()) text_it = forms.CharField(label='Testo (it)', widget=forms.Textarea(attrs={'rows':"20", 'cols':"100"})) text_en = forms.CharField(label='Text (en)', widget=forms.Textarea(attrs={'rows':"20", 'cols':"100"})) views = forms.IntegerField(widget=forms.HiddenInput(), initial=1) class Meta: model = Post fields = ('title_it', 'title_en', 'text_it', 'text_en', 'tags', 'views') My models.py: class Post(models.Model): title = MultilingualCharField(_('titolo'), max_length=64) text = MultilingualTextField(_('testo')) ... MultilingualCharField and MultilingualCharField are about the same: class MultilingualCharField(models.CharField): def __init__(self, verbose_name=None, **kwargs): self._blank = kwargs.get("blank", False) self._editable = kwargs.get("editable", True) #super(MultilingualCharField, self).__init__(verbose_name, **kwargs) super().__init__(verbose_name, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): # generate language specific fields dynamically if not cls._meta.abstract: for lang_code, lang_name in settings.LANGUAGES: if lang_code == settings.LANGUAGE_CODE: _blank = self._blank else: _blank = True rel_to = None if hasattr(self, 'rel'): rel_to = self.rel.to if self.rel else None elif hasattr(self, 'remote_field'): rel_to = self.remote_field.model if self.remote_field else None localized_field = models.CharField(string_concat( self.verbose_name, " (%s)" % lang_code), name=self.name, primary_key=self.primary_key, max_length=self.max_length, unique=self.unique, blank=_blank, null=False, # we ignore the null argument! db_index=self.db_index, #rel=self.rel,#AttributeError con django 2.0 rel=rel_to, default=self.default or "", editable=self._editable, serialize=self.serialize, choices=self.choices, help_text=self.help_text, db_column=None, db_tablespace=self.db_tablespace ) localized_field.contribute_to_class(cls, "%s_%s" % (name, lang_code),) def translated_value(self): language = get_language() val = self.__dict__["%s_%s" % (name, language)] if not val: val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)] return val setattr(cls, name, property(translated_value)) … -
Unable to import Django model from the other app during migration roll-back
I'm creating a data-migration for the new_app with the possibility to roll it back. # This is `new_app` migration class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(import_data, reverse_code=delete_data) ] This migration adds some data to the model defined in other app: my_other_app. To import the model where I want to update or delete records I use apps.get_model() method. # This is `new_app` migration def import_data(apps, schema_editor): model = apps.get_model('my_other_app', 'MyModel') It works like charm when I apply migrations. But when I run try to roll back the migration with the :~> manage.py migrate new_app zero I get exception: LookupError: No installed app with label 'my_other_app'. Model import in roll back code: # This is `new_app` migration def delete_data(apps, schema_editor): schema_model = apps.get_model('my_other_app', 'MyModel') The code for model import is identical, but why it doesn't work during migration roll back? For now I have a workaround with straight model import during roll-back. Don't know if it may cause troubles in future. -
Django REST Framework: nested serializer not properly validating data
I'm new to DRF (and Django) and trying to create a nested serializer which is able to validate the following request data: { "code": "12345", "city": { "name": "atlanta", "state": "Georgia" }, "subregion": { "name": "otp north" } } To simplify things for the client, I'd like this single request to create multiple records in the database: A City (if a matching one doesn't already exist) A Subregion (if a matching one doesn't already exist) A CodeLog which references a city and (optionally) a subregion Models: class City(models.Model): name = models.CharField(max_length=75, unique=True) state = models.CharField(max_length=50, blank=True) class Subregion(models.Model): city = models.ForeignKey(City) name = models.CharField(max_length=75) class CodeLog(models.Model): code = models.CharField(max_length=10) city = models.ForeignKey(City) subregion = models.ForeignKey(Subregion, blank=True, null=True) Serializers: class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('name', 'state') class SubregionSerializer(serializers.ModelSerializer): class Meta: model = Subregion fields = ('name',) class CodeLogSerializer(serializers.ModelSerializer): city = CitySerializer() subregion = SubregionSerializer(required=False) class Meta: model = CodeLog fields = ('code', 'city', 'subregion') # This is where I'm having troubles create(self, validated_data): city_data = validated_data.pop('city', None) subregion_data = validated_data.pop('subregion', None) if city_data: city = City.objects.get_or_create(**city_data)[0] subregion = None if subregion_data: subregion = Subregion.objects.get_or_create(**subregion_data)[0] code_log = CodeLog( code=validated_data.get('code'), city=city, subregion=subregion ) code_log.save() return code_log View: class CodeLogList(APIView): … -
Bitrix API on Django
Are there any Bitrix API implementations for the Django REST Framework, do I need several examples, or is the concept itself? How is Bitrix DRF authorization? -
Queryset with values filtered from another queryset
If I have a queryset qs1 like this: <QuerySet [{u'name': u'John', u'birthdate': u'1980-01-01'}, {u'name': u'Larry', u'birthdate': u'1976-12-28'}, .....']} I need to use all values associated with key 'name' from qs1 to query another model and get qs2 like this: <QuerySet [{u'student_name': u'John', u'grade': u'A'}, {u'student_name': u'Larry', u'grade': u'B'}, .....']} After this, I have to combine qs1 and qs2 so the final_qs like this: [{u'name': u'John',u'birthdate': u'1980-01-01', u'grade': u'A'}, {u'student_name': u'Larry', u'birthdate': u'1976-12-28', u'grade': u'B'}, .....']} How would I achieve this? I have code like this: qs1 = Person.objects.values('name', 'birthdate') for t in qs1: qs2 = Grades.objects.filter(student_name=t['name']) .values('student_name', 'grade') My qs1 looks OK. However, my qs2 becomes this: <QuerySet [{u'student_name': u'John', u'grade': u'A'}]> <QuerySet [{u'student_name': u'Larry', u'grade': u'B'}]> Because of qs2, I am not able use zip(qs1, qs2) to construct final_qs the way I want. -
Django Push Notification with Android App
I am working on an Android project where I am using DJANGO as my backend. There are 2 kinds of android app I needed to create.Suppose they are App1 and App2. Now I am sending message from App1 to App2 and vice versa and i also need real time update in both the app for which i am using django push notification.But I am not getting really good examples on how to implement this django as a backend in Firebase cloud messaging between both of my android apps.I am really new to this .Please help me I am really stuck in this from quite a few days and I dont what to do. -
Update field in rendered Django Form
I'm having a hard time figuring out how to update a Field in Django Form while editing the Form. In my form I have a ModelChoiceField and ChoiceField: first is a list of Car manufacturers, second is a list of models available for this manufacturer. Obviously I don't want to fill second field with models for every manufacturer but only for one selected in first ModelChoiceField. Here's my example Form: class PostForm(forms.ModelForm): make = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) model = forms.ChoiceField() ... In my template after I render PostForm I disable model field with jQuery and wait for user to select some value in make field. And then use AJAX to request values for model field (in this sample code I only return single item): $('#id_make').change(function () { $.ajax({ url: '{% url 'get_models' %}', data: {'make': $('#id_make :selected').text()}, dataType: 'json', success: function (data) { $('#id_model').append($('<option>', { value: 1, text: data.model})).removeAttr('disabled'); } }); }) With this done I do see updated options in <select> element for model ChoiceField, but after I select new value in model ChoiceField and submit form I receive: Select a valid choice. 1 is not one of the available choices." '1' is id of the element that I appended to … -
Setting the name of a javascript variable using Django variable
Curious one - how do you set a javascript variable’s name to that of a Django variable? I need something like: var “{{django_variable}}” = I’ve tried this but the script just sees var “” = Any pointers? -
Overriding Django Username Value
I want to make my (Django built-in User class) username field more obfuscated. Is there any downside to this code (testing+working): @receiver(pre_save, sender=User) def presave_user_override_username(sender, instance=None, created=False, **kwargs): #Reference: https://stackoverflow.com/questions/11561722/django-what-is-the-role-of-modelstate if instance._state.adding is True: while True: rstr = random_string_generator(20) # eg. UlBxNgZV04bbLNE5A7Fz if not User.objects.filter(username=rstr).exists(): instance.username = rstr break Users will be created with django-allauth with Social Providers only for now. In the off chance that I decide to allow email sign-up, I can have them login with their e-mail address. Right? Any foreseeable issues or better approaches? -
Python - Django 2.0 - URL patterns, passing arguments
First of all I am completely new to web development and Python, however I am enjoying the language. I am writing a very basic web page which has a text box where a user can type in a username, then hit the Ok button which submits a form using a GET request. The GET passes the username as an argument and searches the auth_user table in the database. My problem is I am not able to pass the username argument, please help if you can Django 2.0 url patterns urls.py app_name = 'just_gains' urlpatterns = [ path('lifecoaching', views.LifeCoach, name='life_coaching'), path('lifecoaching/resultslifecoaching/<user_name>', views.LifeCoachSearchResults, name='results_life_coaching'), ] forms.py class LifeCoachSearch(forms.Form): user_name = forms.CharField(label='Username', max_length=100, required = False) views.py def LifeCoach(request): if request == 'GET': form = LifeCoachSearch(request.GET) if form.is_valid: user_name = form.cleaned_data['user_name'] LifeCoachSearchResults(request,user_name) else: form = LifeCoachSearch() return render(request, 'just_gains/life_coaching.html', {'form': form}) def LifeCoachSearchResults(request, user_name): testUser = User.objects.filter(username__startswith=user_name) context = {'TestUser': testUser} return render(request, 'just_gains/results_life_coaching.html', context) HTML (lifecoaching) <form action="{% url 'just_gains:results_life_coaching' %}" method="GET" > {% csrf_token %} {{ form }} <input type="submit" value="OK"> </form> HTML (resultslifecoaching) <ul> <li><a>print usernames that match the argument</a></li> </ul> Thanks -
django REST urls.py does not resolve endpoint
Noob here. I am using https://github.com/Seedstars/django-react-redux-base which is great and straight forward Django REST + React.js starter project. This is Django 1.11. My problem is with the Django REST backend not resolving the API endpoints correctly. I have added an application profiles that should return a user profile when queried by: /api/v1/profiles/getprofile/(some_name) Here is my top-level urls.py: from django.conf import settings from django.conf.urls import include, url from django.views.decorators.cache import cache_page from base import views as base_views urlpatterns = [ url(r'^api/v1/accounts/', include('accounts.urls', namespace='accounts')), url(r'^api/v1/getdata/', include('base.urls', namespace='base')), url(r'^api/v1/profiles/', include('profiles.urls', namespace='profiles')), url(r'', cache_page(settings.PAGE_CACHE_SECONDS)(base_views.IndexView.as_view()), name='index'), ] My profiles/urls.py: from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from . import views urlpatterns = [ url(_(r'^getprofile/(?P<display_name>.*)/$'), views.PublicProfileView.as_view(), name='getprofile'), ] With This setup, when I query http://localhost:8000/api/v1/profiles/getprofile/test, I get the IndexView in the response, basically html containing the frontend. However if I comment out r'' from the top level urls.py I get the expected JSON payload for the 'test' profile that I have in the database. Why would the resolver skip r'^api/v1/profiles/ and resolve straight to r''? Am I doing this wrong? -
Error connecting Django 2.0 with sql server 2014 using python 3.6
I am new in Django and I am trying to connect it with Sql server. As I read there is a third party connector for this. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Program Files\Python36\lib\site-packages\django\db\models\base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Program Files\Python36\lib\site-packages\django\db\models\base.py", line 315, in add_to_class value.contribute_to_class(cls, name) File "C:\Program Files\Python36\lib\site-packages\django\db\models\options.py", line 205, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Program Files\Python36\lib\site-packages\django\db\__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Program Files\Python36\lib\site-packages\django\db\utils.py", line 202, in … -
XML parsing and mathematical addition DJANGO REST
How to read data from xml by URL and fold with the entered number in the field, html forms ? DJANGO REST FRAMEWORK XML: <item> <title>USD</title> <pubDate>29.01.18</pubDate> <description>320.66</description> <--required number <quant>1</quant> <index/> <change>0.00</change> <link/> </item> eg: You enter the number: result = 10 * 320.66 print result //3206.6 P.S. Google Translate. I can explain to you more clearly what I need in Russian. Please help :) -
Django ignores timezone
I am trying to print a range of timestamps which are stored in a table. The timestamps are stored in the following format. 2018-01-28 15:00:00-05:00 2018-01-28 16:00:00-05:00 2018-01-28 17:00:00-05:00 2018-01-28 18:00:00-05:00 2018-01-28 19:00:00-05:00 2018-01-28 20:00:00-05:00 2018-01-28 21:00:00-05:00 2018-01-28 22:00:00-05:00 2018-01-28 23:00:00-05:00 2018-01-29 00:00:00-05:00 2018-01-29 01:00:00-05:00 2018-01-29 02:00:00-05:00 Now I am trying to access the rows that match a range and print the timestamp using the below code. timenow = datetime.datetime.now() forecasts = Forecast.objects.filter(timestamp__range=(timenow,timenow + timedelta(days=1))) for forcast in forecasts: print(forcast.timestamp) Output: 2018-01-28 21:00:00+00:00 2018-01-28 22:00:00+00:00 2018-01-28 23:00:00+00:00 2018-01-29 00:00:00+00:00 2018-01-29 01:00:00+00:00 2018-01-29 02:00:00+00:00 2018-01-29 03:00:00+00:00 2018-01-29 04:00:00+00:00 2018-01-29 05:00:00+00:00 2018-01-29 06:00:00+00:00 2018-01-29 07:00:00+00:00 However, I keep getting the invalid timestamps. I am not sure what is wrong here since I have already set the TIME_ZONE and USE_TZ variables. TIME_ZONE = 'America/Toronto' USE_TZ = True -
How to subclass AbstractUser in Django?
I'm trying to extent my user model. In the Django documentation for extending the user model it says: ... just want to add some additional profile information, you could simply subclass django.contrib.auth.models.AbstractUser I don't have experience in subclassing models. I've set everything up except for subclassing the model to AbstractUser and can't seem to find good documentation on it. Does anyone have experience subclassing AbstractUser? My models.py: class AuthKey(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) authkey = models.CharField(max_length=100) My admin.py: class AuthenticationKeyInline(admin.StackedInline): model = AuthenticationKey can_delete = False verbose_name_plural = 'AuthenticationKey' # Defines a new User admin class UserAdmin(BaseUserAdmin): inlines = (AuthenticationKeyInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) -
django: github oauth app always returns 404 not found
I am using this article for social auth with github. Actually I am already using 1 github oauth app, by refering to this article. But this time, I am always getting this, I am using the same config as in the article, Is there any problem with my app? -
I have one questions in Django.. I don't have any logic about that i am learning
I have one list like id name dob 1 xyz 1989-10-31 2 abc 1994-11-29 3 asd 1996- 06 - 28 4 adf 1993 - 05 -06 5 abc 1992 - 07-09 6 tre 1996- 07 -28 I want to show to user like this id name dob year 1 xyz 1989-10-05 2017 2 abc 1992 - 07-09 2017 3 adf 1993 - 05 -06 2017 4 abc 1994-11-29 2017 5 asd 1996- 06 -28 2017 6 tre 1996- 07 -28 **2018** i can give starting year by my self but it show first five user to starting year then next five can see next year means 2018 i want do it continues ......