Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django many-to-many :how to get the id
I have the ManytoMany models are as follows: class Brand(models.Model): Company_Group = models.ManyToManyField(Company) class Company(models.Model): Pref_Company_Name_Flg = models.CharField(u'Preferred Name Flag',max_length=255, default="") Pref_Company_Name = models.CharField(u'Preferred Name',max_length=255, default="") I wanto to filter the id of brands in containing "company_instance" brands = Brand.objects.all() company_instance=company.objects.filter(id =company_id) for brand in brands: for i in Brand.Company_Group.through.objects.filter(Company_Group = brand): print i.id I have found the Similar problem as follows: click here but Report errors : Cannot resolve keyword 'Company_Group' into field. Choices are: brand, brand_id, company, company_id, id then I try this way,also Report errors: type object 'Brand' has no attribute 'Company_id' Thanks andvance -
DJANGO: Sorting sets of sets
I have this models (simplified): #models.py class Expression(models.Model): text = models.CharField(max_length=254) class Country(models.Model): name = models.CharField(max_length=100) class Definition(models.Model): expression = models.ForeignKey(Expression) country = models.ForeignKey(Country) text = models.CharField(max_length=254) class Vote(models.Model): definition = models.ForeignKey(Definition) And this view #views.py def index(request): expressions = Expression.objects.all() return render(request, 'expression_index.html', { 'expressions':expressions) So it will show the last 10 created expressions. Then in the template I have this: #index.html {% for expression in expressions %} {{ expression }} {% for definition in expression.definition_set.all %} <ul> <li>{{ definition }}</li> </ul> {% endfor %} {% endfor %} Every definition has several votes. Every vote is a single row so we can do: definition.votes_set.count() How can I achieve to display them like this: The top definition of every country alphabetically. Each country appears only with one definition. Lets say Germany has two definitions for expression "A" and Denmark has three definitions for the same expression it will show only two definitions: the one with the most votes. I hope I'm making sense. Thanks -
JSON Fields pagination in Django REST framework
I am trying to add pagination in lates Django REST framework, how can I provide pagination inside tracks field because tracks can be more than 1-2 k? { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse' 'tracks': [ {'title': 'Public Service Announcement'}, {'title': 'What More Can I Say'}, {'title': 'Encore'}, ............ 1k ], } -
Django login FieldError - Exception Value: Cannot resolve keyword 'request' into field
I've setup Django + Mezzanine on in a localhost virtual environment. On the admin login page, I input my admin username and password and am returned with a Traceback that I do not understand. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.11.2 Python Version: 3.4.2 Installed Applications: ('mezzanine.boot', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.redirects', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.sitemaps', 'mezzanine.conf', 'mezzanine.core', 'mezzanine.generic', 'mezzanine.pages', 'mezzanine.blog', 'mezzanine.forms', 'mezzanine.galleries', 'mezzanine.twitter', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'mezzanine.core.request.CurrentRequestMiddleware', 'mezzanine.core.middleware.RedirectFallbackMiddleware', 'mezzanine.core.middleware.TemplateForDeviceMiddleware', 'mezzanine.core.middleware.TemplateForHostMiddleware', 'mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware', 'mezzanine.core.middleware.SitePermissionMiddleware', 'mezzanine.pages.middleware.PageMiddleware') Traceback: File "c:\projects\1111\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "c:\projects\1111\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "c:\projects\1111\lib\site-packages\django\core\handlers\base.py" in _get_response 178. response = middleware_method(request, callback, callback_args, callback_kwargs) File "c:\projects\1111\lib\site-packages\mezzanine\core\middleware.py" in process_view 39. response = view_func(request, *view_args, **view_kwargs) File "c:\projects\1111\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "c:\projects\1111\lib\site-packages\django\contrib\admin\sites.py" in login 393. return LoginView.as_view(**defaults)(request) File "c:\projects\1111\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "c:\projects\1111\lib\site-packages\django\utils\decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "c:\projects\1111\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "c:\projects\1111\lib\site-packages\django\utils\decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "c:\projects\1111\lib\site-packages\django\utils\decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "c:\projects\1111\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "c:\projects\1111\lib\site-packages\django\utils\decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) … -
Django Migration Database Column Order
I use Django 1.11, PostgreSQL 9.6 and Django migration tool. I couldn't have found a way to specify the column orders. In the initial migration, changing the ordering of the fields is fine but what about migrations.AddField() calls? AddField calls can also happen for the foreign key additions for the initial migration. Is there any way to specify the ordering or am I just obsessed with the order but I shouldn't be? -
Using S3 Subfolder as Django collectstatic destination
I'm in process launching a Django (1.11.x) project on AWS (ElasticBeanstalk, S3, RDS). With boto3 Django App I managed that my static files push to S3, straight into the bucket. However the S3 bucket has some other files and directories unrelated to static. For that reason I would like to create a Folder within the S3 bucket called static and push all the static files into this specifically designated directory. My settings.py looks like this: [...] # Static files (CSS, JavaScript, Images) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = AWS_S3_MyKEY AWS_SECRET_ACCESS_KEY = AWS_S3_MySECRET AWS_STORAGE_BUCKET_NAME = 'elasticbeanstalk-us-west-2-1xxxxxxxxxxx1' AWS_S3_CUSTOM_DOMAIN = '%s.s3-us-west-2.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_QUERYSTRING_AUTH = False # general static / media settings STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' MEDIA_URL = '%smedia/' % STATIC_URL MEDIA_ROOT = '/static/media/' ADMIN_MEDIA_PREFIX = '%sadmin' % STATIC_URL STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), # ... ] [...] I have some experience with Django, but this is my first project involving AWS and boto. Any help would be appreciated. Thank you in advance. -
Options for private access for a website
What options do I have to put a website on a staging server and to allow the access only to specific people plus several external services, like PayPal IPN, Facebook Connect, Twitter OAuth2, Google OAuth2, etc. Let's say, I have full control of the server with Debian Linux and can install any software necessary or add any configuration. The website is running on Django. -
object not being updated after form_valid
I have a Question and a Reply. When a Reply is created, I want to set the related Question's attribute to new_replies = True. This switch should happen after creating a Reply object using a generic CreateView / a form. I can get the switch to occur for only the logged in user who created the Reply, but the change will not be reflected for any other user. I think this is because the object in the database is not being updated. Models.py class Reply(models.Model): parent_question = models.ForeignKey(Question, null=True) class Question(models.Model): new_replies = models.BooleanField(default=False) Views.py class ReplyCreate(CreateView): """ creates a comment object """ model = Reply #specify which model can be created here fields = ['content', ] # which fields can be openly editted ... def form_valid(self, form): """ add associate blog and author to form. """ #this is setting the author of the form form.instance.author = self.request.user.useredus #associate comment with Question based on passed parent_question = get_object_or_404(Question, pk= self.kwargs['pk']) form.instance.parent_question = parent_question response = super(ReplyCreate, self).form_valid(form) # PROBLEM: not being saved to dB? parent_question.new_replies = True # inform the question there are new replies parent_question.save() return response def get_success_url(self): return reverse('edus:question_detail', kwargs={'pk': self.kwargs['pk'], }) -
How to return status code after getting db validation error in django-rest-framework?
I have a test case that looks like this (the point being to prevent duplicate user profiles): def test_create_duplicate_profile(self): new_user = models.User( username='bobjones', password=';alsdfkj;asoi' ) new_user.save() client = APIClient() client.force_authenticate(new_user) response = client.post( path='/api/profiles/' ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) same_user = models.User.objects.get( username='bobjones' ) response = client.post( path='/api/profiles/' ) self.assertEqual(response.status_code, status.HTTP_409_CONFLICT) client.logout() This results in an error (as well as failing test): (.virtualenv) nbascoutingdotcom $ python manage.py test profiles Creating test database for alias 'default'... System check identified no issues (0 silenced). E.. ====================================================================== ERROR: test_create_duplicate_profile (profiles.tests.test_api.ProfilesAPITest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/evanzamir/nbascoutingdotcom/.virtualenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/Users/evanzamir/nbascoutingdotcom/.virtualenv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: profiles_profile.user_id My model looks like this: class Profile(TimestampModerated): id = models.BigAutoField(primary_key=True, db_column='id', null=False) uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4(), editable=False) user = models.OneToOneField('auth.User', on_delete=models.CASCADE, related_name='profiles', blank=False, unique=True) bio = models.CharField(max_length=140, blank=True, null=True) media_url = models.URLField(blank=True, null=True) dob = models.DateField(blank=True, null=True) class Meta: verbose_name_plural = "profiles" Here is the serializer: class ProfileSerializer(serializers.ModelSerializer): user = serializers.CharField(source='user.username', read_only=True, validators=[UniqueValidator(queryset=Profile.objects.all())]) email = serializers.CharField(source='user.email', read_only=True) first = serializers.CharField(source='user.first_name', read_only=True) last = serializers.CharField(source='user.last_name', read_only=True) last_login = serializers.DateTimeField(source='user.last_login', read_only=True) date_joined = serializers.DateTimeField(source='user.date_joined', read_only=True) class Meta: model = Profile fields = ('id', 'created', 'moderation_code', 'user', 'updated', … -
Swagger Django logout is working locally using both Safari and Chrome but on Heroku is working only with Chrome
Any ideas why Swagger Django logout is working locally using both Safari and Chrome but on Heroku is working only with Chrome? I am not sure what information you need, so give me a feedback what you need and I will add it immediately. At this moment my login settings looks in this way: URL: url(r'^login', views.UserAuthenticationView.as_view()), @permission_classes([CustomPermission]) class UserAuthenticationView(GenericAPIView): serializer_class = UserAuthenticationSerializer def post(self, request, *args, **kwargs): serializer = UserAuthenticationSerializer(data=self.request.data) if serializer.is_valid(): user = serializer.validated_data['user'] return Response({'token': user.auth_token.key, 'id': user.id}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) -
Django template logic: is there a simpler way?
I want to have the following logic in a Django template: If ~A&B, Q However, {% if not A and B %}Q{% endif %} doesn't work, even though according to the docs (especially here) it should be interpreted as {% if not (A and B) %}Q{% endif %}. While {% if not A or not B %}Q{% endif %} works, I want to learn why the other method isn't working. Yes, I could use nested ifs, but even the second method is cleaner than that. Thanks! -
Start uwsgi when outside virtualenv
I am trying to run some Django code using uwsgi. When I am within the right virtualenv, it runs fine. But outside of it, when I run it as follows: uwsgi /home/axial/axial/config.ini I get this error: [uWSGI] getting INI configuration from config.ini *** Starting uWSGI 2.0.15 (64bit) on [Fri Jul 7 23:34:01 2017] *** compiled with version: 4.2.1 Compatible FreeBSD Clang 3.8.0 (tags/RELEASE_380/final 262564) on 29 June 2017 06:51:11 os: FreeBSD-11.1-RC1 FreeBSD 11.1-RC1 #0 r320486: Fri Jun 30 02:25:16 UTC 2017 root@releng2.nyi.freebsd.org:/usr/obj/usr/src/sys/GENERIC nodename: axial machine: amd64 clock source: unix detected number of CPU cores: 1 current working directory: /usr/home/axial/axial detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 5734 your memory page size is 4096 bytes detected max file descriptor number: 28467 lock engine: POSIX semaphores thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address 127.0.0.1:3031 fd 3 Python version: 2.7.13 (default, Jun 29 2017, 01:17:13) [GCC 4.2.1 Compatible FreeBSD Clang 3.8.0 (tags/RELEASE_380/final 262564)] Set PythonHome to /home/axial/venv/ ImportError: No module named site My config.ini is as follows: [uwsgi] socket = … -
Can Django be used to combine both webapp and moblie api?
I want to use django framework to write a web site with static/dynamic pages (I will not be using angular/react - i.e. SPA technology) but I also want the web app to serve as the backend for a mobile app. What's the best practice here? Can Django alone be used for it? Will I need to use Django REST framework? If you could recommend some specific modules to keep the app as simple as possible and avoid DRY code. That'd be great. Thanks. -
django oauth2 provider 401 after getting token
I used Django Oauth2 toolkit in my django app. my client is an angular web application and uses django api with oauth2. it perfectly works in my localhost and every thing is ok but when i use application in server after success login and getting the access token when it requests another page with authentication the 401 error occures. client is client.example.com and django api is on api.example.com. please help me... request token: client_id:ePmICVI9Dwsb0eKCv8aMTKvq4Jnr7ewtFWFZGLEu grant_type:password username:mohammad password:mz575451 client_secret:2RGeORI0eZbKFZX3gYtjGy response: {"expires_in": 36000, "token_type": "Bearer", "access_token": "yzKlTXuDLOZj5wGescfkNiejyYKhg2", "scope": "read write", "refresh_token": "JJp5Kxq3PcDQthwvSLxvfW2Ee5rLUE"} -
Django query filtered data from database based on GET request
I'm learning django and want to query data based on the request by the user. Here is my code: models.py: class Airline(models.Model): name = models.CharField(max_length=10, blank=True, null=True) code = models.CharField(max_length=2, blank=True, null=True) class FinancialData(models.Model): airline = models.ForeignKey(Airline) mainline_revenue = models.DecimalField(max_digits=7, decimal_places=2) regional_revenue = models.DecimalField(max_digits=7, decimal_places=2) other_revenue = models.DecimalField(max_digits=7, decimal_places=2) total_revenue = models.DecimalField(max_digits=7, decimal_places=2) urls.py: urlpatterns = [ url(r'^airline/(?P<pk>\d+)/$', views.airlinesdata, name='airline_data'), ] views.py: def airlinedata(request): data = FinancialData.objects.filter(pk=airline_id) return data I am not sure what should I wrote in views.py that when a user select for example airline_id of 3, it retrieves FinancialData from the databse for that airline only using the ForeignKey? Thanks -
Updating Objects through Django Rest Framework
I have a Django Rest Framework set up that serves GET requests properly. After asking a previous question here, it should also be able to update objects properly. However, I'm not sure how I can update just one field in a model object. I have a Model ViewSet like this: class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.filter(done = False).order_by('-unixTime') serializer_class = TaskSerializer paginate_by = None And I have the urls registered through a router like this: router = routers.DefaultRouter() router.register(task', views.TaskViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] The serializer is about as basic as they come right now: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('id', 'user', 'task', 'unixTime', 'done') I'd like to be able to update the 'done' field of the Task object as identified by its primary-key id. I think I would need to use a partial_update model or path, but I'm unsure how to implement this. Also, just to give more information, the DRF browser view says the allowed HTTP methods are GET, POST, HEAD, OPTIONS. -
How to filter MultiValueField
I need to filter SearchQuerySet by user, to show only objects, related to current user. I have a model connected to another model by reverse FK: class ItemList(models.Model): title = models.CharField(max_length=50) description = models.TextField(max_length=500) class Item(models.Model): user = models.ForeignKey(User, related_name='items') list = models.ForeignKey(ItemList, related_name='items') and here I have index for it: class ItemListIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) users = indexes.MultiValueField() def prepare_users(self, obj): return [item.user.pk for item in obj.items.all()] here's the ViewSet I use to make search requests: class ItemListSearchViewSet(HaystackViewSet): index_models = [ItemList] serializer_class = ItemListHaystackSerializer filter_backends = [HaystackFilter] pagination_class = SmallResultsSetPagination def get_queryset(self, index_models=[]): qs = super(ItemListSearchViewSet, self).get_queryset(index_models) qs = qs.filter(users__in=[self.request.user.pk]) return qs What I can't figure out, is why this get_queryset method doesn't work properly and I always get empty results for my searches. -
In Django1.10, sending email functionality not working without any exception
I would like to send email in Django 1.10. This is the snippet code in settings.py file. EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my email address' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = '587' EMAIL_USE_TLS = True This is the snippet code in views.py file which is responsible for sending email. from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings from .forms import contactForm def contact(request): form = contactForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] comment = form.cleaned_data['comment'] subject = 'Message form MYSITE.com' message = '%s %s' %(comment, name) emailFrom = form.cleaned_data['email'] emailTo = [settings.EMAIL_HOST_USER] send_mail(subject, message, emailFrom, emailTo, fail_silently=True) context = locals() template = "contact.html" return render(request,template,context) When I clicked submit button, I only received Review blocked sign-in attempt - google email. So I have set my email account as Allow less secure apps: OFF. Then hit the submit button again, I haven't received any email without any exception. As if sending email functionality working - browser loading for a little while. I'm not sure why I couldn't receive email. -
Uploading file to s3 without storing localy django
Is exists such thing like some module with custom storage/upload file handles which help me with loading files from user straight to the s3, without storing whem localy first? So instead of get file from user -> store localy/ im memory -> upload to s3 i want something like get file from user -> upload it to s3 But i cant find anything particular. I was looking for a custom FILE_UPLOAD_HANDLERS/ STORAGE with support of such feature - but wasn't able to find anithing. -
photolouge gallery only uploads one picture
I have a django site with photologue installed, and I followed the official documentation to get it setup. Whenever I go to the admin site to create a gallery I can choose multiple pictures to put in that gallery but once I hit save only the first selected photo gets saved to the gallery. Does anyone know why this is happening. I'm using photologues default template to view my pictures on the front end. -
Rendering Django form in template which corresponds to object your trying to modify
I'm currently displaying a list of objects on the left hand side of the screen with this view: def post_detail(request,id= None): instance= get_object_or_404(NumObject, id=id) context= { 'title': instance.number, 'instance': instance, } return render(request,'post_detail.html',context) and this in the template: {% for obj in instance.blacklist_set.all %} <li><a href=""><h2>{{obj.bnum}}</h2></a></li> {% endfor %} Now, I'm trying to display a form which allows you to edit the blacklist object (as a form) within the same template, on the right hand side. So far, I have a form for the blacklist object, and the view that displays it: def bl_createrules(request): form= AddRules(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect('/') context= { 'blform': form, } return render(request, 'rules.html',context) And on the right hand side of the page, I'm including the template that should display the form like this: {% include 'rules.html' %} The rules.html template just displays the {{form.as_p}}. For some reason the the form itself does not display in the template, just the submit button. My main question is: how can I get the right side of the template to display a form that corresponds to the object clicked on the left hand side? -
Django Rest Framework filtering data by url
I want to filter my Django Rest Framework serialized data by the URL provided by user. Here is my code: models.py: class Airline(models.Model): name = models.CharField(max_length=10, blank=True, null=True) code = models.CharField(max_length=2, blank=True, null=True) def __str__(self): return self.name class FinancialData(models.Model): airline = models.ForeignKey(Airline) mainline_revenue = models.DecimalField(max_digits=7, decimal_places=2) regional_revenue = models.DecimalField(max_digits=7, decimal_places=2) other_revenue = models.DecimalField(max_digits=7, decimal_places=2) total_revenue = models.DecimalField(max_digits=7, decimal_places=2) def __str__(self): return str(self.mainline_revenue) view.py: class ListAirlineFinancialData(generics.ListAPIView): serializer_class = FinancialDataSerializer def get_queryset(self, *args, **kwargs): query_list = FinancialData.objects.filter(pk=airline_id) urls.py: urlpatterns = [ url(r'^api/v1/airline/(?P<pk>\d+)/$', views.ListAirlineFinancialData.as_view(), name='airline_financial_data'), ] What should I code in views to filter my data for the following URL. http://localhost:8000/api/v1/airline/3/ At this moment Django is giving me an error that name 'airline_id' is not defined I can understand that it wants me to pass on airline_id which is in my database but I really dont know how to do it. What code should I write in views.py that it filters all the data for the airline any particular id. Thanks -
Correct way to validate GET parameters in django
I'm building a social website that uses django templates/dynamic pages (no SPA technology in place). I have some ajax calls that check the users news feed or new messages. Example GET web request of those looks as follows: GET /feeds/check/?last_feed=3&feed_source=all&_=1500749662203 HTTP/1.1 This is how I receive it in the view: @login_required @ajax_required def check(request): last_feed = request.GET.get('last_feed') feeds = Feed.get_feeds_after(last_feed) It all works, but I want to protect it so the function get_feeds_after does not crash when a malicious user sets the GET parameter to last_feed="123malicious4556". Currently it crashes because in the Feed model the function does this: @staticmethod def get_feeds_after(feed): feeds = Feed.objects.filter(parent=None, id__gt=float(feed)) return feeds and crashes with the error: ValueError at /feeds/check/ invalid literal for float(): 2fff2 I currently solve this by directly performing checks on the GET variable and handling exception on int() casting: def check(request): last_feed = request.GET.get('last_feed') try: feed_source = int(request.GET.get('last_feed')) except ValueError: return HttpResponse(0) My question is what is the best django-recommended way to address this? I know django has special support forms validation. But this does not seem quite right here, as the GET calls are more of an api rather than forms so it seems like a bad idea to define … -
Django: How to update related model fields when creating model
Django 1.11 I have two models status and statusupdate. When a user makes a new statusupdate I would like it to update certain fields within the status model as well. The way I see it there are four options overriding the save() method on statusupdate using signals custom model manager, which could query for related models and update fields a method on the model that would call the related model and update where I wanted it to. The models are related in the following way; I've done this to have a comprehensive history of the status (using statusupdate), which holds alot more information than the status itself. I've removed some fields to make the example more simple. class Status(models.Model): odometer = models.IntegerField() ... class statusUpdate(models.Model): odometer = models.IntegerField() status = models.ForeignKey(Status, on_delete=models.CASCADE) ... When a user creates a new stautsUpdate, I would like the odometer on Status to be set aswell. Q: What would be the Django way of updating a related model's fields? -
Django: I can not display the information searched from the database on the website
I'm setting up a user registration / login / search program and when I try to find users by email and show them on the site it's like they do not find it in the database, but it's there. views.py enter code here from django.shortcuts import render enter code here from django.views.generic import CreateView, TemplateView enter code here from django.http import HttpResponseRedirect enter code here from django.contrib.auth.views import login, logout enter code here from django.core.urlresolvers import reverse_lazy, reverse enter code here from .forms import CustomUserCreationForm enter code here from .models import MyUser enter code here def home(request): enter code here return render(request, 'usuarios/home.html') enter code here def login_view(request, *args, **kwargs): enter code here if request.user.is_authenticated(): enter code here return HttpResponseRedirect(reverse('usuarios:home')) enter code here kwargs['template_name'] = 'usuarios/login.html' enter code here kwargs['extra_context'] = {'next': reverse('usuarios:home')} enter code here return login(request, *args, **kwargs) enter code here def logout_view(request, *args, **kwargs): enter code here kwargs['next_page'] = reverse('usuarios:home') enter code here return logout(request, *args, **kwargs) enter code here class SerchView(TemplateView): enter code here template_name = "usuarios/pesquisar.html" enter code here def search_view(request, **kwargs): enter code here email = MyUser(email = request.GET['email'], nome = request.GET['nome']) enter code here myusers = MyUser.objects.filter(email__contains = 'email') enter code here context …