Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: Updating subobject with new route, not partial update to model
I'm trying to create an API object, Roster, which has a list of Members as a subobject on it. However, I do not want to update the subobject by partially updating the Roster object -- instead, I want a route for "add member" and "remove member". Goal: GET /Roster/{ROSTERID} response body: { id: {roster id}, members: # members sub object is read only [ {member subobject}, {member subobject}, ... ], } POST /Roster/{RosterID}/AddMember { {member id}, {member id}, ... } and then a similar thing for removing a member. Note: I want to be able to pass a existing member id in. I don't want to create new members here. What should I be looking for in the docs to be able to add a route to update the member list with a user id, instead of having to pass in the whole user object? serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class RosterSerializer(serializers.ModelSerializer): members = serializers.ListField( child=UserSerializer() ) class Meta: model = Roster fields = ('id', 'name', 'members') depth = 2 app/models.py class Members(User): on_pto = models.BooleanField(default=False) class Roster(models.Model): objects = models.Manager() name = models.CharField(max_length=80, blank=True, default='', unique=True, null='') members = models.ForeignKey( … -
Add data to modelserializer field based on request
Basically what I am looking for is to auto-populate the two fields created_by and last_modified_by based on a fixed value. class SupportingAttachment(models.Model): order = models.ForeignKey(Order,null = True,blank = True) file = models.FileField(upload_to= upload_supporting_attachment, null=True, blank=True) created_by = models.ForeignKey(User,blank = True,related_name = 'support_created_by') created = models.DateTimeField(auto_now_add=True) last_modified_by = models.ForeignKey(User,blank = True,related_name = 'support_modified_by') last_modified = models.DateTimeField(auto_now=True) As of now, as a makeshift solution, I am writing a manual serializer and adding the data by overriding the validate function and calling create. def validate(self, attrs): userid = self.context['request'].user.id x = attrs.update({"created_by": userid, "last_modified_by": userid}) return attrs I want to do this in a ModelSerializer without specifying the fields manually. I am assuming I have to override one of the functions of the ModelViewSet or the CreateAPIView So which function do I override on the View layer to set the user_id on the two fields and pass it to the serializer? Also is this the correct way of doing it? -
Djagno: django.db.utils.InternalError: (1046, u'No database selected')
I'm trying to use Django with mariadb 10.4.8 My settings.py file is as follows: DATABASES = { 'default': { 'NAME:': 'mydb', 'ENGINE': 'django.db.backends.mysql', 'USER': 'staff', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '', } } In init.py: import pymysql pymysql.install_as_MySQLdb() "./manage.py makemigrations" and "./manage.py migrate" yield the same error: File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 210, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 55, in table_names return get_names(cursor) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 50, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/mysql/introspection.py", line 56, in get_table_list cursor.execute("SHOW FULL TABLES") File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in … -
Move record from first Django model to second and then delete it from first
I want to move a record from NewUsers model to PendingUsers model on the button click. After moving, the record should be removed(deleted) from NewUsers model. Here's the models: class NewUser(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, default=1) newuser_name = models.CharField(max_length=50) newuser_company = models.CharField(max_length=100) newuser_mobile = models.CharField(max_length=10) newuser_designation = models.CharField(max_length=50) newuser_image = models.ImageField(upload_to='userprofile_pics/users/', blank=True) def __str__(self): return self.user.email class PendingUsers(models.Model): pendinguser = models.OneToOneField(NewUser, on_delete = models.CASCADE, default=1) def __str__(self): return self.pendinguser.newuser_name On Button click, the code to move the record is: query_user = get_object_or_404(NewUser, id=id) pendingUser = PendingUsers() pendingUser.pendinguser = query_user pendingUser.save() And to delete it from NewUsers: NewUser.objects.filter(id=id).delete() It is successfully moving the record to PendingUsers. But as soon as I'm deleting it from NewUser, it is automatically deleted from PendingUser as well. Can anybody help me out with this about how to achieve this successfully? Do I need to change my PendingUsers model? Thanks in advance! -
How can I get my website "Contact Me" Form to arrive at my Gmail?
I am trying to build a contact me form for my portfolio but I am running into issues. Traceback File "..\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner SMTPSenderRefused at / (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError c17sm3159820ild.31 -gsmtp', 'The_email_I_use_on_form@gmail.com') views.py def index_view(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Send email goes here sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('New Enquiry', message, sender_email, ['to_me@gmail.com']) return HttpResponse("Thanks for contacting, We will be in touch soon!") else: form = ContactForm() return render(request, 'index.html', {'form': form }) Settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PWD') Forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) I went into my settings on Gmail to see if there could be something in the security settings blocking me from receiving the form submissions, I tried changing the security setting that allows access for less secure apps. Should I choose a different email provider or is there a work-around for this? -
How to resolve this No reverse match found in Django when request.user returns a lazy object
here is my urls.py line path('account/<str:username>/<id>/', creating_unilevels, name="CreatingUnilevels") and the button <a href="{% url 'CreatingUnilevels' id=own_account.id username=request.user %}">View Account</a> and on that page there is a own_account=Account.objects.all().get(id=id) how to resolve this error Reverse for 'CreatingUnilevels' with keyword arguments '{'username': <SimpleLazyObject: <User: samuel>>, 'id': ''}' not found. 1 pattern(s) tried: ['account\\/(?P<username>[^/]+)\\/(?P<id>[^/]+)\\/$'] -
DRF POST Image and Text at the same time
This is what my model looks like: class ExampleModel(models.Model): text = models.CharField(max_length=2) image = models.ImageField(upload_to='Thats all set. Dont worry about it.') I have a standard serializer: class ExampleSerializer(serializers.ModelSerializer): class Meta: model = ExampleModel fields = "__all__" And then there's my view: class ExampleView(viewsets.ModelViewSet): queryset = ExampleModel.objects.all() serializer_class = ExampleSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = ExampleSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) What I want to know is a) I'm trying to populate the text and model fields using Python requests. requests.post(url, headers="The tokens(Already taken care of)", "How to put in the body? Where and how do I add the image and text?" b) Is there something I need to change or add in either of these or outside to meet my requirement? Any help is appreciated. Thank you for your time reading this :) -
Django - How to create users with the same username and password?
I would like to ask if there is any way to create a user where the username and password are the same. By default when I try to do it from the administrator I get an error saying that the passwords are the same. Even when I try to add some additional initial in the password does not allow me to save it. Is there a way to do it? -
How to filter last item of child collection?
I'm trying to query all posts that have it's last comment created today || haven't yet had comment. How can I make that kind query filter in Django? Here are my Models class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() class Comment(models.Model): content = models.TextField() post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") created_at = models.DateTimeField(auto_now_add=True) -
I encountered "Exception while resolving variable 'redirect_to'" when running a django application
I made a simple application with localization (django 2.2.4). I built a way to change language and used the exact code in https://docs.djangoproject.com/en/2.2/topics/i18n/ when I run it locally using python manage.py runserver it works fine but when I run it through nginx and gunicorn on a different ubuntu server I get Traceback (most recent call last): File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'redirect_to' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): AttributeError: type object 'RequestContext' has no attribute 'redirect_to' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'redirect_to' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: <unprintable VariableDoesNotExist object> ``` There was a python version difference but after upgrading to the same exact versions of python (python3.7) same error occurs. Code that's throwing the exception {% load i18n %} … -
How do i fix No function matches the given name and argument types. You might need to add explicit type casts
already_transferred = Transfer.objects.all().filter(transferred_by=request.user, account_id=id).aggregate(total=Coalesce(Sum('amount'), 0)) and the server is giving this error function sum(text) does not exist LINE 1: SELECT COALESCE(SUM("API_insidetransfer"."amount"), 0) AS "a... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. here is my model class Transfer(models.Model): transferred_by = models.CharField(max_length=120) account_id = models.CharField(max_length=120) amount = models.CharField(max_length=120, default=0) created_on = models.DateTimeField(auto_now=True) how can i fix this? -
Covert two tuples into Dict with one key: multiple values
I have two tuples, and I want to be able to convert them into dic with one key and multiple values. This will be written in python. one_tup = [('A',1),('B',2),('C',3)] two_tup = [('A',2),('B',4),('D',4)] dic = {'A':(1,2),'B':(2,4),'C':(3),'D':(4)} I was wondering if there's a faster and more efficient to do it without looping through each indexes and comparing it and then storing it. Because that's what I'm planning to do but I think it will take really long time given that I have about a couple thousand elements in each array. -
How can I set manage=False for django simple history table
I'm using django-simple-history for my model. I am deleting a field on the model but setting the meta property managed to False. However, this does not translate to the simple history table. Is there a way to achieve this? -
Connection reset by peer after several minutes in django celery
I have deployed a celery app for production but it disconnects from rabbitmq after 5 to 10 minutes after that no response is given from server The error code is: [Errno 104] Connection reset by peer this is my celery.py file django project: import os from celery import Celery from parrot_server import settings BROKER_URL = 'amqp://parrot_user:Alireza@1234@localhost:5672/parrot' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parrot_server.settings') app = Celery('parrot_server', broker=BROKER_URL, backend='rpc://') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request:{0!r}'.format(self.request)) It has 8 functions that 2 of them is called with apply_async function. I look forward to your answer. Thank you -
django-rest-framework Overriding create function not working on ModelSerializer
I want to insert only new data into my database. In case, the data with the same primary key is already in the database, I want to ignore it and not raise an exception. However, the default ModelSerializer's create function seems to raise and exception if the value already exists in the table. So, I am trying to solve this problem by overriding the ModelSerializer's create() function. Here's my code: serializers.py class UsrPlaceMapSerializer(serializers.ModelSerializer): class Meta: model = UsrPlaceMap fields = '__all__' def create(self, validated_data): place_id = validated_data.get("ggl_plc_id") place_map = UsrPlaceMap.objects.filter(ggl_plc_id=place_id) print("USRMAP INIT") if place_map is not None: print("USRMAP NOT NONE") return place_map place_map = UsrPlaceMap.objects.create(ggl_plc_id=place_id, state=validated_data.get("state"), cty_nm=validated_data.get("cty_nm"), cntry=validated_data.get("cntry")) print("USRMAP CREATED") return place_map models.py class UsrPlaceMap(models.Model): cty_nm = models.CharField(max_length=500) state = models.CharField(max_length=200, blank=True, null=True) cntry = models.CharField(max_length=500) ggl_plc_id = models.CharField(primary_key=True, max_length=500) class Meta: managed = False db_table = 'usr_place_map' and I am calling the seralizer instance's save method using this: instance = UsrPlaceMapSerializer(data=data, many=True) instance.save() However, I get an error if I try to submit values already in the table: { "ggl_plc_id": [ "usr place map with this ggl plc id already exists." ] } } The print statements on the overriddent create() don't print anything either. So, I am guessing … -
When I try to login to Django admin via https, python server was closed without any error
I follow the Official Django tutorial, but I´m stucked in the point where I should login into Admin page. I can fill name and password, but after hit Log in button, python development server ends. I´m running them using this command python manage.py runserver 0.0.0.0:3000 I´m running Linux container on Codeanywhere using Python 3.7 and Django 3.1. Only output I get is: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 04, 2019 - 16:14:47 Django version 3.1, using settings 'buky.settings' Starting development server at http://0.0.0.0:3000/ Quit the server with CONTROL-C. [04/Oct/2019 16:14:48] "GET /admin/ HTTP/1.1" 302 0 [04/Oct/2019 16:14:49] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1916 [04/Oct/2019 16:14:49] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [04/Oct/2019 16:14:49] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [04/Oct/2019 16:14:49] "GET /static/admin/css/responsive.css HTTP/1.1" 200 18052 [04/Oct/2019 16:14:49] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [04/Oct/2019 16:14:50] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [04/Oct/2019 16:14:50] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [04/Oct/2019 16:14:57] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 My urls.py is like in tutorial: urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] What can be wrong? Thanks Alex -
Access webhook information from Dialogflow in Django
I have configured Dialogflow to make a POST request after a name is asked. When I view the information in an online request viewer I can see the information I want in the Query strings section: > { "responseId": "045c0d0b-7b5b-448e...", > "queryResult": { > "queryText": "rob", > "parameters": { > "last-name": "lastname", > "given-name": "Rob" > }, In Django however, I cannot find this information. I tried to save the full request and request.META in the database. The received request on my server looks like: {'QUERY_STRING': '', 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/json', 'CONTENT_LENGTH': '5323', 'REQUEST_URI': '/folder', 'PATH_INFO': '/folder', 'DOCUMENT_ROOT': '/home/info/domains/mysite.info/private_html', 'SERVER_PROTOCOL': 'HTTP/1.1', 'HTTPS': 'on', 'REMOTE_ADDR': '64.233.172.250', 'REMOTE_PORT': '53451', 'SERVER_PORT': '443', 'SERVER_NAME': 'mysite.info', 'HTTP_CONTENT_TYPE': 'application/json', 'HTTP_HOST': 'www.mysite.info', 'HTTP_CONTENT_LENGTH': '5323', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_ACCEPT': '/', 'HTTP_USER_AGENT': 'Google-Dialogflow', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,br', 'wsgi.input': , 'wsgi.file_wrapper': , 'wsgi.version': (1, 0), 'wsgi.errors': <_io.TextIOWrapper name=2 mode='w' encoding='UTF-8'>, 'wsgi.run_once': False, 'wsgi.multithread': False, 'wsgi.multiprocess': True, 'wsgi.url_scheme': 'https', 'uwsgi.version': b'2.0.18', 'uwsgi.node': b'server.mysite.info', 'SCRIPT_NAME': ''} I use Nginx with Uwsgi How do I access the full information in Django? -
Two types of users account in Django
I've form in HTML: <form action=""> <select> <option>Freelancer</option> <option>Employer</option> </select> <input type="text" placeholder="Name"> </form> When user will send the form I want check what account type user has selected. If user selected a Freelancer account I want save him to Freelancer model. If he selected Employer to Employer model. How to use this in forms.py when the class Meta would has two models? -
How to immediately return to my site after PayPal payment
I am creating a website through which people can buy tickets via paypal – I want to send a confirmation email once the payment is complete. So, I turned on auto return in paypal and set it up so that the email would be sent as soon as 'notify_url' was received. However, I only get this notification once it redirects from paypal to the website – I'm afraid that the users will click off the page before it is redirected and before the email is sent. Is there a way to make the process faster, i.e allow me to send the email as soon as the payment is confirmed? -
What could be causing this error in this file but not anywhere else?
I have an HTML file that serves as the layout and it's rendered with python. I keep getting the error 'str' object has no attribute 'field' And it says it comes from my tag, which works on every other page. This is not something I created but I'm rather learning to be able to use it as a newer web developer. My html file looks like this {% extends "ops/base.html" %} {% load core_tags %} {% block page_title %}Ops{% endblock %} {% block main %} <form id="create-w-form" action="{% url "ops:enter" %}" method="POST" class="form-horizontal"> {% csrf_token %} <div class="row"> <div class="form-group col-xs-12"> {% standard_input create_w_form.em_num %} </div> </div> <div class="row"> <div class="col-xs-12 text-right"> <div class="btn btn-primary ajax-submit-btn">Submit</div> </div> </div> </form> {% endblock main %} If I erase the line that contains {% standard_input create_w_form.em_num %} It will render the page, otherwise it won't and I'll get the error mentioned above. -
Django-rest , return customized Json
Hi i'm having this code for a backend query class HexList(generics.ListCreateAPIView): serializer_class = HexSerializer def get_queryset(self): hex_list = Hex.objects.filter(game_id=self.kwargs['pk']) return hex_list That returns this Json: [ { "id": 2, "game_id": 0, "position": 3, "resource": "NO", "token": 0 }, { "id": 3, "game_id": 0, "position": 5, "resource": "WO", "token": 0 }, { "id": 4, "game_id": 0, "position": 6, "resource": "BR", "token": 4 } ] What i would like it to return is the same data, but with in the shape of a Json like something like this: "hexes":[ { "id": 2, "game_id": 0, "position": 3, "resource": "NO", "token": 0 }, { "id": 3, "game_id": 0, "position": 5, "resource": "WO", "token": 0 }, { "id": 4, "game_id": 0, "position": 6, "resource": "BR", "token": 4 } ] } I've tried this : class HexList(generics.ListCreateAPIView): serializer_class = HexSerializer def get_queryset(self): hex_list = Hex.objects.filter(game_id=self.kwargs['pk']) return Response({'hexes': hex_list}) And i'm getting a ContentNotRenderedError Exception What should i do? Thanks in advance -
RuntimeWarning: DateTimeField received naive datetime while time zone support is active
pst = pytz.timezone('US/Pacific') start_time = pst.localize(datetime.strptime(data_post['startTime'], fmt)) if 'endTime' in data_post: end_time = pst.localize(datetime.strptime(data_post['endTime'], fmt)) I got the below Warning /venv/local/lib/python2.7/site-packages/django/db/models/fields/init.py:1393: RuntimeWarning: DateTimeField DashboardTestResult.start_time received a naive datetime (2019-09-27 00:00:00) while time zone support is active. RuntimeWarning) -
Sending api_key in header while url has parameters
For security reasons, I designed my django app to accept api_key in url header (in Authorization). So to call the service: curl -H "Authorization: 123456789ABC" http://127.0.0.1:8000/api:v1/live but I don't know how to send other url parameters: curl -H "Authorization: 123456789ABC" http://127.0.0.1:8000/api:v1/live?from=A&output=pdf it gets the api_key but not the parameters and gives this error in command prompt: {"api_key": "123456789ABC"}'output' is not recognized as an internal or external command, operable program or batch file. -
How to filter out profiles that have an appointment (foreign key relationship)?
I am attempting to retrieve all Profile objects that do not have an Appointment scheduled. An Appointment object may or may not have a Profile associated with it (either being an empty time slot or a booked appointment). I haven't tried anything yet, because I don't know where to start from here. users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=30) objects = managers.ProfileManager() booking/models.py class Appointment(models.Model): profile = models.ForeignKey( 'users.Profile', on_delete=models.PROTECT, unique=False, null=True, ) massage = models.CharField( default=None, max_length=2, choices=[ ('SW', 'Swedish'), ('DT', 'Deep Tissue'), ], null=True, ) date_start = models.DateTimeField() date_end = models.DateTimeField() black_out = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) objects = AppointmentManager() users/managers.py def search_by_name(self, request): first_name = request.GET.get('first-name', '') last_name = request.GET.get('last-name', '') profiles = [] max_results = 5 if first_name == '' and last_name == '': return (True, {'profiles': profiles}) elif last_name == '': profiles = models.Profile.objects \ .filter(user__first_name__icontains=first_name)[:max_results] elif first_name == '': profiles = models.Profile.objects \ .filter(user__last_name__icontains=last_name)[:max_results] else: profiles = models.Profile.objects \ .filter(user__first_name__icontains=first_name) \ .filter(user__last_name__icontains=last_name)[:max_results] return (True, {'profiles': profiles}) The search_by_name function filters all Profile objects containing first and/or last names, including those with an Appointment scheduled (which I don't want). Any help is appreciated. -
Displaying Django inline formsets for different instances of parent model
I am new to Django and am trying to display an inline formset in my Django application to allow a user to add instances of a child model to its corresponding instance of the parent model. I feel like there is a simple answer but so far I haven't been able to think of or find a solution. My models: class ExerciseName(models.Model): name_of_exercise = models.CharField(max_length=100, default = 'Exercise name', unique=True) def __str__(self): return self.name_of_exercise class SetLogger(models.Model): weight = models.FloatField(default=0) reps = models.FloatField(default=0) date = models.DateField(auto_now=True) exercise_group = models.ForeignKey(ExerciseName, on_delete = models.CASCADE) My forms : class ExerciseNameForm(forms.ModelForm): class Meta: model = ExerciseName fields = ('name_of_exercise', ) Views: def name_list(request): exercise_name = ExerciseName.objects.all() sets = SetLogger.objects.all() exercisename = ExerciseName.objects.get(pk=1) SetLoggerFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',)) if request.method == 'POST': form = ExerciseNameForm(request.POST) formset = SetLoggerFormSet(request.POST, instance=exercisename) if form.is_valid(): form.save(commit=True) else: form = ExerciseNameForm() if formset.is_valid(): formset.save(commit=True) else: formset = SetLoggerFormSet() return render(request, 'gymloggerapp/name_list.html', {'exercise_name': exercise_name, 'form': ExerciseNameForm(), 'sets': sets, 'formset': formset}) So far, this has worked in allowing me to add weight and reps to the first instance of my ExerciseName model (with pk=1), by just displaying the formset in my template. However, I would like to create a formset in this way …