Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I receive an error running pytest on a query set for a proxy model in django
My User model contains the following choices class Roles(models.TextChoices): ACCOUNT_MANAGER = "ACCOUNT_MANAGER", _("Account Manager") CLIENT_MANAGER = "CLIENT_MANAGER", _("Client Manager") ADMIN = "ADMIN", _("Admin") base_role = Roles.ACCOUNT_MANAGER I have then created a proxy model and manager class ACManager(models.Manager): # Ensures queries on the Account Manager model return only Account Managers def get_queryset(self, *args, **kwargs): results = super().get_queryset(*args, **kwargs) return results.filter(role=User.Roles.ACCOUNT_MANAGER) class AccountManager(User): # This sets the user role to Account Manager during record creation base_role = User.Roles.ACCOUNT_MANAGER objects = ACManager() I have the following test @pytest.mark.django_db def test_ac_manager_get_queryset(): # Test setting user roles role = User.Roles.ACCOUNT_MANAGER user = User.objects.create_user(email="test@example.com", password="password123", role=role) # Create an instance of ACManager manager = ACManager() # Call the get_queryset method queryset = manager.get_queryset() # Assert that only users with the ACCOUNT_MANAGER role are in the queryset assert user in queryset assert queryset.count() == 1 When I run the test I get the following error message django.core.exceptions.FieldError: Cannot resolve keyword 'role' into field. Creating users with the different roles works so I am a bit confused as to why this is happening. Any help on resolving this issue would be appreciated. -
Gradual Disk Usage Increase in Django/OpenLiteSpeed on Ubuntu - Seeking Guidance on Identifying and Resolving the Issue
disk usage increased by 1.57 GB in one month I've recently deployed a Django website using the OpenLiteSpeed Ubuntu image on a Hostinger VPS. Over the period from Oct 14th to Nov 14th, I observed a significant 1.57 GB increase in disk space usage, as indicated in the attached image. I'm puzzled by this unexpected growth, as there haven't been any notable changes or additions to the system during this time. I'm using the following : Python 3.10.12 acme==1.21.0 asgiref==3.7.2 attrs==21.2.0 Automat==20.2.0 Babel==2.8.0 bcrypt==3.2.0 blinker==1.4 certbot==1.21.0 certifi==2023.7.22 chardet==4.0.0 charset-normalizer==3.3.0 click==8.0.3 cloud-init==23.3.1 colorama==0.4.6 command-not-found==0.3 ConfigArgParse==1.5.3 configobj==5.0.6 constantly==15.1.0 crispy-bootstrap5==0.7 cryptography==3.4.8 dbus-python==1.2.18 decorator==4.4.2 distlib==0.3.4 distro==1.7.0 distro-info==1.1+ubuntu0.1 Django==4.2.6 django-ckeditor==6.7.0 django-crispy-forms==2.0 django-js-asset==2.1.0 django-mathfilters==1.0.0 django-robots==6.1 filelock==3.6.0 gunicorn==21.2.0 httplib2==0.20.2 hyperlink==21.0.0 idna==3.4 imageio==2.31.5 imageio-ffmpeg==0.4.9 importlib-metadata==4.6.4 incremental==21.3.0 jeepney==0.7.1 Jinja2==3.0.3 josepy==1.10.0 jsonpatch==1.32 jsonpointer==2.0 jsonschema==3.2.0 keyring==23.5.0 launchpadlib==1.10.16 lazr.restfulclient==0.14.4 lazr.uri==1.0.6 MarkupSafe==2.0.1 more-itertools==8.10.0 moviepy==1.0.3 netifaces==0.11.0 numpy==1.26.0 oauthlib==3.2.0 opencv-contrib-python==4.8.1.78 opencv-python==4.8.1.78 packaging==23.2 parsedatetime==2.6 pexpect==4.8.0 Pillow==10.0.1 platformdirs==2.5.1 proglog==0.1.10 psutil==5.9.5 psycopg2==2.9.9 ptyprocess==0.7.0 pyasn1==0.4.8 pyasn1-modules==0.2.1 PyGObject==3.42.1 PyHamcrest==2.0.2 PyICU==2.8.1 PyJWT==2.3.0 pyOpenSSL==21.0.0 pyparsing==2.4.7 pyRFC3339==1.1 pyrsistent==0.18.1 pyserial==3.5 python-apt==2.4.0+ubuntu2 python-debian==0.1.43+ubuntu1.1 python-magic==0.4.24 pytz==2022.1 PyYAML==5.4.1 requests==2.31.0 requests-toolbelt==0.9.1 SecretStorage==3.3.1 service-identity==18.1.0 six==1.16.0 sos==4.5.6 sqlparse==0.4.4 ssh-import-id==5.11 systemd-python==234 tqdm==4.66.1 Twisted==22.1.0 typing_extensions==4.8.0 tzdata==2023.3 ubuntu-advantage-tools==8001 ufw==0.36.1 unattended-upgrades==0.1 urllib3==2.0.6 uWSGI==2.0.22 virtualenv==20.13.0+ds wadllib==1.3.6 zipp==1.0.0 zope.component==4.3.0 zope.event==4.4 zope.hookable==5.1.0 zope.interface==5.4.0 I'm also using PostgreSQL 14.9 Ubuntu 22.04 with OpenLiteSpeed Django Image OpenLiteSpeed 1.7.18 I … -
How to assign the user making the request to a foreign key field in Django models
I'm currently working on a web app similar to discord. I'm trying to set the user who is sending the request to create the server as the owner of the server so that the only thing he wants to enter is details like - name , icon and description. This is my model for server: class Server(models.Model): name = models.CharField(max_length=30) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="server_owner") creation_date = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=250, null=True, blank=True) member = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="servers", through='ServerMember') icon = models.FileField( upload_to=server_icon_upload_path, null=True, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): is_new_server = self._state.adding if is_new_server: super().save(*args, **kwargs) try: member_role = Role.objects.create( name="member", server=self ) server_member = ServerMember.objects.create( user=self.owner, server=self) server_member.role.add(member_role) except Exception as e: print(f"Error creating 'member' role: {e}") if self.id: existing = get_object_or_404(Server, id=self.id) if existing.icon and existing.icon != self.icon: # Delete the old icon existing.icon.delete(save=False) super().save(*args, **kwargs) I've tried to override the perform_create function but it didn't work: class ServerCreateView(generics.CreateAPIView): queryset = Server.objects.all() serializer_class = ServerSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(owner=self.request.user) -
How to work in development with Discord OAuth2 live
I have a django app with Discord OAuth2 authentication live on the deployed site. With all the redirects leading back to the deployed app, what is the procedure for doing development/debugging when I can’t see the progress on the localhost? Thanks! -
String Reference not working in model container when using Djongo models
I want to reference CartCustomizationCategory class inside CartCustomization, but the CartCustomizationCategory class is defined below CartCustomization class. I can't change the order of the classes because they are used inside each other. So, I used string reference which works with Django models, but isn't working with Djongo models. Is there a python way to solve this, or I can use something else for this. class CartCustomization(models.Model): class Meta: abstract = True id = models.CharField(max_length=300) name = models.CharField(max_length=100) quantity = models.IntegerField() price = models.IntegerField() customization_categories = models.ArrayField(model_container = "CartCustomizationCategory") class CartCustomizationCategory(models.Model): class Meta: abstract = True id = models.CharField(max_length=300) name = models.CharField(max_length=100) customizations = models.ArrayField(model_container=CartCustomization) class CartItem(models.Model): class Meta: abstract = True id = models.CharField(max_length=300) name = models.CharField(max_length=100) parent_item_id = models.CharField(max_length=12) quantity = models.IntegerField() price = models.IntegerField() customization_categories = models.ArrayField(model_container=CartCustomizationCategory) This is the Traceback Stack Traceback (most recent call last): File "D:\CRUV\craver-backend\craver\manage.py", line 22, in <module> main() File "D:\CRUV\craver-backend\craver\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\CRUV\craver-backend\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\CRUV\craver-backend\venv\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "D:\CRUV\craver-backend\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\CRUV\craver-backend\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "D:\CRUV\craver-backend\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rudra\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, … -
Persistant connections doesn't work properly after migrating to Django 4.2
after migrating from django 3.2 to 4.2 I've noticed persistant connections doesn't work the same for the new version. I'm using CONN_MAX_AGE=20 setting For Django 3.2 I can see that oracle doesn't create new sessions in v$session table on each request. But in Django 4.2 there is new session created for each request even though we haven't changed anything in the database connections. STACK: python 3.9.16 django 4.2.5 oracle 19.16.0 Any ideas how to recreate the old behaviour on the new version of Django? -
websocket disconnects after hadnshaking Django Channels
I am coding a real time chat using django and channels My code consumers.py: class ChatConsumer(WebsocketConsumer): def connect(self): room_hash = self.scope["url_route"]["kwargs"]["room_hash"] #self.room_group_name = self.scope["url"]["kwargs"]["hash"] self.send(text_data = json.dumps({ 'type':'room_hash', 'hash': room_hash })) chat_room = Room.objects.get(hash = hash) print(chat_room) self.accept({ 'type': 'websocket.accept' }) def disconnect(self): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print("Message is "+message) Routing from django.urls import path from . import consumers ws_urlpatterns = [ path('ws/<str:room_hash>/', consumers.ChatConsumer.as_asgi()) ] template script: {{room.hash|json_script:"json-roomhash"}} <script type = "text/javascript"> let room_hash = JSON.parse(document.getElementById("json-roomhash").textContent) let url = `ws://${window.location.host}/ws/${room_hash}/` const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) let hash = data.hash console.log(hash) } const form = document.querySelector("#form") console.log(form) form.addEventListener('submit', (e)=>{ e.preventDefault() let message= e.target.message.value chatSocket.send(JSON.stringify({ 'message':message })) form.reset() }) </script> And it throws me this error when i try to connect to websocket by hash of the room. raise ValueError("Socket has not been accepted, so cannot send over it") ValueError: Socket has not been accepted, so cannot send over it Exception inside application: Socket has not been accepted, so cannot send over it -
How do I create an emptry LineString in GeoDjango
I am having a problem with the latest version of the GeoDjango extensions in Django version 4.2.6 when I create an empty LineString. The same code is behaving differently than it did in version 4.0.10. The default seems to have switched to creating a Geos object with 3-dimensions rather than the previous 2-dimensions. The following code returns a different WKT object depending on the version of Django I am using. from django.contrib.gis.geos import LineString ls = LineString() ls.wkt This is returning a 3-dimensional object "LINESTRING Z EMPTY". Running exactly the same code on Django 4.0.10 creates a 2-dimension object "LINESTRING EMPTY". Is there anything obvious I am doing wrong? I am also running a slightly newer version of geos-3.12.0 versus 3.11.2 but I cannot see anything is both sets of release notes that describe this change in behaviour. -
JavaScrip Gmail API code not working on Django template
im testing a simple Gmail API integration to my django app and its not working. Im trying to migrate the javascript example from the Google docs website, and migrate it to my django proyect, yet doesnt work, and when trying to use the EXACT SAME CODE with the server initialization provided in the docs, it works, why is not working the Gmail API on my django project?? What ive tested? The error happens to be on the callback of the tokenClient object, is never called and reached, perse because of a code problem. It indeed opens the prompt of the Google Sign-In in both codebases (django and google recomended), but after that is supposed that the callback is going to be called, but is not (on django). function handleAuthClick() { tokenClient.callback = async (resp) => { if (resp.error !== undefined) { // code NEVER REACHED on my django template throw (resp); } document.getElementById('signout_button').style.visibility = 'visible'; document.getElementById('authorize_button').innerText = 'Refresh'; await listLabels(); }; if (gapi.client.getToken() === null) { // Prompt the user to select a Google Account and ask for consent to share their data // when establishing a new session. tokenClient.requestAccessToken({prompt: 'consent'}); } else { // Skip display of account chooser … -
Async function isn't behaving as intended in Django websocket consumer
async def handle_round(self, word_to_guess): # Mark the current active round as inactive if self.current_round: self.current_round.is_active = False await database_sync_to_async(self.current_round.save)() # Create a new round await database_sync_to_async(Round.objects.create)( word=word_to_guess, time_left=self.room.guess_time, room=self.room, ) self.current_round = await self.get_current_round() print('Current round', self.current_round) await self.update_game_state() await self.handle_timer() # Handle timer async def handle_timer(self): print('handle_timer') if self.room and self.player and self.current_round: # Broadcast the initial timer value to the room await self.channel_layer.group_send( self.room_group_name, { 'type': 'update_timer', 'time': self.current_round.time_left, } ) async def update_timer(self,event): print('update_timer') asyncio.ensure_future(self.update_timer_helper(event)) # Separate coroutine to update the timer async def update_timer_helper(self, event): time_remaining = self.current_round.time_left while time_remaining >= 0: # Broadcast the timer updates to the room, including the new player await self.send(text_data=json.dumps( { 'type': 'timer_update', 'value': time_remaining, } )) if time_remaining == 0: break # Sleep for 1 second before the next update await asyncio.sleep(1) # Decrement the time remaining self.current_round.time_left -= 1 await database_sync_to_async(self.current_round.save)() time_remaining -= 1 I'm having some trouble with my django consumer for a game I'm making. When calling handle_timer in handle_round() from the loop in start_game(), it isn't called until after the loop finishes. Why? -
Request Issue With Django On AWS
I have recently been working on developing an application that can answer questions from documents. It has been going well so far, as the project itself works locally, and answers questions with great accuracy. However, when I brought this project over to AWS, it has incredible difficulty answering the questions, always failing with a 504 error. I am receiving the below error from the web.stdout logs, but I am not sure if this is why its failing, or what is going on. https://i.stack.imgur.com/c2zPq.png The project is programmed in python with a Django front end, and Elastic Beanstalk is being used for deployment. The project can be found here: https://github.com/Nessbound/asop_chatbot/tree/stack-overflow I'm not exactly sure where the error is, so I am posting the whole project. Thanks in advance for any help! -
How would I handle another POST request on my site
Hello in my login site I have a form that sends a POST request on submit. this is how I handle the forms POST request in my view def SignUp(request): if request.method == 'POST': stuff goes here else: form = SignUpForm() return render(request, "index.html", {"form": form}) now in my javascript i want to add another POST request that'll check if the current username within a certain is already taken. I made it and sent the POST to my current view where both this POST request will be handled along with the form POST request. what ends up happening is that SignUp() keeps handling both the POST requests. How do I handle two POST requests in one view? Is there a better way to do all of this? (i would preferably want to stay on this url) tried to read about any way to differentiate between POST requests but found nothing. (i started learning django just a few days ago and im completely lost trying to make this work) -
Django / Pytest / Splinter : IntegrityError duplicate key in test only
I know it's a very common problem and I read a lot of similar questions. But I can't find any solution, so, here I am with the 987th question on Stackoverflow about a Django Integrity error. I'm starting a Django project with a Postgres db to learn about the framework. I did the classic Profile creation for users, automated with a post_save signal. Here is the model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.TextField(max_length=280, blank=True) contacts = models.ManyToManyField( "self", symmetrical=True, blank=True ) And this is the signal that goes with it : def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() post_save.connect(create_profile, sender=User, dispatch_uid="profile_creation") The project is just starting, and for now I only create users in the admin view. With the post_save signal, it's supposed to create a Profile with the same form. Here is the admin setup : class ProfileInline(admin.StackedInline): model = Profile class UserAdmin(admin.ModelAdmin): model = User list_display = ["username", "is_superuser"] fields = ["username", "is_superuser"] inlines = [ProfileInline] I'm using pytest and Splinter for my test, and this is the integration test that don't work : @pytest.mark.django_db class TestAdminPage: def test_profile_creation_from_admin(self, browser, admin_user): browser.visit('/admin/login/') username_field = browser.find_by_css('form input[name="username"]') password_field = browser.find_by_css('form input[name="password"]') username_field.fill(admin_user.username) … -
Django: General Questions about API views
I am working on a project and I have a front-end in React which makes some basic CRUD axios calls to the django server. I am trying to figure the best way to administer my django views to receive and process these requests. I understand this very much depends on the how my application needs to function. But at the moment, I am just trying to create simple views (which joins a couple of data models together and returns) This is the approach in action: class Hero(models.Model): character = models.ForeignKey( Card, on_delete=models.CASCADE, related_name="class_id", null=True ) weapon = models.ForeignKey( Card, on_delete=models.CASCADE, related_name="weapon_id", null=True ) player = models.OneToOneField(Player, on_delete=models.PROTECT, null=True) class Game(models.Model): hero1 = models.ForeignKey( Hero, on_delete=models.PROTECT, related_name="hero1_id", null=True ) hero2 = models.ForeignKey( Hero, on_delete=models.PROTECT, related_name="hero2_id", null=True ) hero3 = models.ForeignKey( Hero, on_delete=models.PROTECT, related_name="hero3_id", null=True ) hero4 = models.ForeignKey( Hero, on_delete=models.PROTECT, related_name="hero4_id", null=True ) and then I would write a view as such, class GameHeroView(APIView): serializer_class = HeroSerializer def get(self, request, id=0): game_id = request.query_params.get("id") if game_id is None: game_id = id # Create an empty list for serialized data serialized_data = [] sql = ( " \ SELECT gh.* \ FROM gauntlet_game gg, \ gauntlet_hero gh \ WHERE gg.id = " … -
Django - Update database entry if it exists or insert new entry combining two tables together (models)
I have an app that merges two excel files into one (data from Students and data from their subjects' grades). Therefore, one table for students and one for the grades. Here is what my models.py looks like: models.py class Students(models.Model): study_program = models.CharField(max_length=40, blank=True, null=True) registration_number = models.IntegerField(blank=True, null=True) id_number_1 = models.FloatField(blank=True, null=True) name = models.CharField(max_length=100, null=True) surname = models.CharField(max_length=100) nationality = models.CharField(max_length=10) . . (many more columns here) . def __str__(self): return self.name + ' ' + self.surname class StudentGrades(models.Model): student = models.ForeignKey(Students, default=None, on_delete=models.CASCADE) subject = models.CharField(max_length=40) # Μάθημα (Subject) subject_code = models.CharField(max_length=20, ) # Κωδ. μαθ. (Subject Code) student_class = models.CharField(max_length=40, ) # Τμήμα Τάξης (Class) . . (many more columns here) . def __str__(self): return self.subject + ' ' + self.student.name + ' ' + self.student.surname The primary key that connects these two is the registration number of the student. Each student has a unique registration number. On the views.py I've created two functions that (one for each table) that saves the excel files' content to the database. Here is the views.py: views.py This function saves the students records to the database. If the student's row has a registration number that is a match, it updates … -
Django Rest Framework - How to store a GIF image
I am working on a Django project using Django Rest Framework, and I am facing an issue related to storing and processing GIF images in one of my models. class GiftCardPlan(model.Model): # ... other fields ... image = ProcessedImageField(null=True, blank=True, upload_to=giftcardplan_image_path, processors=[SmartResize(480, 290, upscale=False)], options={'quality': 100}) serializer class GiftCardPlanSerializer(serializers.ModelSerializer): image = Base64ImageField(read_only=True) I want to handle GIF images properly within the GiftCardPlan model. I've tried different approaches, but none seem to work as expected. My current implementation loses GIF animation during processing. -
Getting error "Unknown command: 'load_data'. Did you mean loaddata?" while running "python manage.py load_data"
While running python manage.py load_data I am getting an error Unknown command: 'load_data'. Did you mean loaddata?. Below I have attached the folder structure where load_data.py is present. I also tried running python -m store_monitor.management.commands.load_data but still not working. -
getting Permission denied: '/vol/web/media' when trying to create file in my django application
Here is my dockerfile. FROM python:3.9-alpine3.13 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./electron /electron COPY ./scripts /scripts WORKDIR /electron EXPOSE 8000 RUN apk add --no-cache --virtual .build-deps gcc musl-dev RUN python3.9 -m venv /py && \ /py/bin/pip install --upgrade pip setuptools wheel && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .temp-deps \ build-base postgresql-dev musl-dev linux-headers && \ mkdir -p /vol/web/media && \ <----- The problem is located at this level /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home ozangue && \ chown -R ozangue:ozangue /vol && \ chmod -R 755 /vol && \ chown -R ozangue:ozangue /vol/web/media && \ chmod -R 755 /vol/web/media && \ chmod -R +x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER ozangue CMD ["run.sh"] I cannot save a model containing a file. Because this file must be saved in /vol/web/media The part of the code that poses a problem is as follows (in views.py): file = request.FILES["excel_file"] file_obj = FileModelXSL(file=excel_file) fichier_obj = fichier_obj.save() in settings.py STATIC_URL = '/static/static/' MEDIA_URL = '/static/media/' MEDIA_ROOT = '/vol/web/media' STATICFILES_DIRS = (BASE_DIR / 'static',) STATIC_ROOT = '/vol/web/static' When I build the container, I don't get any errors but I have the impression that /vol/web/media: mkdir … -
AssertionError: PermissionDenied not raised
I'm new to testing in django , i'm trying to test a view that raises PermissonDenied when the test user is not authenticated , this is part of the view code @login_required def files_raw(request): user = request.user # Get the current user # Initialize the base SQL query base_sql_query = "" # Check user conditions if user.is_superuser: # If the user is a superuser, they can access all data, so no need to change the base query. base_sql_query = "SELECT * FROM files" elif user.groups.filter(name='RNA').exists(): # User is in the 'RNA' group, update the base query to include 'RNA'. base_sql_query = "SELECT * FROM files WHERE files.Sample_id LIKE '%RNA'" elif user.groups.filter(name='WGS').exists(): # User is in the 'WGS' group, update the base query to exclude 'RNA'. base_sql_query = " SELECT * FROM files WHERE files.Sample_id NOT LIKE '%RNA'" else: # If none of the conditions are met, raise a PermissionDenied with a custom error message. print("DEBUG: Conditions not met for user:", user) raise PermissionDenied("You are not authorized to access this data") # Execute the raw SQL query with connection.cursor() as cursor: cursor.execute(base_sql_query) # Initialize an empty list to store the results files = [] # Iterate over the cursor to fetch … -
why i can't run my Django project with : python manage.py runserver
I encountered an error: File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'C:\Users\Youssef\Documents\Hello_Django\import_data' However, I do not have a file named "import_data," and I am not using the path 'C:\Users\Youssef\Documents\Hello_Django\import_data.' This is where I had my previous project, which I have since deleted. i tried this : python manage.py runserver i expect the localhost to my web app -
Can Anyone tell if my ERD(Entity Relation Diagram) is correct or not?
I am creating an ERD for my college project. can anyone tell me if my ERD is correct or not. if not then what are my mistakes. I am creating this ERD from django app. I generated the UML diagram with django-extension. But still my teacher says i need to draw the ERD with rectangles identifying the Entities and such. So this is what is created can anyone confirms if it is right or wrong?? -
Django - Created a web app which is linked to my PSQL, but when inserting data to one of my tables gives error for no ID
I have a table where it has only two columns being exercise_id and muscle_id create table if not exists exercise_muscle( exercise_id INT not null, muscle_id INT not null, primary key (exercise_id, muscle_id), foreign key (exercise_id) references exercise(exercise_id), foreign key (muscle_id) references muscle(muscle_id) ); But when I try and insert data into this with the model seen below model for ExerciseMuscle I get this error where it tries to return exercise_muscle.id, which doesn't exist Error picture I have also checked my django dbshell and it looks all fine \d exercise_muscle Table "public.exercise_muscle" Column | Type | Collation | Nullable | Default -------------+---------+-----------+----------+--------- exercise_id | integer | | not null | muscle_id | integer | | not null | Indexes: "exercise_muscle_pkey" PRIMARY KEY, btree (exercise_id, muscle_id) Foreign-key constraints: "exercise_muscle_muscle_id_fkey" FOREIGN KEY (muscle_id) REFERENCES muscle(muscle_id) And checked my psql table and it doesn't have an id column -
django simple jwt login with OTP without password
i have a django-rest app , for auth system i need help . i want to use JWT for auth (simple_jwt) but i was reading the doc , that i have find that i need to send the password and user to get the token to get login . this is a problem because users dont have the password i'm going to use OTP code to login users I have searched the google and looks like i must code a backend i dont want to make it complicated i want as simple as it can be , i searched and i find something like knox too do it can help me out ? -
How to get all pages awaiting moderation in Wagtail
I'm trying to find a way to query all pages that are currently awaiting moderation. I tried PageRevision.objects.filter(submitted_for_moderation=True).values('page_id'), but it seems to return only a few of them, I don't understand why. If i can get all pages in moderation, then i will be able to get what I really want : all pages awaiting moderation for the user currently logged in. Thanks a lot. -
How to create orders and order items in DRF
I want to know, how efficiently i can create order and its order items in DRF using views and serializers. I am sending many=True for POST request to OrderItemSerializer because i will be having a list of order items and want them to validated at once. My questions: How can I pass and update the order field, which was obtained from creating an order, in each OrderItem object . I want these list of order items to be created at once instead of looping over all and doing OrderItems.objects.create(**validated_data) ? views.py class OrderAPIView(generics.GenericAPIView): permission_classes = [IsAuthenticated] serializer_class = OrderSerializer def get_object(self): return self.request.user def get_queryset(self): ... def get(self, request): ... def post(self, request): serializer = self.serializer_class(data = request.data) if serializer.is_valid(): serializer.validated_data['user'] = self.get_object() order = serializer.save() # create order items return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py class OrderSerializer(serializers.ModelSerializer): PENDING, CONFIRMED, SHIPPED = "PENDING", "CONFIRMED", "SHIPPED" OUT_FOR_DELIVERY, DELIVERED, CANCELLED = "OUT_FOR_DELIVERY", "DELIVERED", "CANCELLED" ORDER_STATUS_CHOICES = [ (PENDING, "Order Pending"), (CONFIRMED, "Order Confirmed"), (SHIPPED, "Shipped"), (OUT_FOR_DELIVERY, "Out for Delivery"), (DELIVERED, "Delivered"), (CANCELLED, "Cancelled") ] total_price = serializers.DecimalField(max_digits = 7, decimal_places = 2) user = serializers.SlugRelatedField(slug_field = 'email', read_only = True) user_address = UserAddressSerializer() is_paid = serializers.BooleanField(default = …