Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: use inspectdb generate model get ORA-00904 error
I want to generate models file automatic by shell 'inspectdb',but i got following error: Unable to inspect table 't_cobizaccrent' The error was: ORA-00904: "IDENTITY_COLUMN": invalid identifier The table defined as follow table columns and this is the primary key primary keys The environment : OS version:windows 10 Python version:3.7.0 Django version:2.0.7 cx_Oracle version:6.4.1 Oracle version:11.2.0 -
can't access child of OneToOneField in django?
I am trying to acces child of OneToOneField but I am getting the error. class Products(models.Model): unique_id=models.CharField(max_length=13,unique=True) product_full_name=models.CharField(max_length=50,null=True) child_name=models.CharField(max_length=15,null=True)# name of the model connected by OneToOneField in lowercase def __str__(self): return str(self.product_full_name) def selling_price(self): child=self.child_name return getattr(a,child+'_set').all().first().selling_price class Product1(models.Model): product=models.OneToOneField(Products) selling_price=models.FloatField() ...... class Product2(models.Model): product=models.OneToOneField(Products) selling_price=models.FloatField() ...... class Product3(models.Model): product=models.OneToOneField(Products) selling_price=models.FloatField() ...... When I am trying to access get_selling_price() method I am getting error "Products object does not have any attribute product1_set" for the Products model that is connected to the Product1 model. -
Monitoring a data source and store to database in realtime
I want to keep monitoring a data source for example weather condition or stock market (there is no way to let the data source to call you ... you have to query API every time) and keep storing the data retrieved to mysql or other databases. There will be a web page to show the analysis result generated from the database. My question is: what is the typical way to implement this? What is the best way to make the server to keep tracking the data source? Considering the workload and server performance. Is there any language can do this better than others? PHP, Python, or Javascript? Thanks! -
what does this ORM query means?
i understand the first query but what is second query is doing? inner_qs = Blog.objects.filter(name__contains='Ch').values('name') entries = Entry.objects.filter(blog__name__in=inner_qs) -
How to get the corresponding child instance to an abstract class instance in django2?
I have a model: login which stores the username and password for every user that can login, and I have Customer, Manager, and Bank extending that. I have made a function for authentication in the Login model. What I want to do now is to authenticate using that function and then get the actual subclass that has logged it have it be each of the above(bank, customer, manager). I'm aware of this question but since that question is for 10 years ago and already has 8 answers and so many comments. I thought It would be better to ask a new question to see if there is any easier solution for django2 now. Here is my models code: Please feel free to comment on it(I would love that): class Login(models.Model): class Meta: abstract = True password = models.CharField(max_length=1000) username = models.CharField(max_length=100) # this is not the actualy password it is sha512(salt + password) salt = models.CharField(max_length=1000) def init(self, uname, password): self.username = uname self.salt = token_hex(32) self.password = sha512(self.salt + password) def authenticate(self, password): if self.password == sha512(self.salt + password): return True return False class Bank(Login): name = models.CharField(max_length=100) token = models.CharField(max_length=100) wallet = models.ForeignKey('Wallet', on_delete=models.CASCADE, related_name='bank_wallet') def create_wallet(self): self.wallet … -
Django: Model data not displaying in local timezone
I'm using Django 1.11 and pytz==2018.3. I have a chat model with a timezone field that won't display in local time. class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1200) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) When I print it normally like this I get: <div class="textcontainer lighter"> {{ message }} <span class="time-right">{{ message.timestamp|date:"SHORT_DATETIME_FORMAT" }}</span> </div> output: July 8, 2018, 2:55 a.m However, this is UTC time (6 hours ahead. I want it to say a different time instead). I've tried the following: {{ message.timestamp|localtime }} But this doesn't do anything. I've also tried including these two as well: {% load tz %} {% get_current_timezone as TIME_ZONE %} In my settings.py file I have: USE_L10N = True USE_TZ = True Thoughts? Thanks in advance! -
Why is Django giving Page not found error?
I am Building a Sample REST API using Django-REST-Framework and Apache Cassandra. Here's my model: import uuid from cassandra.cqlengine import columns from cassandra.cqlengine.models import Model class User(Model): read_repair_chance = 0.05 user_id = columns.UUID(primary_key=True, default=uuid.uuid4) username = columns.Text(required=True) password = columns.Text(required=True) email = columns.Text(required=True) def __str__(self): return self.username def get(self,request, format=None): uname = [user.name for user in User.object.all()] return Response(uname) I am able to add new users and get a list of them. But when I try to issue a DELETE request using POSTMAN, DELETE http://localhost:8000/users/0f7b0ada-01ab-4907-b9d2-3fa0d27ae1ce I am getting page not found 404 error. Can someone identify where am I going wrong. Here's the contents of the rest of the files: Views.py from rest_framework import viewsets from .models import User from .serializers import UserSerializer from rest_framework.response import Response from rest_framework import status class UserView(viewsets.ViewSet): def get_object(self, pk): try: return User.objects.get(pk=pk) except User.DoesNotExist: raise Http404 def get_user_list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset,many=True) return Response(serializer.data) def get(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user) return Response(user.data) def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return … -
Django template url NoReverseMatch for re_path
I am attempting to make a validation link e-mail as part of my user sign-up in Django. I have a {% url %} tag in my template however it is giving me a NoReverseMatch error with regards to the uid & token variables. Here is the code in the template: https://{{ domain }}{% url 'users:activate' uidb64=uid token=token%} Here is my URL pattern: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), And last of all here is my error: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uidb64': b'MzY', 'token': '4xq-eb603ee3a9676d7b3edc'}' not found. 1 pattern(s) tried: ['users\\/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] I have a hunch it may be something to do with the regular expression but that is not a strong point I have (yet)! It appears to find the activation URL pattern but I cant seem to make it recognize the arguments for the url! -
django-rest and angular nginx load static image issue
hi im trying to load my angular app with nginx everything work except static image that are part of template (product image that are saved in upload folder are ok) this is the related code of setting.py : MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, 'upload') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.dirname((__file__))) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' and this is my index file in /static/ folder: {% load static %} <!DOCTYPE html> <html lang="fa" id="persain"> <head> <meta charset="utf-8"> <title>M4new</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="stylesheet" href="{% static 'styles.4bdc8f4141f772a8814a.css' %}"> </head> <body> <app-root>Loading . . .</app-root> <script type="text/javascript" src="{% static 'runtime.6afe30102d8fe7337431.js' %}"></script> <script type="text/javascript" src="{% static 'polyfills.b0205464c9bd4e7fe3b3.js' %}"></script> <script type="text/javascript" src="{% static 'scripts.59ed76cc23ba77b0ec72.js' %}"></script> <script type="text/javascript" src="{% static 'main.159b545905e86c2df1d4.js' %}"></script> </body> </html> and my static directory is like this : and my result : as you see image cant load because they lose static keyword in begin of url . i tried Python manage.py collectstatic and i add urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to end … -
Django with AWS Elastic Beanstalk; cannot reflect environment variables on eb
I'm new to AWS and I'm trying to deploy my Django project into it. I set up db and already set environment variables manually but it doesn't reflect on eb even though it reflect on local server. When I run local server, the pages does work but when I try to access to page on AWS eb, this error happens. "settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. settings.py is like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME', ''), 'USER': os.environ.get('DB_USERNAME', ''), 'PASSWORD': os.environ.get('DB_PASSWORD', ''), 'HOST': os.environ.get('DB_HOSTNAME', ''), 'PORT': os.environ.get('DB_PORT', ''), } } How can I fix this? Also quick question eb open doesn't work on Linux subsystem so I have to copy and paste the url AWS gives evry time I get access to page. What is the cause of this? -
unable to save changes to objects with form.save()
I am writing a control view function edit_article to update fields of title and content of model table Article: To update the title and content, I employed article=form.save def edit_article(request, pk): article = Article.objects.get(pk=pk) if request.method == "POST": form = ArticleForm(data=request.POST) print(request.POST) if form.is_valid(): article = form.save() It reports error when issue submitting django.db.utils.IntegrityError: (1048, "Column 'owner_id' cannot be null") I did not change owner_id, just keep it as its previous state. The problem is solved by explicitly re-assign attribute: if form.is_valid(): # article = form.save() article.title = form.cleaned_data['title'] article.content = form.cleaned_data['content'] article.save() Why form.save() failed as a shortcut? -
Django calls wrong path after calling long path first
I have these 3 paths in my urls.py: urlpatterns = [ ... path("stuff/<str:name>/", views.stuff), path("stuff/<str:name>/<str:color>/", views.colored_stuff), path("stuff/<str:name>/<str:color>/<str:size>/", views.sized_colored_stuff), ] and these corresponding methods in views.py: def stuff(request, name): ... def colored_stuff(request, name, color): ... def sized_colored_stuff(request, name, color, size): ... If I call https://example.com/stuff/Oak/Red/Big, the third path is called, which makes sense. However, then when I try to hit https://example.com/stuff/Birch then request still goes to the third path instead of the first. Any idea why and how to fix it? -
In django, what is correct setup for media deployment on python anywhere
I am trying to deploy my django app on python anywhere, but I believe media_urls or media_root may be set incorrectly. I also spent time trying to figure out how to print all valid urls on django, but nothing work for me on this link. Django : How can I see a list of urlpatterns?. I received a "ModuleNotFoundError: No module named 'django.core.urlresolvers'" from .base import * DEBUG = False ALLOWED_HOSTS = ["*"] MEDIA_ROOT = os.path.join(BASE_DIR, "images") MEDIA_URL = '/snapcapsule/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") -
Django request.POST.get does not save to model field
I am trying to save data from request.POST dictionary. I would like to get the the 'name' value from request.POST which should correspond to the prefix. However, it does not happen and nothing gets saved to Name model. Also, I get no error. Could you please kindly advise how to solve this case? Thank you. views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions from django.core.exceptions import ValidationError import pdb model_names = ['A', 'B'] def get_assumptions(request): AssumptionFormset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) if request.method == 'POST': formsets = [AssumptionFormset(request.POST, prefix=thing) for thing in model_names] if all([formset.is_valid() for formset in formsets]): for formset in formsets: for form in formset: form.save(commit=False) form.Name = request.POST.get('name') form.save() else: formsets = [AssumptionFormset(prefix=thing) for thing in model_names] return render(request, 'assumptions.html', {'formsets': formsets}) assumptions.html <div class="form"> <form action="" method="post"> {% for formset in formsets %} {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <h1>{{formset.prefix}}</h1> <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %}"> {% for field in form.visible_fields %} <td> {# Include the hidden … -
Django No Reverse Match on Nginx Server
I am trying to build a simple blog application on an ubuntu droplet hosted on digital ocean. I have the DJango app in mid development and I am getting a No reverse match for a view that existes Here is the error: 'NoReverseMatch at / Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name.' Here is my Url Patterns: from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), ] ~ Here is My view from django.shortcuts import render, get_object_or_404 def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) ~ Here is My nginx file: server { listen 80; server_name XXX.XXX.XXX.XXX; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/XXXX/Django; } location / { include proxy_params; proxy_pass http://unix:/home/XXX/Django/BizBlog.sock; } } Where is the error occurring? I can't figure this out, I have worked with Django before and know it has to do with the url searching for the string patterns in my view function and being unable to find it but the function is there. What is wrong? -
Issue upgrading to Wagtail 2.1
Upgraded from Wagtail 2.0 to 2.1. Running on an Ubuntu vagrant box. I get the error below when running any manage.py command after upgrading from Wagtail 2.0 to 2.1 or 2.11. If I downgrade back to 2.0 it works again, so I'm sure I have some incorrect dependencies in there... Any thoughts on how to resolve this? Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/chrisrogers/blog/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/chrisrogers/blog/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/chrisrogers/blog/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/chrisrogers/blog/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/chrisrogers/blog/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/chrisrogers/blog/lib/python3.6/site-packages/wagtail/search/apps.py", line 4, in <module> from wagtail.search.signal_handlers import register_signal_handlers File "/Users/chrisrogers/blog/lib/python3.6/site-packages/wagtail/search/signal_handlers.py", line 3, in <module> from wagtail.search import index File "/Users/chrisrogers/blog/lib/python3.6/site-packages/wagtail/search/index.py", line 10, in <module> from modelcluster.fields import ParentalManyToManyField File "/Users/chrisrogers/blog/lib/python3.6/site-packages/modelcluster/fields.py", line 19, in <module> from modelcluster.models import get_related_model, … -
Error greenlet docker build
everything good? I have a problem using docker build. This application has already been mounted on 2 other machines but every time this error occurs. Does anyone know what I should do to fix it. I have a windows 10 and im using Docker Toolbox. I tried this answer here from the site without success: Python module installation error: command 'gcc' failed with exit status 1 I followed the docking tutorial from docker's own website: https://docs.docker.com/compose/django/#define-the-project-components Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code RUN pip3 install virtualenv RUN virtualenv /code ADD requirements.txt /code/ RUN python -m pip install -r requirements.txt --no-cache-dir ADD . /code/ Error log: PS C:\Users\ThinkPad\Documents\ChatBot> docker build -t backend . Sending build context to Docker daemon 209.5MB Step 1/9 : FROM python:3 ---> ce54ff8f2af6 Step 2/9 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 5cefadc9e069 Step 3/9 : RUN mkdir /code ---> Using cache ---> 1dd0287bc4ba Step 4/9 : WORKDIR /code ---> Using cache ---> 3790083599e1 Step 5/9 : RUN pip3 install virtualenv ---> Using cache ---> ddc61851cc43 Step 6/9 : RUN virtualenv /code ---> Using cache ---> fa9028959057 Step 7/9 : ADD requirements.txt /code/ ---> a4b2b341f4f6 Step 8/9 : RUN python -m … -
signup as multiple user
The use case of my application is I will have different kinds of user. They are: Agent Agency Manufacturer They have their own kinds of attributes. 1 User 2 Agent ID FirstName MiddleName LastName DOB Sex Address: City Street Country Mobile Number Organization 3 Agency ID Name Address: City Street Country Contact Number (Multiple numbers can be added) Email VAT/PAN Number 4 Manufacturer ID Name Address: City Street Country Contact Number (Multiple numbers can be added) Email VAT/PAN Number [ Note: Agency have agents. Manufacturer could be associated with the agency or could have agents directly. ] For this, I have designed my model in such a way class Agency(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField( max_length=200, blank=False, null=False) city = models.CharField(max_length=150, blank=False, null=False) street = models.CharField(max_length=150, blank=True, null=True) country = models.CharField(max_length=150, blank=True, null=True) mobile_number = PhoneNumberField() email = models.EmailField(blank=False, null=False) vat_number = models.CharField(max_length=40, blank=False, null=False) agent/models.py class Agent(models.Model): SEX_CHOICE = ( ('male', 'Male'), ('female', 'Female'), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) agencies = models.ForeignKey( Agency, related_name="agents", on_delete=models.CASCADE) manufacturers = models.ForeignKey( Manufacturer, related_name="agents_manufacturer", on_delete=models.CASCADE, blank=True, null=True) first_name = models.CharField( max_length=120, blank=False, null=False) middle_name = models.CharField( max_length=120, blank=True, null=True) last_name = models.CharField( max_length=120, blank=False, null=False) date_of_birth = models.DateField(blank=True, null=True) sex = … -
Django's assertQuerysetEqual() method failing despite the two query sets printing out the same in the shell?
I have a Family and a Session with a one-to-many relationship, such that an instance family has a session_set. Further, the Session has a session_number field, which is an integer. I have two instances of Family, family1 and family2, such that if I print out their session_set.order_by('session_number') in the ipdb debugger I get that they look exactly the same: ipdb> family1.session_set.order_by('session_number') <QuerySet [<Session: Welcome>, <Session: First-Time Parents: The Basics of Birth>, <Session: Initial Postpartum Lactation>, <Session: Sleep Techniques for New Babies>, <Session: Breastfeeding Preparation>, <Session: Newborn Care Basics>, <Session: Easing the Transition Back to Work>, <Session: Preparing for Parenting>, <Session: Decoding Baby Cues>, <Session: Postpartum Doula Support>, <Session: First-Time Parents: Birth Prep Q&A>, <Session: Postpartum Lactation Follow-Up>, <Session: Sleep Training for 4 Months & Beyond>, <Session: Mental Wellness in Pregnancy>, <Session: Infant CPR>, <Session: Prenatal Pelvic Physical Therapy>, <Session: Prenatal Massage>]> ipdb> family2.session_set.order_by('session_number') <QuerySet [<Session: Welcome>, <Session: First-Time Parents: The Basics of Birth>, <Session: Initial Postpartum Lactation>, <Session: Sleep Techniques for New Babies>, <Session: Breastfeeding Preparation>, <Session: Newborn Care Basics>, <Session: Easing the Transition Back to Work>, <Session: Preparing for Parenting>, <Session: Decoding Baby Cues>, <Session: Postpartum Doula Support>, <Session: First-Time Parents: Birth Prep Q&A>, <Session: Postpartum Lactation Follow-Up>, <Session: … -
Modifying CSS on django-autocomplete-light 3.1.3
I am currently learning Django Framework with django-autocomplete-light 3.1.3 and i can't find any way to change the css of a input field. In there documentation it is written that we can create our own HTML template de deal with the data but can we just change a little bit the css of an input box ? I've try to add my own classes to the element before creation with widget-tweaks but every styling attribute is being cancel by the default of django-autocomplete-light. I really just want to set the size of the box to 100% of the parent element and I've been stuck here for 2 days... Thanks a lot -
Django - How to Validate Data by Name
I have a formset that I recently added an autocomplete text box with jQuery in one of the fields. The autocomplete is a text box that auto completes text based on the product names. Since it is a text field and not a select field like I had before, I need to type in the PK in order for the form to actually validate correctly. I tried adding a custom cleaning function that queries the database by the entered name and outputs the correct object, but django validation seems to not even run my cleaning, and rejects the form before my cleanign function can even run. Please forgive some of the code here that doesn't seem to make much sense, I'm new. Any help is greatly appreciated! If it helps I included my code below. views.py def create_orderproduct_view(request, pk=None): order_list = [] order_number = get_object_or_404(Order, pk=pk) OrderProductFormSet = formset_factory(OrderProductForm) if request.method == 'POST': formset = OrderProductFormSet(request.POST) for x in formset: if x.is_valid() and 'Product_ID' in x.cleaned_data: x.save() else: return HttpResponseRedirect(reverse('orderproduct', kwargs={'pk':pk})) else: formset = OrderProductFormSet() return render(request, 'create_orderproduct.html', {'formset': formset}) forms.py class OrderProductForm(ModelForm): class Meta: model = OrderProduct exclude = ('ID',) widgets = { 'Product_ID' : AutoCompleteWidget() } def clean_Product_ID(self): … -
How to get all the related fields from a query set in Django?
I have two models, Session and SessionType which have a many-to-one relationship. There is also a Family foreign key on Session, like so: from django.db import models class SesssionType(models.Model): pass class Session(models.Model): session_type = models.ForeignKey('SessionType') family = models.ForeignKey('Family') For a certain instance family of Family, I have several Session objects in the session_set: ipdb> family.session_set.all() <QuerySet [<Session: Welcome>, <Session: Breastfeeding Preparation - Timothy Anderson>, <Session: First-Time Parents: The Basics of Birth>, <Session: Initial Postpartum Lactation>, <Session: Sleep Techniques for New Babies>, <Session: Breastfeeding Preparation>, <Session: Newborn Care Basics>, <Session: Easing the Transition Back to Work>, <Session: Preparing for Parenting>, <Session: Decoding Baby Cues>, <Session: Postpartum Doula Support>, <Session: First-Time Parents: Birth Prep Q&A>, <Session: Postpartum Lactation Follow-Up>, <Session: Sleep Training for 4 Months & Beyond>, <Session: Mental Wellness in Pregnancy>, <Session: Infant CPR>, <Session: Prenatal Pelvic Physical Therapy>, <Session: Prenatal Massage>]> I would like to get a queryset containing the SessionTypes of these Sessions, similar to the following list: ipdb> [session.session_type for session in family.session_set.all()] [<SessionType: Welcome>, <SessionType: Breastfeeding Preparation>, <SessionType: First-Time Parents: The Basics of Birth>, <SessionType: Initial Postpartum Lactation>, <SessionType: Sleep Techniques for New Babies>, <SessionType: Breastfeeding Preparation>, <SessionType: Newborn Care Basics>, <SessionType: Easing the Transition Back to … -
django rest fileupload with link returned
I was searching through stackoverflow for example of working fileupload APIView (using DRF of latest versions), I've already tried with many different code samples but none worked (some of them are deprecated, some - isn't what i want) I have these models: class Attachment(models.Model): type = models.CharField(max_length=15, null=False) attachment_id = models.CharField(max_length=50, primary_key=True) doc = models.FileField(upload_to="docs/", blank=True) I don't wanna use forms and anything else but rest parsers I want to get POST'ed fields (for example name) in future I believe the solution is easy but this doesnt work class FileUploadView(APIView): parser_classes = (FileUploadParser,) def post(self, request): file_obj = request.FILES doc = Attachment.objects.create(type="doc", attachment_id=time.time()) doc.doc = file_obj doc.save() return Response({'file_id': doc.attachment_id}, status=204) -
Self Referencing Symmetrical Many to Many Django Model in Admin or View
How do you get the other side of a symmetrical self reference in a M2M django model? Say we are making a parts catalog, and we have lots of Parts and we want to have an Interchange to show which parts can be used in place of another: class Part(models.Model): name = models.CharField(max_length=300) number = models.CharField(max_length=200, default 'because numberphiles like more ids') … interchanges = models.ManyToManyField("self", through='Interchange', symmetrical=False, # + sign per http://charlesleifer.com/blog/self-referencing-many-many-through/ related_name="interchanges_to+", # through_fields per docs through_fields=('reference', 'interchange') ) # per this http://charlesleifer.com/blog/self-referencing-many-many-through/ def add_interchange(self, part, symm=True): interchange = models.Interchange.objects.get_or_create( reference_part=self, interchange_part=part) if symm: # avoid recursion by passing `symm=False` part.add_interchange(self, False) return interchange def remove_interchange(self, part, symm=True): models.Interchange.objects.filter( reference_part=self, interchange_part=part).delete() if symm: # avoid recursion by passing `symm=False` part.remove_interchange(self, False) def get_interchanges(self): return ", ".join([str(p) for p in self.interchanges.filter(interchange_part__reference=self)]) def get_references(self): return …? # This is where I don't know how to get the Parts that are referring to it as being an interchange class Interchange(models.Model): reference = models.ForeignKey(Part, related_name="reference_part") interchange = models.ForeignKey(Part, related_name="interchange_part") # just to confirm we have a M2M table, we will add a foregin key to a User if this interchange has been personally verified confirmed_by = models.ForeignKey(User, null=True, blank=True) # … others … -
runserver command not working
The runserver command doesn't work even though I did everything on this newboston tutorial: https://www.youtube.com/watch?v=CHjXtRrhqxc&index=2&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK And it doesn't exactly indicate that there's no file or anything. it just stays like this for a long time. the command doesn't break either and it doesn't let me input another command.... PS C:\WINDOWS\system32> cd.. PS C:\WINDOWS> cd.. PS C:> cd .\Users PS C:\Users> cd .\murta PS C:\Users\murta> cd .\Desktop PS C:\Users\murta\Desktop> cd .\Murtaza PS C:\Users\murta\Desktop\Murtaza> ls Directory: C:\Users\murta\Desktop\Murtaza Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 7/10/2018 3:34 AM Murtaza -a---- 7/10/2018 3:34 AM 0 db.sqlite3 -a---- 7/10/2018 3:21 AM 554 manage.py PS C:\Users\murta\Desktop\Murtaza> python manage.py runserver