Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to attach PDF generated from view to email in django?
I have this code written for sending email: def enviar_email(sender="sistema@jfpb.jus.br", receivers=['angelo.vidal@jfpb.jus.br'], subject="", msg=""): for r in receivers: message = MIMEText(msg) message['Subject'] = subject message['From'] = sender message['To'] = r smtpObj = None try: smtpObj = smtplib.SMTP("10.102.8.29", port="2525") smtpObj.sendmail(sender, r, message.as_string()) print("Successfully sent email") except Exception as e: print("Error: unable to send email", e) finally: if smtpObj: smtpObj.quit() I would like to know how to attach a PDF file that is generated dynamically to the email sent. Here is the code to create the view: class ComprovanteFormularioView(TemplateView): template_name = 'comprovante_submissao_formulario_pdf.html' def dispatch(self, request, *args, **kwargs): self.copia_atermacao_total = get_object_or_404(models.CopiaAtermacaoTotal, id=kwargs.get('pk')) return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): self.copia_atermacao_total.data_emissao_comprovante = date.today self.copia_atermacao_total.save() context = dict() context['atermacao'] = self.copia_atermacao_total context['request'] = request pdf = html_to_pdf('comprovante_submissao_formulario_pdf.html', context) return HttpResponse(pdf, content_type='application/pdf') I couldn't find anywhere where to do this, I only found out how to send a file that was already saved in the database. Any help would be much appreciated -
It is possible to show two sibling models into one's inline admin
I have one parent model, called Farmer, which has foreign key relationship with two child models namely, FarmerAdvisory and ImageDetail. I want to show ImageDetail as an inline model to FarmerAdvisory in admin panel. Is this possible? FarmerAdvisory Models.py class FarmerAdvisory(BaseModel): STATUS_CHOICES = ( ('OPEN', 'OPEN'), ('CLOSED', 'CLOSED') ) id = models.AutoField(db_column='id', primary_key=True) category = models.CharField(db_column='category', max_length=50, null=False, blank=False) sub_category = models.CharField(db_column='sub_category', max_length=100, null=True, blank=True) title = models.CharField(db_column='title', max_length=200, null=True, blank=True) description = models.CharField(db_column='description', max_length=750, null=True, blank=True) status = models.CharField(db_column='status', max_length=20, null=False, blank=False, default='OPEN', choices=STATUS_CHOICES) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, null=True, db_column='farmer_id') objects = models.Manager() class Meta: managed = True db_table = 'farmer_advisory' ImageDetails Models.py class ImageDetail(BaseModel): id = models.AutoField(db_column='id', primary_key=True) filename = models.CharField(db_column='filename', max_length=100) ref_type = models.CharField(db_column='ref_type', max_length=20, choices=ImageRefType) ref_sub_type = models.CharField(db_column='ref_sub_type', max_length=100, blank=True, null=True) ref_id = models.IntegerField(db_column='ref_id', blank=True, null=True) farmer_id = models.ForeignKey('Farmer', models.DO_NOTHING, db_column='farmer_id', blank=True, null=True) objects = models.Manager() class Meta: managed = True db_table = 'image_detail' -
Join two models when only 1 model has a foreign key
ModelA ------ id atr_a atr_b atr_c is_active ModelB ------ id atr_d atr_e modelA_id Without modifying either model, I need to include ModelB data in my ModelA ViewSet. I am not sure how this should be done given my constraints. class ModelAViewSet(...): endpoint_permissions = [...] queryset = ( ModelA.objects.filter(is_active=True) ) serializer_class = ModelASerializer filterset_class = ModelAFilter If I had the foreign key included in ModelA, it would be trivial, simplying including the ModelB serializer in my modelA serializer for the foreign key column, but without that, I am not sure on the approach. (Adding ModelB as a foreign key modelA is not an option) -
Updating post count via Javascript Fetch not showing
I want to show the like count when a user clicks on the like button (e.g 1 Like, 2 Likes) using Fetch but the count is not showing. I am using the Django to create the Like and Unlike Scenario. Here is my code: VIEWS.PY def update_like(request): username = request.user post_id = request.GET.get('post_id') post = NewTweet.objects.get(id = post_id) like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first() if like_filter == None: new_like = LikesPost.objects.create(post_id=post_id, username=username) new_like.save() post.save() return HttpResponseRedirect(reverse("index")) else: like_filter.delete() post.save() return HttpResponseRedirect(reverse("index")) MAIN.JS document.addEventListener('DOMContentLoaded', function () { const likeIcon = document.querySelector("#likeBtn") likeIcon.addEventListener("click", handleLike) function handleLike(event) { //save the parent element in id let id = parseInt(event.target.parentElement.dataset.id) let likes = parseInt(event.target.previousElementSibling.innerText) fetch(`/updatelike/${id}`, { method: "POST", }) .then(response => response.json()) .then((data) => { if (data.likes <= 1) { document.querySelector('#likeCount').innerHTML = `${likes + 1} like` } else { document.querySelector('#likeCount').innerHTML = `${likes + 1} likes` } }) } }) INDEX.HTML {% extends "network/layout.html" %} {% block body %} <div class="middle-sidebar"> <div class="main-page-header mt-3 sticky-top">Home</div> <div class="main-page-input"> <!-- <form class="d-flex flex-column"> --> <div class="row"> <div class="col-2 main-page-header-profile-picture"> <img src="https://i.pinimg.com/originals/a6/58/32/a65832155622ac173337874f02b218fb.png" class="main-page-header-profile-picture" alt="profile-picture"/> </div> <div class="col-10"> <div class="main-page-input-box"> <form method="POST" action="new_post"> {% csrf_token %} {{ form.as_p }} <div> <textarea name="caption" id="tweet-box" class="form-control main-page-tweet-box text-wrap" cols="30" rows="10" placeholder="What's happening"> </textarea> <!-- … -
Django - Can CreateView additionally create an entry in another model?
Can the CreateView be extendet so that after the entry in the Order-Model is created, an additional entry in the Shipping-Model is created automatically. In the Shipping-Model a new id (UUID) should be assigned and the created order should be entered as ForeignKey. class Order(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) client = models.ForeignKey( Client, on_delete=models.CASCADE, related_name="bestellung", ) … class Shipping(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="zollanmeldung_kopf", ) … class Order_CreateForm(forms.ModelForm): class Meta: model = Order fields = ( 'client', …, ) class OrderCreateView(CreateView): model = Order template_name = "order/order_create.html" form_class = Order_CreateForm I was not sure how to create a corresponding entry in the Shipping-Model or how and where to enter the required code. Best regards! Christian -
Why Django postgres DB flush is not working?
I want to reset the postgres DB from 0. When running python manage.py flush as suggested in this SO question I get the error django.db.utils.ProgrammingError: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... When I check the database tables with python manage.py dbshell and \dt I can only see 4 tables in the database (accounts_account, django_migrations, app1_model1,app1_model2), so all the tables on sessions etc. are missing. If I try to register a superuser with my usual email, it says it is already taken. So there are tables stored somewhere even if accounts_account appears empty in PGAdmin. At the same time, if I register a new superuser with a new email, when I try to login at http://127.0.0.1:8000/admin/ I get error: I also tried to delete completely the database in PGAdmin. Delete all the migrations in Django. And when I try python manage.py makemigrations, I get No changes detected. There are tables stored somewhere not showing in the PGAdmin for postgres. How can I fully and completely restart the whole thing from complete 0 like I just started the project? -
Using a Union Operator to Chain Django Queryset not working as expected
I am attempting to create a simple filter of users in my system that both allows admin users to be selected as well as any user that has an M2M association for associated_properties I normally use the Union Operator | to combine querysets when needed, but I am running into some strangeness I don't understand where the count of both querysets is much lower separately than the combined queryset. For example: # show all staff to root and admin staff = Staff.objects.filter(allowed_properties=request.session['property']).exclude( user__group__name__iexact='admin').order_by('user__group', 'user__first_name') # now get admin staff_admin = Staff.objects.filter(user__group__name__iexact='admin').order_by('user__first_name') final_staff = staff_admin | staff # 9, 26, 80...no way 9+26 should equate to 80, so why? # also many items are duplicated, but only from a few admins # that have actually been assigned a property print(len(staff_admin), len(staff), len(final_staff)) So what is going on, why would combining a queryset of 9 and 26 create one with 80 that has duplicated entries? Update Using union() works as expected, but that doesn't answer what the initial issue was. staff_admin.union(staff, staff_admin) # 9 26 35 print(len(staff_admin), len(staff), len(final_staff)) -
How to copy a field from one model to another model in django
suppose I have two models: class ModelA(models.Model): ... field = models.TextField(max_length=200) class ModelB(models.Model): ... field = models.TextField(max_length=200) And I want to copy the values from ModelA to ModelB without raw SQL, In Django's ORM I've tried many variations and I came up with this: from django.db.models import F, Subquery, OuterRef a_objs = ModelA.objects.filter(pk=OuterRef('pk')).values('pk') ModelB.objects.filter(pk=Subquery(a_objs)).update(field=F(OuterRef('field'))) This code fails in the update clause, how can I reference the another model field? that generates the following query: UPDATE model_b SET model_b.field = model_a.field FROM model_a WHERE model_a.id = model_b.id -
Django template - how do I create column name from a string and another column?
I am trying to create a dynamic column name. I have and Answer model that has all the answers the quiztaker selected and I have a Question model which of course contains the questions with four columns for the multiple choices. What I want to accomplish in the below code is display the actual correct choice as it is in one of the multiple choice columns, the actual text. But right now Question.ans just equals to a number, the column with the selected choice. The column names are OP1, OP2, OP3 and OP4 In the below code I already tried to create a variable and use it as a column name but that did not work at all. example: col_var = "question.OP" + question.ans So then the var would be "question.OP2" (or whatever other value) But when I do Correct answer: {{ col_var }} <---- this does not work I am still very new to Django and python, could you guys please let me know how I can get this done? I added my code to GIT if anyone needs to see other parts. Code on GIT <h2>You scored {{ score }} out of {{ total_questions }}</h2> {% if incorrect_questions … -
"Can't connect to MySQL server" While trying to connect MYSQL database to Django-REST in Docker
My configuration is as follows: I am running a Django-REST backend, with a MySQL database. I am trying to run the Django backend in its own Docker container, as well as running a MySQL database in its own Django container. It seems that Django is not able to connect to the MySQL database when my containers are running. Database settings in Django: DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", BASE_DIR / "db.sqlite3"), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432"), } } Dockerfile: FROM python:3.10.2-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code RUN apt update \ && apt install -y --no-install-recommends python3-dev \ default-libmysqlclient-dev build-essential default-mysql-client \ && apt autoclean RUN pip install --no-cache-dir --upgrade pip COPY ./requirements.txt /code/ RUN pip install --no-cache-dir -r requirements.txt COPY ./neura-dbms-backend /code/ EXPOSE 7000 Requirements.txt: Django djangorestframework django-cors-headers requests boto3 django-storages pytest mysqlclient==2.1.1 django-use-email-as-username djangorestframework-simplejwt gunicorn docker-compose.yml: version: "3.8" services: neura-dbms-backend: build: context: ./DBMS/neura-dbms-backend command: [sh, -c, "python manage.py runserver 0.0.0.0:7000"] image: neura-dbms-backend container_name: neura-dbms-backend volumes: - ./DBMS/neura-dbms-backend/neura-dbms-backend:/code ports: - 7000:7000 networks: - docker-network environment: - DEBUG=1 - SECRET_KEY=${SECRET_KEY_DBMS} - DJANGO_ALLOWED_HOSTS=${DJANGO_ALLOWED_HOSTS} - DJANGO_ALLOWED_ORIGINS=${DJANGO_ALLOWED_ORIGINS} - JWT_KEY=${JWT_KEY} - SQL_ENGINE=django.db.backends.mysql - SQL_DATABASE=db_neura_dbms - SQL_USER=neura_dbms_user - SQL_PASSWORD=super_secure_password - SQL_HOST=db_neura_dbms - … -
How do I get the data from the database randomly for a quiz game
with (Paginator(QuesModel.objects.filter(kategorie__exact=globalCategory).order_by("?"), 1)) I get some data displayed twice, but I want each question to be displayed randomly once. How can I do that? Thanks? views.py globalCategory = request.POST.get("Categorie") first= False count_of_selected_category = Paginator(QuesModel.objects.filter(kategorie__exact=globalCategory).order_by("?"), 1) page = request.GET.get("page") x = count_of_selected_category.get_page(page) global_counter = 1 questions = x globalQuestions = questions context = { 'questions': globalQuestions, 'category': request.POST.get("categorie"), } Maybe somebody can help me :( -
I have problem with cutomizing the 404 page in django
This is my settings.py: DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] main urls.py: handler404 = 'home.views.custom_page_not_found_view' my views for 404 page: def custom_page_not_found_view(request, exception): return render(request, "404.html", {}, status=404) i tryed this solution:(Correct way of implementing custom 404 page in Django 3 in production) but it doesn't work and kept getting server 500 error responses how do i fix this? -
Redis becomes bottleneck when my app has high usage, but metrics seem normal
My project is using Django 3.2 with django-redis and is hosted on Heroku with the Redis Enterprise Cloud add-on for hosting Redis. I'm monitoring my app's performance with Sentry. Whenever my app has high usage, Sentry shows all interactions with Redis as taking a lot more time (could even be up to 10 seconds). The Redis add-on offers metrics and everything looks normal there; read/write latency is max 0.07ms. Adding more dynos (instances) relieves the issue, but I don't understand how all this is connected to Django doing Redis requests (e.g. adding celery tasks). Does anybody have an idea as to what might be going on? -
How to upload image file in post request in python?
class UpdateProfilePictureSerializer(serializers.ModelSerializer): user_uuid = serializers.UUIDField(label=("uuid"), required=True, error_messages={ "invalid": "uuid_require", "required": "uuid_require", "blank": "blank_uuid"}) profile_picture = serializers.ImageField( label=("Profile Picture"), required=True, error_messages={ "invalid": "invalid_profile", "required": "profile_required", "blank": "blank_profile"}) class Meta: model = User fields = ['user_uuid', 'profile_picture'] def validate(self, validated_data): user_uuid = validated_data.get('user_uuid') try: user = User.objects.get(user_uuid=user_uuid) profile_picture = validated_data.get('profile_picture') if (profile_picture is not None): check_validate_image_extension(profile_picture.name) if profile_picture.size > MAX_FILE_SIZE: raise serializers.ValidationError("invalid_image_size") user.profile_picture = profile_picture else: raise serializers.ValidationError("profile_error") user.save() except User.DoesNotExist: raise serializers.ValidationError("user_not_exist") return validated_data This is my serializer which will handle data from request body from a view My question is that I'm writing test cases For this endpoint I want to test it in a test file So what I have to do is make Post request using below code. response = self.client.post(url='api/endpoint', data = {'profile_picture':'', 'user_uuid':'some valid uuid'} My question is what should I pass in profile_picture key. So it will be a valid file. I mean i want to upload image from a path that is app/tests/test.jpg According to serializer what should i pass in. Both key's value's If pass file with open('test.jpg','rb') throwing me error -
Django/Celery: AttributeError when invoking task
I'm defining a Celery task to send bulk emails and am getting an unexpected error when invoking it with Celery. The function works fine by itself without Celery, and line-by-line it works fine in the Django shell, so at this point I am completely lost. models.py: class TimestampedModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class BroadcastMessage(TimestampedModel): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) message_subject = models.CharField(max_length=100) message_text = models.TextField(blank=False, null=False) def __str__(self): return f"Message from {self.teacher} on {self.created_on}: {self.message_subject}" class Teacher(TimestampedModel): studio = models.ForeignKey(Studio, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f"{self.user.username}" class BroadcastMessageTracker(TimestampedModel): message = models.ForeignKey(BroadcastMessage, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) delivered_on = models.DateTimeField(auto_now_add=True) delivery_successful = models.BooleanField(default=True) exception = models.TextField(blank=True, null=True) views.py class BroadcastMessageCreateView(CreateView): model = BroadcastMessage fields = [ "message_subject", "message_text", ] template_name = "studios/broadcastmessage_form.html" success_url = reverse_lazy("dashboard") def form_valid(self, form): teacher = Teacher.objects.get(user=self.request.user) form.instance.teacher = teacher # storing the response so we can action on the saved object before redirecting response = super().form_valid(form) send_bulk_email.delay(self.object.id) return response tasks.py @shared_task(bind=True) def send_bulk_email(self, message_id): message = BroadcastMessage.objects.get(id=message_id) teacher = message.teacher students = Student.objects.filter(teacher=teacher, is_active=True, opt_out_of_receiving_email=False) mail_ctr = 0 for student in students: tracker = BroadcastMessageTracker() tracker.message = message tracker.student = student tracker.delivery_successful = True if student.email: try: ret = send_mail( subject=message.message_subject, message=message.message_text, from_email=teacher.user.email, … -
I use django, postgresql, redis, channels, Docker tools for my project.I have some problem with Docker postgresql image
When I run docker-compose up command This error occured: django.db.utils.OperationalError: could not translate host name "postgres_db" to address: Temporary failure in name resolution My docker-compose.yml file: version: "3.5" services: redis: image: redis:latest networks: - redisnet postgres_db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres django_wsgi: container_name: django_wsgi build: context: . command: uwsgi --socket=:9000 --module=core.wsgi:application --py-autoreload=1 volumes: - .:/code env_file: - .env networks: - webnet - redisnet links: - redis - postgres_db:postgres_db depends_on: - postgres_db django_asgi: container_name: django_asgi build: . # command: python manage.py runserver 0.0.0.0:8002 command: daphne -b 0.0.0.0 -p 8002 core.asgi:application env_file: - .env volumes: - .:/code networks: - webnet - redisnet links: - redis - postgres_db:postgres_db depends_on: - postgres_db nginx: image: nginx:1.15.0 depends_on: - django_asgi - django_wsgi volumes: - ./nginx:/etc/nginx/conf.d - ./static:/static networks: - webnet ports: - "80:80" networks: webnet: redisnet: My Dockerfile: `FROM python:3.8 ENV PYTHONUNBUFFERED 1 ENV REDIS_HOST "redis" RUN mkdir /code WORKDIR /code RUN pip install --upgrade pip RUN pip install psycopg2 COPY requirements.txt /code/ RUN pip install uwsgi RUN apt-get update && apt-get install -y tdsodbc unixodbc-dev RUN pip install -r requirements.txt ADD . /code/` My nginx default.conf file: upstream django_wsgi { server django_wsgi:9000; } upstream django_asgi { server django_asgi:8002; … -
Django static files load combined with css function url() generates weird & string in paths
I have deployed a django website to digital ocean, and storing static files into AWS buckets. So far so good, 'some' of my static files are loading correctly. For example, files like: <link rel="icon" href="{% static 'images/logo.svg' %}"> <script src="{% static 'js/jquery-3.3.1.slim.min.js' %}"></script> are loaded totally fine. The generated url when inspecting chrome's dev tools for, say the above logo is: https://<REGION>.digitaloceanspaces.com/<BUCKET NAME>/static/images/logo.svg?AWSAccessKeyId=<ACCESS KEY ID>&Signature=<AWS SECRET> which is correct, and the logo shows indeed on my webpage. Now, the weird thing is that I have some inline <style> blocks for which 'it nearly works'. Let me explain, I have the following piece in my html: <style> header#background-image { background-image: url("{% static 'images/header-background.svg' %}"); } </style> which is rendered as (again looking at chrome's dev tool): <style> header#background-image { background-image: url("https://<REGION>.digitaloceanspaces.com/<BUCKET NAME>/static/images/header-background.svg?AWSAccessKeyId=<ACCESS KEY ID>&amp;Signature=<AWS SECRET>&amp;Expires=1673362355"); } </style> The reason I mentioned this is 'nearly' ok is because I noticed the &amp; pieces of string in the generated url. If I correct those changing them to simple & and go to the modified link I indeed see my background image... This is so weird and drives me crazy, anybody got an idea of what is happening? -
Django custom auth backend not triggering when user does not exists
In Django==3.1.6, using a custom auth backend for insensitive login does not work properly. It only prints something when the user exists (lowercase). Whenever I enter a uppercase, it doesnt work and prints nothing. In my settings.py AUTHENTICATION_BACKENDS = [ 'users.UserEmailBackend.UserEmailBackend', 'django.contrib.auth.backends.ModelBackend', The auth backend # gets the user_model django default or your own custom from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.db.models import Q # Class to permit the athentication using email or username # requires to define two functions authenticate and get_user class UserEmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() print("AAAAA") # write to a file try: # below line gives query set,you can change the queryset as per your requirement username = username.lower() user = UserModel.objects.filter( Q(username__iexact=username) | Q(email__iexact=username) ).distinct() except UserModel.DoesNotExist: return None if user.exists(): ''' get the user object from the underlying query set, there will only be one object since username and email should be unique fields in your models.''' user_obj = user.first() if user_obj.check_password(password): return user_obj return None else: return None def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None You see there's a print("AAAAA") in the authenticate method. This is only called when … -
Dependant Drop Down in Java Script
I had made a form which include dependant drop down list but while I am selecting the dependant dropdown its just passing the index value. How can i add a value to the dependant dropdown list HTML SECTION <div class="form-row m-b-55"> <div class="name">Department</div> <div class="value"> <div class="input-group"> <div class="rs-select2 js-select-simple select--no-search"> <select name="department" id="department"> <option disabled="disabled" selected="selected">Select Department</option> </select> <div class="select-dropdown"></div> </div> </div> </div> </div> <div class="form-row m-b-55"> <div class="name">Course</div> <div class="p-t-15"> <div class="input-group"> <div class="rs-select2 js-select-simple select--no-search"> <select name="course" id="course"> <option disabled="disabled" selected="selected">Select Course</option> </select> <div class="select-dropdown"></div> </div> </div> </div> </div> JAVA SCRIPT var courseObject = { "Commerce":["B.Com CA","B.Com IF","B.Com Finance","M.Com"], "Computer Science" : ["B.Sc Computer Science","BCA","M.Sc Computer Science"], "Physics":["B.Sc Physics","M.Sc Physics"], "Chemistry":["B.Sc Chemistry","M.Sc Chemistry"] } window.onload = function(){ var departmentSel = document.getElementById("department"); var courseSel = document.getElementById("course"); for (var x in courseObject){ departmentSel.appendChild(new Option(x,x)); } departmentSel.onchange=function(){ courseSel.length = 1; for (var y in courseObject[this.value]){ courseSel.appendChild(new Option(courseObject[this.value][y],y)); } } } OUTPUT I need to get value as course name not just as id -
How to filter an object with ManyToMany field?
I'm building a view where I add a product to a cart. To do this I create an instance of a CartItem model wich is related to a cart, a product and has variations (color, size...). When the instance of CartItem is created I want to check if it alredy exists to know if I need to increment its stock or create a new one. So I first check for one with the same cart and product (ok so far). But then I don't know how to check if one that has the same variations exists (which is a ManytoMany fied). the view : def add_to_cart(request, product_id): product = Product.objects.get(id = product_id) variation_list = [] if request.method == "POST": print(request.POST) for item in request.POST: key = item value = request.POST[key] try: variation = Variation.objects.get(product = product, variation_category__iexact = key, variation_value__iexact = value) variation_list.append(variation) except: pass print(variation_list) try: cart = Cart.objects.get(cart_id=_get_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create(cart_id=_get_cart_id(request)) cart.save() try: cart_item = CartItem.objects.get(product=product,cart=cart) # How to filter cart_item so I know if it matches with variation_list cart_item.product_quantity +=1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create(product=product,cart=cart) cart_item.save() for variation in variation_list: cart_item.variation_list.add(variation) return redirect('cart') the Product model: class Product(models.Model): name = models.CharField(max_length=50, unique=True) slug = … -
Only able to get /article/1/ to load. /article/2/ displays a 404
Each page in /articles/x/ represents one article, each article has its own article content which is in the ArticleContent model which is structure like id tag css_id css_class content article_id (foreign key that points to Article Table) 1 p blab la 1 2 p bahaofs 2 actual database has more records for multiple article_ids loading /article/1/ works exactly as expected with article content ArticleContent Model class ArticleContent(models.Model): lemons = models.ForeignKey('Article', on_delete=models.CASCADE) order = models.IntegerField(blank=True) tag = models.CharField(max_length=20) css_id = models.CharField(max_length=100, blank=True) css_class = models.CharField(max_length=100, blank=True) extra = models.TextField(max_length=200, blank=True) content = models.TextField(max_length=2000, blank=True) Article Model class Article(models.Model): def __str__(self) -> str: return self.title title = models.TextField(max_length=200) slug = models.SlugField(max_length=100, blank=True) preview = models.TextField(max_length=500) hasimage = models.BooleanField(default=True) image = models.ImageField(upload_to='articles/static/articles/images', blank=True) date = models.DateTimeField(blank=True) url = models.TextField(blank=True) alt = models.TextField(max_length=1000, blank=True) urls.py app_name = 'article' urlpatterns = [ path('', views.index, name='index'), path('articles/<int:pk>/', views.DetailView.as_view(), name='article_detail'), ] views class DetailView(generic.DetailView): model = ArticleContent template_name = 'articles/article_detail.html' def get_queryset(self, *args, **kwargs): article_content = ArticleContent.objects.filter(lemons_id=self.kwargs['pk']) return article_content def get_context_data(self, *args, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in settings context['ordered_article_content'] = self.get_queryset() context['kwargs'] = self.kwargs['pk'] context['is_header_on'] = True context['is_footer_on'] = True context['header_links'] = HeaderLinks.objects.all() context['footer_links'] = … -
Django Rest Framework nested writable Serializers
I want create a writable multi Level Serializer with 2 and more Levels. But when I use the code under. I get Response BAD REQUEST 400. When I exclude the TaskSerializer its working (1Level) but more nested its not working. What I can do that it works? Thanks in advance. views.py class BoardView(APIView): def get(self, request, email): user = User.objects.get(email=email) boards = Boards.objects.filter(board_creator=user.id) serializer = BoardsSerializer(instance=boards, many=True) return Response(serializer.data) def post(self, request, email): response = Response() data = request.data['board'] user = User.objects.filter( email=data['board_creator']).first() if user is None: response.data = { 'detail': 'User not found' } response.status_code = status.HTTP_404_NOT_FOUND return response boards_by_user = Boards.objects.filter(board_creator=user.id) board_len = boards_by_user.filter( board_name=data['name']) if len(board_len) > 0: response.data = { 'detail': 'Board already exists' } response.status_code = status.HTTP_409_CONFLICT return response data['board_creator'] = user.id print(data) serializer = BoardsSerializer(data=data) if serializer.is_valid(): serializer.save() response.status_code = status.HTTP_201_CREATED response.data = { 'detail': 'Board created successfully' } return response response.status_code = status.HTTP_400_BAD_REQUEST return response model.py class Boards(models.Model): board_name = models.CharField(max_length=255, null=None) board_creator = models.ForeignKey(to=User, on_delete=models.CASCADE) def __str__(self) -> str: return str(self.board_name) class Columns(models.Model): column_name = models.CharField(max_length=255, null=None) board = models.ForeignKey( to=Boards, on_delete=models.CASCADE, related_name='columns') def __str__(self) -> str: return str(self.column_name) class Tasks(models.Model): task_title = models.CharField(max_length=255, null=None) task_description = models.TextField(null=True, blank=True) task_created = models.DateTimeField(default=timezone.now) … -
Django project working on IP address of droplet. But, it does not work on custom domain
I have my domain on GoDaddy and my hosting setup in DigitalOcean. So after I setup my basic django project, I used a droplet to deploy the code to an IP address. When I run this command, my project was running at my [IP_ADDRESS]:8000: gunicorn -w 2 -b 0.0.0.0:8000 --chdir /home/USER_NAME/projectdir/test_project test_project.wsgi Then, I put the three digital ocean nameservers in GoDaddy. I also modified the settings.py file by using the ALLOWED_HOSTS variables: ALLOWED_HOSTS = ['IP_ADDRESS', 'www.DOMAIN_NAME', 'DOMAIN_NAME'] My Nginx configuration looks something like this: server { listen 8000; listen 80; server_name IP_ADDRESS DOMAIN_NAME www.DOMAIN_NAME; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/USER_NAME/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } But still, I get 'This Site can't be reached'. I also checked that the nameservers have been updated by using https://lookup.icann.org/en. So I don't know where the problem lies. If you need any additional information let me know. Thank you -
Using Modelform with ModelChoicefield does not work for me, gives undefined error when submitting the form
I am trying to use a form that adds data to the model RaportProductie using AJAX. In the form I have 2 dropdown inputs that take data from the ManoperaRaportareBloc model. These are the attributes from ManoperaRaportareBloc : categorie_lucrare and subcategorie_lucrare When I submit the form it shows an error with undefined. Please help. ty. forms.py: class RaportProductieForm(forms.ModelForm): data = forms.DateField(initial=datetime.date.today) categorie_lucrare = forms.ModelChoiceField(queryset=ManoperaRaportareBloc.objects.all().values_list('categorie_lucrare', flat=True)) subcategorie_lucrare = forms.ModelChoiceField(queryset=ManoperaRaportareBloc.objects.all().values_list('subcategorie_lucrare', flat=True)) class Meta: model = RaportProductie fields = ['lucrare', 'data', 'tip', 'subcontractor', 'obiectiv', 'categorie_lucrare', 'subcategorie_lucrare', 'um', 'cantitate', 'valoare_prod'] views.py: def raportproductie_create_view(request): # request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": # get the form data form = RaportProductieForm(request.POST) # save the data and after fetch the object in instance if form.is_valid(): instance = form.save() # serialize in new friend object in json ser_instance = serializers.serialize('json', [ instance, ]) # send to client side. return JsonResponse({"instance": ser_instance}, status=200) else: # some form errors occured. data = { 'result': 'error', 'message': 'Form invalid', 'form': 'oops.' } return JsonResponse(data, status=400) # some error occured return JsonResponse({"error": ""}, status=400) template.html: $("#friend-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the … -
Why is app.urls not found?(Django Python)
I’m making my first django based backend server and I registered the urls for each app like urlpatterns = [ path('admin/', admin.site.urls), path('backfo/', include('backfo.urls')), path('commun/', include('commun.urls')), path('starts/', include('starts.urls')), path('travleres/', include('travleres.urls')), path('starts/', include('starts.urls')), path('new/', include('new.urls')), path('joint/', include('joint.urls')), ] Then I get this error in cmd saying -> ModuleNotFoundError: No module named 'backfo.urls' I don’t get what went wrong and if you need more code I’ll post it on.