Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement x-editable in Django
how can I use x-editable in Django. my model.py file from django.db import models class Certificate(models.Model): application = models.CharField(db_column='Application', primary_key=True, max_length=255, blank=True, null=False) # Field name made lowercase. startdate = models.CharField(db_column='startDate', max_length=255, blank=True, null=True) # Field name made lowercase. expiredate = models.CharField(db_column='ExpireDate', max_length=255, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'certificate' -
How to count with filter django query?
I'm trying to get a list of latest 100 posts and also the aggregated count of approved, pending, and rejected posts for the user of that post. models.py class BlogPost(models.Model): POST_STATUSES = ( ('A', 'Approved'), ('P', 'Pending'), ('R', 'Rejected') ) author = models.ForeignKey(User) title = models.CharField(max_length=50) description = models.TextField() status = models.ChoiceField(max_length=1, choices=POST_STATUSES) views.py def latest_posts(request) latest_100_posts = BlogPost.objects.all()[:100] I get the latest 100 posts, now I want to get each author of the post and display their total Approved, Pending, Rejected count Title Of Post, Author1, 10, 5, 1 Title Of Post2, Author2, 7, 3, 1 Title Of Post3, Author1, 10, 5, 1 ... Some things I've thought about are looping through each of the 100 posts and returning the count, but it seems very inefficient for post in latest_100_posts: approved_count = BlogPost.objects.filter(author=post.user,status='A').count() pending_count = BlogPost.objects.filter(author=post.user,status='P').count() rejected_count = BlogPost.objects.filter(author=post.user,status='R').count() Is there a more efficient way to do this? I know about using aggregate Count but I'm not sure how to sub-filter on the status ChoiceField -
Django 2.1 -- Display Model Meta class verbose_name in Template View
First section of code works fine; it is for reference. #Basic Model class MyTestModel(models.Model): record = models.CharField(max_length=100) def __str__(self): return self.record #Specify verbose_name class Meta: verbose_name = 'UniqueNameExample' verbose_name_plural = verbose_name ordering = ['record'] #Generic ListView. class MyTemplateView(ListView): model = MyTestModel template_name = 'base.html' context_object_name = 'model_list' #Python block in HTML template. So far, so good. {% for item in model_list %} {{ item.record }}<br> #{{ item }} also works {% endfor %} I am trying to access the Model's verbose_name ('UniqueNameExample') AND the model_list in the view. I've tried registering a filter, a tag, and simple_tag. Something like: templatetags/verbose.py from django import template register = template.Library() @register.filter (or @register.tag or @register.simple_tag) def verbose_name(obj): #Could be verbose_name(model) or whatever input return obj._meta.verbose_name And then after {% load verbose %} in my HTML (which also works fine), I'll try something like this: {{ object|verbose_name }} And I'll get the error 'str' object has no attribute '_meta'. Error is the same if using a tag: {% verbose_name object %} Note: tags apparently worked for earlier versions, but maybe I'm using them incorrectly? The one thing I've tried that gets the answer half right is if I set the following under the Meta … -
please help me about nginx+uwsgi+django
I deployed a django project on the cloud server ubuntu system, but it has not been running, I feel where there is an error,Sometimes the page will appear 502 bad gateway,please help me find.thinks a lot!!! this is home/sscc/sscc2019/uwsgi.ini [uwsgi] socket=127.0.0.1:8000 chdir=/home/sscc/sscc2019 wsgi-file=/home/sscc/sscc2019/wsgi.py enable-threads=true thunder-lock=true post-buffering=4096 processes=4 threads=2 master=true pidfile=/home/sscc/sscc2019/uwsgi.pid daemonize=/home/sscc/sscc2019/uswgi.log module=sscc2019.wsgi:application vacuum=true chmod-socket=666 #virtualenv=/root/.virtualenvs/ssccenv harakiri=60 max-requests=5000 uid=1000 gid=2000 #plugin=python3 this is /home/sscc/sscc2019/uwsgi.log: *** Starting uWSGI 2.0.18 (64bit) on [Tue Mar 19 12:35:02 2019] *** compiled with version: 5.4.0 20160609 on 19 March 2019 03:25:55 os: Linux-4.4.0-142-generic #168-Ubuntu SMP Wed Jan 16 21:00:45 UTC 2019 nodename: localhost machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 2 current working directory: /home/sscc/sscc2019 writing pidfile to /home/sscc/sscc2019/uwsgi.pid detected binary path: /usr/local/bin/uwsgi uWSGI running as root, you can use --uid/--gid/--chroot options setgid() to 2000 setuid() to 1000 chdir() to /home/sscc/sscc2019 your processes number limit is 15655 your memory page size is 4096 bytes detected max file descriptor number: 65535 lock engine: pthread robust mutexes thunder lock: enabled probably another instance of uWSGI is running on the same address (127.0.0.1:8000). bind(): Address already in use [core/socket.c line 769] this is /etc/nginx/sites-availables/sscc2019.conf: server{ listen 80; listen:this-is-my-IP:80; charset utf-8; server_name ssccracing.com; client_max_body_size … -
"Authentication credentials were not provided." in DRF
I am using rest_framework_simplejwt authentication in my DRF backend. Every things works absolutely fine when I am using DRF browser in terms of authentication and having access to predefined API endpoints. However when I want to programatically access the end points for post/patch method I get Authentication credentials were not provided. error. Here is my settings: ALLOWED_HOSTS = ['*'] ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'propertypost.apps.PropertyConfig', 'users.apps.UsersConfig', 'rest_framework', # 3rd party 'django_filters', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'allauth.socialaccount', 'django.contrib.gis', ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.OrderingFilter', 'rest_framework.filters.SearchFilter', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( # 'rest_framework.permissions.IsAuthenticated', ), } ... SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=525600), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=120), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } AUTH_USER_MODEL = 'users.CustomUser' REST_USE_JWT = True as I said, above setting works perfectly in DRF browser, but when here when I try to request a patch method it gives Authentication credentials were not provided: AUTH_ENDPOINT = "http://127.0.0.1:8000/rest-auth/login" data = { 'username': username, 'password': password headers = { "Content-Type": "application/json" } r = requests.post(AUTH_ENDPOINT, data=json.dumps(data), headers=headers) token=r.json()['token'] data … -
Django query one to many based on extra condition
I have code set up like this: class User(models.Model): email = models.EmailField(_(u'email address'), max_length=255, unique=True, db_index=True, blank=True) class Verification(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='verifications') category = models.CharField(choices=constants.VERIFICATION_CATEGORY_CHOICES, default=None, max_length=255) status = models.CharField(_(u'verification status'), max_length=255, default=constants.STATUS_PENDING, blank=True, null=True) Now I need to get a list of users who has "ID"(category) verification and verification status is "APPROVED". How can I achieve that? Thanks a lot. -
Why event loop is closed in this situation?
I'm using aiohttp==2.3.10, python3.5, Django==2.1.3 My directory structure as below: ├─project1 ├─app1 ├─management ├─commands └─pull_campaign_list_every_15m.py My main codes: class Command(BaseCommand): help = "pull campaign data" def handle(self, *args, **options): # get related data here task_list = [] for account_info in account_data_list: #... task_list.extend([ asyncio.ensure_future( _handle_campaign_list(related_param)) for campaign in campaign_list if campaign_list ]) loop = asyncio.get_event_loop() try: loop.run_until_complete(asyncio.wait(task_list)) except Exception as e: info_logger.info(e) finally: loop.close() async def _handle_campaign_list(realated_param): # do something here batch handle list data try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: result = await response.text() temp_data = json.loads(result) # save data here using Django ORM except aiohttp.client_exceptions.ClientConnectorError: info_logger.info("bad request connect error") except asyncio.TimeoutError: info_logger.info("server timeout") When I called command like python manage.py pull_campaign_list_every_15m , then I got errors like below: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/.virtualenvs/project1/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/.virtualenvs/project1/lib/python3.5/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/.virtualenvs/project1/lib/python3.5/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/.virtualenvs/project1/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/project1/app1/management/commands/pull_campaign_list_every_15m.py", line 77, in handle campaign_list if campaign_list File "/home/project1/app1/management/commands/pull_campaign_list_every_15m.py", line 77, in <listcomp> campaign_list if campaign_list File "/usr/local/lib/python3.5/asyncio/tasks.py", line 547, in ensure_future task = loop.create_task(coro_or_future) File "/usr/local/lib/python3.5/asyncio/base_events.py", line 259, … -
Django how to update a self-dependent one-to-many field
// models.py class CustomUser(AbstractBaseUser): ....... referred_who = models.ManyToManyField('self', blank=True, symmetrical=False) // views.py class ReferralAward(View): def get(self, request, *args, **kwargs): referral_id = self.request.GET['referral_id'] current_referred = self.request.GET['referred'] user = get_user_model().objects.filter(referral_id=referral_id) // Current User referred_user = get_user_model().objects.filter(username=current_referred) // User being referred for item in user: previous_referred = item.referred_who previous_referred.add(referred_user[0]) user.update(referred_who=previous_referred) return HttpResponse('Update successful') I am implementing a referral system for the user. If the new user registers an account with the link which the referrer provides, the new user will be stored to the 'referred_who' field of the referrer. I am getting for following error for my code: django.core.exceptions.FieldError: Cannot update model field <django.db.models.fields.related.ManyToManyField: referred_who> (only non-relations and foreign keys permitted). Also, I checked my django admin, the 'Referred who' field actually lists all the users in the database. It seems that the one being referred is being highlighted? Is there a way to only show the users being referred instead of all the users? Can someone help me to fix it, or show me a better way to do it? Thanks a lot! -
Django and React development in Docker and nginx, wrong MIME types errors
i developing Django react apps with docker , but my admin page get below error. I'm using nginx to proxy my route to react client and django backend and admin to backend. But my backend shows this kind of error which doesn't serve the static css files. Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:3050/static/admin/css/base.css". ... Does anyone know how to fix this?I have try this link or added include /etc/nginx/mime.types; to my nginx conf but it shows 404 error instead. Below is my nginx conf. I have even try to delete my browser cache but it didn't work toos. Please help upstream client { server client:3000; } upstream api { server api:8000; } server { listen 80; include /etc/nginx/mime.types; ######Try added this but it shows 404 instead of the errors location / { proxy_pass http://client; } location /sockjs-node { proxy_pass http://client; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } location ~ ^/(static/|js|css) { autoindex on; autoindex_exact_size off; autoindex_localtime on; proxy_pass http://client; } location ~ ^/(static/|pagedown|pagedown-extra|rest_framework|admin) { autoindex on; autoindex_exact_size off; autoindex_localtime on; proxy_pass http://api; } location ~ ^/api { # rewrite /api/(.*) /$1 break; # this is for chop off the /api/ urlpath proxy_pass http://api; … -
How to properly login user via dajango
Am trying to login user in django. If I use the code below everything works fine def login(request): return render(request, 'web/login.html') def home(request): if request.method == 'POST': if Member.objects.filter(username=request.POST['username'], password=request.POST['password']).exists(): member = Member.objects.get(username=request.POST['username'], password=request.POST['password']) return render(request, 'web/home.html', {'member': member}) else: context = {'msg': 'Invalid username or password'} return render(request, 'web/login.html', context) What I want: Here am trying to perform the same login by processing data using clean_data but it gives error The view webApp.views.home didn't return an HttpResponse object. It returned None instead. Does it mean that my form data is empty or not posted I have reference solution found here but with no luck link Any help on this here is the code def login(request): return render(request, 'web/login.html') def home(request): if request.method == 'POST': form = loginForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required username = form.cleaned_data['username'] password = form.cleaned_data['password'] #if len(username) < 5 || len(password) < 5: if Member.objects.filter(username=username, password=password).exists(): member = Member.objects.get(username=username, password=password) return render(request, 'web/home.html', {'member': member}) print("success") else: context = {'msg': 'Invalid username or password'} return render(request, 'web/login.html', context) print('failed') -
When I deployed django project with django+nginx+uwsgi, I found that uwsgi could not start up
I did not report an error when I started, but only one,it seems not work,i need help ,thank you a lot! root@localhost:/home/sscc/sscc2019# uwsgi --ini uwsgi.ini [uWSGI] getting INI configuration from uwsgi.ini root@localhost:/home/sscc/sscc2019# ps aux|grep uwsgi root 11018 0.0 0.0 14224 1032 pts/0 S+ 09:03 0:00 grep --color=auto uwsgi this is my nginx ,it seems like working root@localhost:/home/sscc/sscc2019# ps aux|grep nginx root 10997 0.0 0.0 125120 1456 ? Ss 08:55 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; www-data 10998 0.0 0.0 125444 3188 ? S 08:55 0:00 nginx: worker process www-data 10999 0.0 0.0 125444 3188 ? S 08:55 0:00 nginx: worker process root 11024 0.0 0.0 14224 932 pts/0 S+ 09:04 0:00 grep --color=auto nginx this is my uwsgi.log: *** Starting uWSGI 2.0.12-debian (64bit) on [Tue Mar 19 08:09:12 2019] *** compiled with version: 5.4.0 20160609 on 28 September 2018 15:49:44 os: Linux-4.4.0-142-generic #168-Ubuntu SMP Wed Jan 16 21:00:45 UTC 2019 nodename: localhost machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 2 current working directory: /home/sscc/sscc2019 writing pidfile to uwsgi.pid detected binary path: /usr/bin/uwsgi-core uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! … -
Calling function in views.py from template using jaavascrpt
Is it possible to call a function in views.py from a template without having url? I have two droplists on for authors and the other one for the books. When someone selects an author I need to call a function in views.py to got books that related to the author so the second droplist should include books that belong to the author. -
Django - Retrieving fields in another model via mutiple foreignKey relationships
The following sample database stores posts of news and relevant information for each piece of news. I'm interested in retrieving the topics associated with each news. The problem is, they are stored in different tables with complex relationships. Each news is assigned with a newsid in the table NewsFeed: class NewsFeed(models.Model): newsid= models.OneToOneField('NewsSub', on_delete=models.CASCADE, db_column='newsid', primary_key=True) def __str__(self): return str(self.newsid) An one-to-one relationship is defined between the field newsid in the class NewsFeed and the model NewsSub: class NewsSub(models.Model): newsid = models.BigIntegerField(primary_key=True) In another class NewsTopic, a foreignKey relationship is defined between the field newsid with the model NewsSub: class NewsTopic(models.Model): newsid = models.ForeignKey(NewsSub, on_delete=models.DO_NOTHING, db_column='newsid') topicid = models.ForeignKey(NewsLabel, on_delete=models.DO_NOTHING, db_column='topicid', related_name = 'topic') In the NewsTopic db table, each newsid may correspond to more than one topicid. Finally, the field topicid of the class NewsTopic is related to the model NewsLabel: class NewsLabel(models.Model): topicid = models.BigIntegerField(primary_key=True) topiclabel = models.CharField(max_length=100) def __str__(self): return self.topiclabel In the NewsLabel db table, each toicid corresponds to a unique topiclabel. My goal is to retrieve the topiclabel(s) associated with each NewsFeed object, by querying the newsid. Suppose result represents one such object, I'm wondering is it possible to do something like result.newsid.topicid.topiclabel? Thanks and … -
Editing Foreign Fields by Detecting Changes in Model Fields
So, I currently have the following model. class Match(models.Model): date = models.DateField() time = models.TimeField(null=True, blank=True) team1 = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="team1") team2 = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="team2") winner = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True, related_name="winner") viewLink = models.CharField(max_length=100, null=True) viewLink2 = models.CharField(max_length=100, null=True, blank=True) mSlug = models.SlugField(max_length=50, unique=True, null=True) __original_winner = None def __init__(self, *args, **kwargs): super(Match, self).__init__(*args, **kwargs) self.__original_winner = self.winner def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.winner != self.__original_winner: super(Match, self).save(force_insert, force_update, *args, **kwargs) if self.winner == self.team1: team1.currentRanking = team1.currentRanking + 100 team2.currentRanking = team2.currentRanking - 50 else: team2.currentRanking = team1.currentRanking + 100 team1.currentRanking = team2.currentRanking - 50 self.__original_winner = self.winner Whenever the initial model is created, there is no winner, because the match is always in the future. However, when the match is concluded, we want to be able to go into, assign the round a winner, and have it edit each team's ranking points based on who one. However, the model is not updating. Is there another way to do this? -
serializer layer not running
The use case of my application is There can be 3 kinds of user. End User Agent Company It is determined in the signup/registration process by allowing user to fill the role section. Based on the user role he/she has selected, the profile is created accordingly because the profile will be different for end user and company which is relevant. In django, what we do is when the user is created, create a profile or say link the profile table to that user in post_save signal. However, I am using graphql i wanted to leverage the serializer layer to handle such thick cases. I tried the following way but my code is not reached to the create function. This is how i have implemented class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwars): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password=password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractUser): USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] USER_TYPE_CHOICES = ( (1, 'end_user'), (2, 'agent'), (3, 'company'), ) role = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, default=1) objects = UserManager() def __str__(self): return self.email User._meta.get_field('email')._unique = True User._meta.get_field('username')._unique … -
Django get latest version of task
I am trying to write a query in Django but I'm not sure whats the best way to write this. Also assuming that the database is mySQL. This matters if distinct is used. class Homework(models.Model): title = TextField() class Assignment(models.Model): homework_id = Foreignkey(Homework, on_delete=models.CASCADE) task = IntegerField(default=1) version = IntegerField(default=1) Given the models above I want to get all the assignments in a particular homework where the assignments are the latest version of the task. example: Homework_id: 1 assignment v1, t1 assignment v2, t1 assignment v1, t2 If I have one homework object where the assignment with task 1 and assignment task 2 are in it then the result query should return Assignment t1, v2 and Assignment t2, v1 v refers to version t refers to task -
How to access an object from PK of another object in ModelViewSet
The generic structure of the models is that there are teachers and devices, each device has a ForeignKey relationship with the teachers ID/PK. I'm trying to create my API in such a way that when going to the detail view for a teacher, all of the associated devices are displayed. I've overridden get_serializer_class() to specify which serializer to use at the appropriate time, but can't figure out how to correctly change the Queryset based on detail view or not. Error posted below. Got AttributeError when attempting to get a value for field `brand` on serializer `DeviceSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Teacher` instance. Original exception text was: 'Teacher' object has no attribute 'brand'. class TeacherViewSet(viewsets.ModelViewSet): queryset = Teacher.objects.order_by('campus','name') serializer_class = TeacherSerializer detail_serializer_class = DeviceSerializer def get_serializer_class(self): if self.action == 'retrieve': if hasattr(self, 'detail_serializer_class'): return self.detail_serializer_class return super(TeacherViewSet, self).get_serializer_class() def get_queryset(self, pk=None): if pk is not None: return Device.objects.filter(device__owner=self.kwargs.get('pk') return Teacher.objects.all() -
How does one access related fields from a model's custom queryset w/ a manager implemented by queryset.as_manager()?
I've got a model that references itself via a second relationship-model: ... class Branch(models.Model): length = models.PositiveSmallIntegerField() objects = BranchQueryset.as_manager() # Defined below @property def branches(self): if self._branches: branch_pks = [branch.child_branch.pk for branch in self._branches.all()] return Branch.objects.filter(pk__in=branch_pks) return None class Branches(models.Model): parent_branch = models.ForeignKey(Branch, related_name='_branches', on_delete=models.CASCADE) child_branch = models.ForeignKey(Branch, on_delete=models.SET_NULL) order = models.PositiveSmallIntegerField() Thus, if branch is some instance of Branch, branch.branches will return a Queryset of Branch objects which branch from branch. ;) The problem is this: class BranchQueryset(models.QuerySet): def get_trunks(self): return self.filter(branches_set__isnull=True) If I call Branch.objects.get_trunks(), I get the error django.core.exceptions.FieldError: Cannot resolve keyword 'branches_set' into field. Choices are: _branches, length, id, step. So, my custom queryset can't access related objects. I think it has something to do with this: Using managers for related object access By default, Django uses an instance of the Model._base_manager manager class when accessing related objects (i.e. choice.question), not the _default_manager on the related object. This is because Django needs to be able to retrieve the related object, even if it would otherwise be filtered out (and hence be inaccessible) by the default manager. But I haven't managed to get anything working by creating a manager (I was hoping to be able to … -
django: Assertion Error `create()` did not return an object instance
I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have defined a serializer - ReceiptLog with no model, which should create entries in TestCaseCommandRun and TestCaseCommandRunResults when a post() request is made to ReceiptLog api endpoint. Receipt log doesn't exist in the database, I am using it just as an endpoint to accept a combined payload and create entries in underlying tables. Post() to TestCaseCommandRunResults and TestCaseCommandRun works independently, however, when I try to post through ReceiptLog it throws below error Error Traceback: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.6/contextlib.py" in inner 52. return func(*args, **kwds) File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch 495. response = self.handle_exception(exc) File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception 455. self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch 492. response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/rest_framework/generics.py" in post 192. return self.create(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create 21. self.perform_create(serializer) File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in perform_create 26. serializer.save() File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in save 216. '`create()` did not return an object … -
Django Mixin method that affects composite class
Say I have the following simple classes: class NumberMixin(models.Model): number = models.IntegerField() class RaceCar(models.Model, NumberMixin): ... class Athlete(models.Model, NumberMixin): ... Now say that I want a method to set number and that method is going to look the same for RaceCar, Athlete, and any other classes that use NumberMixin. def common_logic(): obj = RaceCar.objects.filter(name='fortytwo').first() obj.number = 42 Each class which is partially composed of NumberMixin will have a common_logic(), except the RaceCar, Athlete, etc. references will be different for each class If I want common_logic() to be used for any class that inherits from NumberMixin, is there any way I can put common_logic() in the NumberMixin class instead of having to copy-paste it into all of the other classes? -
django uwsgi nginx redhat 7 unix socket
uwsgi --http : 8000 --chdir /pathtohomeproject --wsgi.file /pathtowsgifile.py when i do this its working but when i try to use sockets instead of http its not working. Environment is redhat 7 django2.1 and python3. Im banging my head whole day to solve this. can anyone tell me how to fix this i dont know what is the error. my mysite.conf # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///Website/bluetext_reviewer/AutomationServices/site.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for # substitute your machine's IP address or FQDN server_name sjautowebdevn01; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { # your Django project's media files - amend as required alias /Website/bluetext_reviewer/AutomationServices/media; } location /static { # your Django project's static files - amend as required alias /Website/bluetext_reviewer/AutomationServices/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass unix:///Website/bluetext_reviewer/AutomationServices/site.sock; # the uwsgi_params file you installed include … -
What do I need to get a brilliant Python developer profile?
I'm trying to construct a goof profile as a Python developer and it'll be great for me to get some advice from those who are being coding for a while. I'm starting to learn some Django, Tensorflow and some other libraries for Data Science as Matplotlib, pandas, etc. Could you offer me any guidance about new frameworks to learn or where can I give my next step to improve my profile. Thank you so much for any advice and have a great coding. -
Handle file and remote server urls on a django model
i have a model object that is composed of a title and a file : class StoringModel(models.Model): title = models.(max_length=200, default='') file = models.FileField() This way, from the admin panel, i can upload files and then serve the static files anywhere in the app. Now, let's say tomorrow i would like to handle static files and remote urls. What are your advice on how to solve this issue ? Should i prepare an url field that is of type URLField in the model, and let one of url or file be optional ? Is there a way to create a custom field type that answers this issue ? -
Django foreign-key and one-to-one access best practice
Say I have the following Models: class User(models.Model): name = models.CharField(max_length=255) ... class Knapsack(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=False ) ... Now say I want to access a given user's (my_user) knapsacks. I have a couple options: knapsacks = Knapsack.objects.filter(user=my_user).values() knapsacks = my_user.knapsack.values() The same question could be asked but for a one-to-one relationship instead of foreign key. Which one is the better practice? -
Django try exception in class view
im only student so please bear with me. I already posted another topic about this but in function view. now i want to how do i convert this try exception to a class view and also add that comment form. here's my views.py def def BookDetail(request, id): most_recent = Book.objects.order_by('-timestamp')[:3] book= get_object_or_404(Book, id=id) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = book form.save() return redirect(reverse("book-detail", kwargs={ 'id': book.pk })) if request.user.is_anonymous: user_membership = None else: try: user_membership = Customer.objects.get(user=request.user) except Customer.DoesNotExist: user_membership = None context = { 'user_membership': user_membership, 'form': form, 'book': book, 'most_recent': most_recent, } return render(request, 'catalog/book_detail.html', context) here is my new class view class BookDetailView(NeverCacheMixin, generic.DetailView): model = Book