Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Template OverRide Issue
I'm currently using Django 2.0.5 for Pycharm-2018.1.2 I recently started working on my first project which basically requires me to work on the admin part of Django. I've managed to get my project working but I'm having issues with overriding the Admin Template for some reason... I've followed a few tutorials and read a few articles on this forum but i still couldn't find out what's going wrong.. Here's what i have in my 'settings.py' import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-r3^d48%3rh7xrecgl9*3r(had#9nz%7nsn$y%h&o$3_ary*q7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'Bugs.apps.BugsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'BugReport.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'BugReport.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } … -
dongo url patterns error
If you think Dongo is wrong, I'd say it's a Django library for working with the Mongo DB I have a problem now In the URL.py, I am looking at the following error: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) File "/usr/local/lib/python3.6/dist-packages/django/conf/urls/static.py", line 21, in static raise ImproperlyConfigured("Empty static prefix not permitted") django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted from django.contrib import admin from django.urls import include from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static ########################################## urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('first_test.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) but this code run truly in Django2 with path if you know how i can fix it tell me i will be thank you have good time :) -
Need help structuring a Django Database with many-to-many relationship
I am setting up a Django Model/Database for an app that is designed to track the usage of a keyword assigned by a user on social media. Contextual information such as the message, date, url, and platform need to be stored for each usage of the keyword. This part is easy enough to accomplish with three models - a User model that contains username, first, last, email, and password and a Keyword model that contains username as a Foreign Key, and a list of the users' keywords. A third model Context would then be linked via the keyword and contain the contextual information for the usage of the keyword. So the relationships would look like: User Keywords Context username---->username keyword---------->Keyword kw_createdate message post_date url platform However, I also want to enter a number of RelatedTerms for each keyword, so for example, if you were tracking the keyword 'python' you could add related terms 'java', 'ruby', and 'c#'. For the related terms all I really need is a count of the number of times they were used in a given time range, but am not against saving their contextual information as it may be useful in the future. What I can't … -
How to create custom registration form using auth_user model and cutom model fields in django
I am new to django, I have custom user model with extra status and title models. So far i done database part, how can i create registration form for cutom user model with foreignkey fields. My models class code: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class Title(models.Model): value = models.CharField(max_length=100, null=True, blank=True) class Meta: db_table = 'title' class Status(models.Model): value = models.CharField(max_length=100, null=True, blank=True) class Meta: db_table = 'status' class User(AbstractUser): filenumber = models.CharField(max_length=9, null=True, blank=True) personalemail = forms.EmailField(required=True) intakeyear = models.IntegerField(null=True, blank=True) title = models.ForeignKey(Title, on_delete=models.CASCADE, null=True, blank=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True) My settings.py: AUTH_USER_MODEL = 'student.User'# changes built-in user model to ours How can i create user registration form fields like First name, Last name, Title, Status, Email, Personalemail, Password, Password confirmation. I added extra fields to user model title and status(foreignkey fields) and filenumber,intakeyear, personalemail My form.py File: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.forms import ModelForm from student.models import User from student.models import Title, Statu class StudentNewRegistrationForm(forms.ModelForm): title = forms.CharField(required=True) intakeyear = forms.IntegerField(required=True) email = forms.EmailField(required=True) personalemail = forms.EmailField(required=True) status = forms.CharField(required=True) def __init__(self, *args, **kwargs): … -
Am i allowed to call a view from another view?
Am I allowed to call a view from another view like this : # ----- APP #1 ----- def view1(request, obj_list=MyModel.objects): # some stuff queryset = obj_list.all() # some stuff return render(request, "myTemplate", locals()) # ----- APP #2 ------ def view2(request): fav_obj = request.user.profile.favorite_objects return view1(request, obj_list=fav_obj) It works well, but I don't know if it's a good way to use the Django views. Thank you for your answers. -
Remove pound symbol from url django
So, I have a standard bootstrap one page site. I am using django as the backend. for each section of the site, I use the html id I give to it to navigate to it from the navbar. the only problem is that I cannot figure out how to clean the pound sign from the url. I still want something like: example.com/contact navigate to the contact section automatically, however, right it looks like: example.com/#contact How do I go about changing this? Is it something I need to add to the django urls.py file? -
Django ModelForm select type form with empty_label not Showing in Django
here my forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = '__all__' labels = {'company': 'Company ', } empty_labels = {'company': 'Select Company ', } class InventoryForm(forms.ModelForm): name = forms.CharField(label='Nama ', max_length=255) employee = forms.ModelChoiceField( label='Employee ', empty_label="Select Employee", to_field_name="id", queryset=Employee.objects.all(), required=False, ) class Meta: model = Inventory fields = '__all__' on my code, both class trying to set empty_label for my select type form. but on EmployeeForm it is not showing. there no empty_label on class Meta?... how should I do if want use class Meta with emply_label like second class. -
How do i give class attribute to the label of checkbox from the django form
In forms.py, aminities = forms.MultipleChoiceField(choices= dicto.aminites_dic.items(), required=False,widget=forms.CheckboxSelectMultiple(attrs= {'name':'list_details[]','class':'amini'})) In the template, {% for check in form.aminities %} {{check}} {% endfor %} -
Django multiple model query latest 3 in total
I have 5 different models....similar structure but seperated due to lots of record so easier management and scalability. I'm not sure if this is possible with django, but i have a div on the website which is called latest....i want to grab the latest 3 records and show it in this div....however having 5 different models its difficult....each have a timestamp field. Is it possible to query something like show latest 3 records in total, but check 5 of these models and display? Usually if it was in one model I could have just easily said show latest x....but separated models makes its complicated. So i don't want to grab latest 3 records from each model....rather 3 in total but just consider from 5 different models and show latest 3 (either through filtering of id of timestamp field) Please kindly let me know if there is a solution. -
abstract has no column named
I use Django2.0.5+Python3.6.I defined two classes: class Person(models.Model): isMale = models.BooleanField(default=True) name = models.CharField(max_length=32) age = models.IntegerField() mail = models.CharField(max_length=64) phone = models.CharField(max_length=32) class Meta: abstract = True def __str(self): return self.name class User(Person): username = models.CharField(max_length=64) password = models.CharField(max_length=64) department = models.CharField(max_length=64) date_joined = models.DateField() class Meta: abstract = False def __str(self): return self.department + "'s " + self.name Then,I run python manage.py makemigrations python manage.py migrate Though sqlmigrate command,I can see: migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('isMale', models.BooleanField(default=True)), ('name', models.CharField(max_length=32)), ('age', models.IntegerField()), ('mail', models.CharField(max_length=64)), ('phone', models.CharField(max_length=32)), ('address', models.CharField(max_length=32)), ('username', models.CharField(max_length=64)), ('password', models.CharField(max_length=64)), ('department', models.CharField(max_length=64)), ('date_joined', models.DateField()), ], options={ 'abstract': False, }, ), class Meta: abstract = True But in the shell,if I run such commands: p = User(username="",password="",department="",isMale=True,name="",age=1,mail="",phone="",date_joined=timezone.now()) p.save() I get this: django.db.utils.OperationalError: table vsoa_user has no column named isMale .But in sqlmigrate command,I can the "isMale" field in the "User". If I delete "abstract=True" from Person ,this error disappear. I have read https://docs.djangoproject.com/en/2.0/topics/db/models/,but that is no use. -
Regarding AWS/SQL and Django
I am working on deploying a Django app via AWS, and I am using an RDS instance (MySQL) to store information. However, when I try to connect, I get an error like, "(1045, "Access denied for user 'wsgi'@'(ip address)' (using password: YES)"). I've been just following the steps on the AWS website to do this, any ideas how I can fix this in my code? Could my requirements.txt be an issue? Thanks! -
Pass Queryset from decorator to function
I have a decorator which does the same query as the function it's attached to. Is there a way to just pass the Queryset from the decorator so I don't have to run the query twice? decorator.py def is_wifi_author(func): def wrapper(request, wifi_id, **kwargs): wifi = get_object_or_404(Wifi, pk=wifi_id) # Queryset # Is this correct? if request.user != wifi.author: return redirect('youshallnotpass') return func(request, wifi_id, **kwargs) return wrapper views.py @is_wifi_author def edit(request, wifi_id): # print(request) wifi = get_object_or_404(Wifi, pk=wifi_id) # Same queryset # The rest of the view return render(request, 'app/template.html') Yes, just checking if the user has access to edit the post. Any comments welcome. -
Django: New Data from Database won't show in a URL redirect until I click the link again
My problem is that when the user creates a new record on the database in my webpage (Mysql) and the system redirects the user to the list of elements created, the new element won't show up until I click again the link option on a section. In other words I want django to show the new results when I redirect the user to the list, here's some fragments of code I'm using: This is the link where the user clicks to show the list after creating a new object: <div class="modal-footer"> <div class="col-lg-12 text-right"> <a href="{% url 'microsite:myportal_list' device_serial=device_object.network_id %}" class="btn btn-default">Regresar a Listado</a> </div> </div> This is the list where I show the elements from the database: {% for portal in portal_list %} <section class="search-result-item"> <a class="image-link" href="/microsite/myportal/view/{{portal.portal_id}}"> <img class="image" src="{% static 'img/template-icon.png' %}"> </a> <div class="search-result-item-body"> <div class="row"> <div class="col-sm-9"> <h4 class="search-result-item-heading"> <a href="/microsite/myportal/view/{{portal.portal_id}}">No. de Plantilla : {{portal.portal_id}} </a> </h4> <p class="description"> ID Terminos: {{portal.terms_id}} </p> </div> <div class="col-sm-3 text-align-center"> <p class="value3 text-gray-dark mt-sm"> {{ randomNumber|random }} visitas </p> <p class="fs-mini text-muted"> Por Semana </p> <br> <a href="/microsite/myportal/view/{{portal.portal_id}}" class="btn btn-primary btn-info btn-sm">Ver Detalles</a> </div> </div> </div> </section> {% endfor %} Here's my function in views: (The object that … -
Django error "The included URLconf does not appear to have any patterns in it"
I'm trying to write a mixin for a view, SearchFilterMixin, which has a cookie_path class variable: class SearchFilterMixin(FilterMixin, SearchMixin): # Path to send cookies to. Should be set to the path of the model's ListView # in accordance with our naming convention. cookie_path = '/' def get(self, request, *args, **kwargs): self.query_dict = self.query_dict_from_params_or_cookies(request) return super().get(request, *args, **kwargs) def render_to_response(self, context, **response_kwargs): response = super().render_to_response(context, **response_kwargs) response.set_cookie('filters', self.request.GET.urlencode(), path=self.cookie_path) return response @staticmethod def query_dict_from_params_or_cookies(request): """ If no query parameters are sent with the request, obtain them from a cookie. """ return request.GET or QueryDict(request.COOKIES.get('filters')) In the inheriting view, I'm trying to set cookie_path to a reversed URL, reverse('dashboard:families'): from dashboard.views.base import ( DashboardAccessMixin, OrderingMixin, SearchMixin, FilterMixin, HistoryView, SearchFilterMixin ) class ListBase(DashboardAccessMixin, OrderingMixin, SearchFilterMixin): cookie_path = reverse('dashboard:families') However, when I try this, my development server crashes with the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf 'lucy.urls' 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. Here is the full traceback: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1124100d0> Traceback (most recent call last): File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in url_patterns iter(patterns) … -
How to config the Nginx, then it can provide the Django's media resources?
How to config the Nginx, then it can provide the Django's media resources? In my remote CentOS-7 Server after I distributed my Django project, I can not access the media and static resources by my API. How can I config the Nginx, so I can access them? I tried in nginx's vhosts_backend.conf, but did not success. server { listen 8000; server_name 103.20.12.76; access_log /data/ldl/logs/103.20.12.76.access.log main; location / { root /var/www/html/website/backend/; index index.html index.htm; } location ~ /media/*\.(jpg|png|jpeg|bmp|gif|swf)$ { access_log off; expires 30d; root /var/www/html/python_backend/myProject; break; } location /media/ { root /data/ldl/repo/myProject/; } location /static/ { root /data/ldl/repo/myProject/; } } -
Ordering a list with 3 model objects
I've got 3 queryset's: Post, Two and AdvertisePost. The way it currently works is: my site is paginated to have 14 objects on every page. Of those 14 objects it is ordered like this: 1. Post 2. Post 3. Post 4. Post 5. Two 6. Post 7. Post 8. Post 9. Post 10.Two 11.Post 12.Post 13.Post 14.Post But I would now like to have an AdvertisePost on the 12th slot of every page. Not to replace the Post on the 12th slot, but to push it down. But not to push it down so that it ruins the formation of the next page. Here's my current code: two_list = [] returned_list = [] two = Two.objects.all() for i in two: two_list.append(i) ads = AdvertisePost.objects.all() posts = Post.objects.all() for n, post in enumerate(posts): returned_list.append(post) if len(two_list) > 0 and (n + 1) % 4 == 0 and len(returned_list) % 14 != 0: returned_list.append(two_list.pop(0)) paginator = Paginator(returned_list, 14) page = request.GET.get('page') try: lst = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. lst = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. lst = paginator.page(paginator.num_pages) Any idea how … -
How do I set a specific value for an attribute of a model every time I save it on Django?
I have a legacy project that saves models with save, bulk_create and other methods within the framework. What is the best way to set a specific value for an attribute so that every time a record is saved the new value is set and saved? I pose this question because I'm not sure all ways that save is possible in Django except save and bulk_create and knowing that on bulk_create: The model’s save() method will not be called, and the pre_save and post_save signals will not be sent. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#bulk-create -
if the `settings.py`'s `DEBUG=False` what functions will be changed?
In my Django project, if I set the settings.py DEBUG=False, and run python3 manage.py runserver 0.0.0.0:8000. Whether I can not access the static and media file? after set DEBUG=False what functions will be changed? -
error using mod_wsgi with apache2
I am trying to get mod_wsgi running. endusers get error. but I can log into the python command line and load the wsgi core libraries just fine. [Fri May 11 22:37:03.890727 2018] [wsgi:error] [pid 2238] [remote 73.135.97.117:36816] mod_wsgi (pid=2238): Target WSGI script '/home/robin/www/trader/trader/wsgi.py' cannot be loaded as Python module. [Fri May 11 22:37:03.890783 2018] [wsgi:error] [pid 2238] [remote 73.135.97.117:36816] mod_wsgi (pid=2238): Exception occurred processing WSGI script '/home/robin/www/trader/trader/wsgi.py'. [Fri May 11 22:37:03.890808 2018] [wsgi:error] [pid 2238] [remote 73.135.97.117:36816] Traceback (most recent call last): [Fri May 11 22:37:03.890832 2018] [wsgi:error] [pid 2238] [remote 73.135.97.117:36816] File "/home/robin/www/trader/trader/wsgi.py", line 12, in <module> [Fri May 11 22:37:03.890865 2018] [wsgi:error] [pid 2238] [remote 73.135.97.117:36816] from django.core.wsgi import get_wsgi_application [Fri May 11 22:37:03.890884 2018] [wsgi:error] [pid 2238] [remote 73.135.97.117:36816] ImportError: No module named django.core.wsgi root@localhost:/home/robin/www/trader# cat /etc/apache2/mods-enabled/wsgi.load LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so root@localhost:/home/robin/www/trader# cat /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> <VirtualHost *:80> ServerName coinz.com ServerAdmin webmaster@coinz.com DocumentRoot /home/robin/www/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIDaemonProcess trader python-path=/home/robin/www/trader/:/usr/lib/python3/dist-packages/ WSGIProcessGroup trader WSGIScriptAlias / /home/robin/www/trader/trader/wsgi.py <Directory /home/robin/www/trader/> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> root@localhost:/home/robin/www/trader# python3 Python 3.6.5 (default, Apr 1 2018, 05:46:30) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more … -
Django graphos Vertical Lines
How can I draw vertical lines in graphos django I try like this, but it's not working chart = LineChart(data_source, options={ { "vline": "true", "label": "Weekend Start", "linePosition": "0.7" } }) -
Python Django Templates Dictionaries
i need to Print a table in my template of a data that a already Processed in my View. It is in a collections.OrderedDict() variable as: table_dict[position] = {'date': item['date'], 'document': item['document'], 'details': item['details'], 'quantity_balance': quantity_balance, 'unit_price_balance': unit_price_balance, 'total_price_balance': total_price_balance, 'quantity_buy': 0, 'unit_price_buy': 0, 'total_price_buy': 0, 'quantity_sell': 0, 'unit_price_sell_avrg': 0, 'total_price_sell_avrg': 0, 'unit_price_sell': 0, 'total_price_sell': 0, 'earn_total_sell': 0} I has more than one positions, here is an example of the console print of Python: {'total_price_sell_avrg': 0, 'quantity_balance': Decimal('1.000000000000000000'), 'date': datetime.date(2018, 5, 10), 'document': '9d4f8661', 'unit_price_sell_avrg': 0, 'total_price_sell': 0, 'total_price_balan e': Decimal('2400000.000000000000000000000'), 'quantity_sell': 0, 'unit_price_buy': 0, 'details': 'Initial Investment', 'quantity_buy': 0, 'earn_total_sell': 0, 'unit_price_balance': Decimal('2400000.0000000000 0000000'), 'total_price_buy': 0, 'unit_price_sell': 0} {'total_price_sell_avrg': 0, 'quantity_balance': Decimal('1.500000000000000000'), 'date': datetime.date(2018, 5, 10), 'document': '09asdashd', 'unit_price_sell_avrg': 0, 'total_price_sell': 0, 'total_price_bala ce': Decimal('3750000.000000000000000000000'), 'quantity_sell': 0, 'unit_price_buy': Decimal('2700000.000000000000000000'), 'details': '08a7sd80a7doiadsiaud0a87ds', 'quantity_buy': Decimal('0.500000000000000000 ), 'earn_total_sell': 0, 'unit_price_balance': Decimal('2500000.000'), 'total_price_buy': Decimal('1350000.000000000000000000000'), 'unit_price_sell': 0} Now i have and Ordered table where i want to print it put in my html template, that has basically this structure: <table class="tablerow"> <tr> <th colspan="4"></th> <th colspan="3">Buys</th > <th colspan="3">Sells</th> <th colspan="3">Total</th> </tr> <tr> <th >Num T</th> <th >Date</th> <th >Document number</th> <th >Type Operation</th> <th >Details</th> <th >Quantity</th> <th >Unit Price</th> <th >Total Price</th> … -
Same hypothesis test for different django models
I want to use hypothesis to test a tool we've written to create avro schema from Django models. Writing tests for a single model is simple enough using the django extra: from avro.io import AvroTypeException from hypothesis import given from hypothesis.extra.django.models import models as hypothetical from my_code import models @given(hypothetical(models.Foo)) def test_amodel_schema(self, amodel): """Test a model through avro_utils.AvroSchema""" # Get the already-created schema for the current model: schema = (s for m, s in SCHEMA if m == amodel.model_name) for schemata in schema: error = None try: schemata.add_django_object(amodel) except AvroTypeException as error: pass assert error is None ...but if I were to write tests for every model that can be avro-schema-ified they would be exactly the same except for the argument to the given decorator. I can get all the models I'm interested in testing with ContentTypeCache.list_models() that returns a dictionary of schema_name: model (yes, I know, it's not a list). But how can I generate code like for schema_name, model in ContentTypeCache.list_models().items(): @given(hypothetical(model)) def test_this_schema(self, amodel): # Same logic as above I've considered basically dynamically generating each test method and directly attaching it to globals, but that sounds awfully hard to understand later. How can I write the same … -
Signals and django channels chat room
Hi i'm struggling with getting two things working simultaneously... The channels2 chat room example was okay to get going, but i wanted to add a feature of knowing how many people where in the room. I did this by updating a model of the rooms. Then I wanted to have a dashboard which would show the most popular current rooms, which again i wanted to update with using channels. I used the django signals method and this method worked for updating the model whilst nobody was using the chat. However, when seeing if the dashboard updated when somebody joined the chat there was an error. 2018-05-11 19:19:09,634 - ERROR - server - Exception inside application: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. File "/dev/channels_sk/channels-master/channels/consumer.py", line 54, in __call__ await await_many_dispatch([receive, self.channel_receive], self.dispatch) File "/dev/channels_sk/channels-master/channels/utils.py", line 50, in await_many_dispatch await dispatch(result) File "/dev/channels_sk/channels-master/channels/consumer.py", line 67, in dispatch await handler(message) File "/dev/channels_sk/channels-master/channels/generic/websocket.py", line 173, in websocket_connect await self.connect() File "/dev/channels_sk/tables/consumers.py", line 19, in connect room.save() File "/dev/channels_sk/.env/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/dev/channels_sk/.env/lib/python3.6/site-packages/django/db/models/base.py", line 769, in save_base update_fields=update_fields, raw=raw, using=using, File "/dev/channels_sk/.env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in send for … -
django returning author user name for a post
I have a Post model class Post(models.Model): user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE,default=None) In views.py file I tried to return the posts for the user I am looking at according to a specific filter(everything works fine so far), so: class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): self.y= self.model.objects.filter(user__username__iexact=self.kwargs.get("username")) return self.y.filter(message__icontains="jk") Then I tried to use the user name(author of this post inside my template) so I tried (also this worked) : def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.kwargs.get("username") return context Then I thought of another way to do the (get_context_data method) . I thought it should work but it did not... I don't know why!!! so here is the code that did not work and through me an error: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.y.username return context The error is: 'QuerySet' object has no attribute 'username' So why I am not able to get the username through the model?? I know this is wrong but what is the right way to extract the username for these posts from the model not by using the slug of the url;I mean context["post_user"] = self.kwargs.get("username") Sorry if that was long but I tried to be as clear … -
Django 2 url patterns
Trying to get the correct url path mapped back to my view in Django 2. Everytime I try i get a "not found" path. views.py class LoginView(APIView): authentication_classes = () permission_classes = () @staticmethod def post(request): """ Get user data and API token """ user = get_object_or_404(User, email=request.data.get('email')) user = authenticate(username=user.email, password=request.data.get('password')) if user: serializer = UserSerializerLogin(user) return Response(serializer.data) return Response(status=status.HTTP_400_BAD_REQUEST) main urls.py (snippet) urlpatterns = [ path('', include('apiV1.v1.accounts.urls')), path('admin/', admin.site.urls), ] child urls.py urlpatterns = [ path('login', LoginView.as_view(), name='login'), ]