Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pycairo error while deploying django app on AWS
My app is deployed on AWS ElasticBeanStalk was working fine up until one hour ago and now it is giving 502 Bad gateway error. When I tried to redeploy the application it gives me the following error 2023/05/05 07:41:44.917340 [ERROR] An error occurred during execution of command [self-startup] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 1. Stderr: error: subprocess-exited-with-error × Building wheel for pycairo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [15 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-38 creating build/lib.linux-x86_64-cpython-38/cairo copying cairo/__init__.py -> build/lib.linux-x86_64-cpython-38/cairo copying cairo/__init__.pyi -> build/lib.linux-x86_64-cpython-38/cairo copying cairo/py.typed -> build/lib.linux-x86_64-cpython-38/cairo running build_ext Package cairo was not found in the pkg-config search path. Perhaps you should add the directory containing `cairo.pc' to the PKG_CONFIG_PATH environment variable No package 'cairo' found Command '['pkg-config', '--print-errors', '--exists', 'cairo >= 1.15.10']' returned non-zero exit status 1. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for pycairo ERROR: Could not build wheels for pycairo, which is required to install … -
Export geojson from QGIS in SQL
I've a geojson (postgres/postgis) file from QGIS.I want to import in my dabatase (used by Django). Is it possible to generate a SQL command ? like a dump to import later ? I've try ogr2ogr but there's an error, and, it's weird, the sql query in the error message is good : # ogr2ogr -progress -f "PostgreSQL" PG:"host=db user=my_user dbname=my_database password=my_password" "04_GJ_ZM_4326-polygon.geojson" -nln my_table -append ERROR 1: ERROR: column s.consrc does not exist LINE 1: ...nrelid = c.oid AND a.attnum = ANY (s.conkey) AND (s.consrc L... ^ HINT: Perhaps you meant to reference the column "s.conkey" or the column "s.conbin". ERROR 1: ERROR: column s.consrc does not exist LINE 1: ...nrelid = c.oid AND a.attnum = ANY (s.conkey) AND (s.consrc L... ^ HINT: Perhaps you meant to reference the column "s.conkey" or the column "s.conbin". ERROR 1: ERROR: current transaction is aborted, commands ignored until end of transaction block ERROR 1: INSERT command for new feature failed. ERROR: current transaction is aborted, commands ignored until end of transaction block Command: INSERT INTO "my_table" ("polygon" , "number", "name", "department_id") VALUES ('0103000020E6100000010000000C0000001805C1E3DBFB174078D0ECBAB7184640FDA204FD850E194049F60835431E464055DD239BABB619405E8429CAA51F464084BA48A12CBC1940D044D8F0F40A464046B3B27DC8DB1940F3052D2460F845409966BAD749DD19401EA67D737FF7454048F8DEDFA0FD1840FB743C66A0F4454006D671FC50A91840D06394675EF64540AB23473A03C31840D3F4D901D7F945405ED5592DB0D71840F33977BB5E0046408E57207A5256184046B1DCD26A0846401805C1E3DBFB174078D0ECBAB7184640'::GEOMETRY, 44, 'PREALPES DE DIGNE', 4) RETURNING "id" ERROR 1: Unable to write feature 0 from layer 04_GJ_ZM_4326-polygon. ERROR 1: Terminating … -
Django admin styles not showing on docker and hot reload not working
im dockerizing my app that runs with Daphne/channels, I have styles in my rest framework api and the app but can't see them in my admin. Here is my dockerfile with entrypoint.sh FROM python:3.11.3-slim-buster WORKDIR /app ENV REDIS_HOST "redis" ENV PYTHONUNBUFFERED=1 ENV PYTHONWRITEBYTECODE 1 COPY ./requirements.txt ./requirements.txt RUN pip install -r requirements.txt COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] COPY . . EXPOSE 8000 python manage.py collectstatic --no-input python manage.py migrate --force daphne core.asgi:application --bind 0.0.0.0 here is dockercompose with removed postgres and redis version: "3.11.3" services: nginx: image: nginx:latest volumes: - ./nginx:/etc/nginx/conf.d - static_files:/usr/share/nginx/html/static ports: - "80:80" gym_django: restart: always build: context: . args: options: --reload volumes: - .:/app - static_files:/app/staticfiles ports: - 8000:8000 env_file: - .env container_name: gymbud_cont depends_on: - pgdb links: - redis volumes: static_files: settings file MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend', 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, "static/images") and URLs static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) any help would be appreciated -
Elasticsearch refuses connection to python Django
I have a Django project with a model: class ParentFoodDirectory(TimeStampedModel): uuid = models.UUIDField(default=uuid.uuid4, editable=False) name = models.CharField(max_length=1000, null=False, blank=False) active = models.BooleanField(null=False, blank=False, default=True) p_id = models.IntegerField(null=False, blank=False) class Meta: verbose_name_plural = "Parent Food Items" def __str__(self): return self.name This model has more than 10 million objects. The searching on this gets really slow that's why I decided to use elastic search. I set up Elasticsearch on a different instance and used ngnix on the machine. Now the elastic search was available through the ext IP. Then in order to map this mode on elastic search I made a dcouments.py file: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from .models import ParentFoodDirectory @registry.register_document class ParentFoodDirectoryDocument(Document): name = fields.TextField() active = fields.BooleanField() p_id = fields.IntegerField() class Index: name = 'parentfooddirectory' class Django: model = ParentFoodDirectory I mentioned the host in my settings: ELASTICSEARCH_HOST = 'http://35.141.96.246/' ELASTICSEARCH_DSL = { 'default': { 'hosts': '35.141.96.246', }, } But while rebuilding index, I get the following error: elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f49febf8d90>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f49febf8d90>: Failed to establish a new connection: [Errno 111] Connection refused) Any clue on what might … -
use throttle to limit number of wrong mod requests
i want to limit wrong method requests in my django app, for example i have GET method on one of my urls and other methods like post, put, patch, delete are not allowed for that url path and even not implemented. i want to count number of requests for not allowed methods and don't allow user requests be more than 10 times for that not allowed methods. and at the same time i don't have any limitation constraint for get method on the same url. -
Sendgrid smtp cannot verify sender identity
I have a Django application that uses sendgrid’s smtp relay for sending emails. However I am receiving a 550 error. I authenticated my domain in sendgrid and I added a send user with the “from” email no-reply@mydomain.com. This email however doesn’t actually exist, is this the cause of my error? If so wouldn’t this mean I have to setup an email server to use no-reply@mydomain.com, and isn’t the whole point of sendgrid to not have to create a email server? This is a point of confusion for me because I thought sendgrid authenticates your domain to act as a email server for it I Set the following env variables: EMAIL_HOST=smtp.sendgrid.net EMAIL_PORT=587 EMAIL_USE_TLS=True EMAIL_HOST_USER=“apikey”EMAIL_HOST_PASSWORD=SG.********* DEFAULT_FROM_EMAIL=no- reply@mydomain.com My error log is: “smtplib.SMTPDataError: (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending- email/sender-identity/ to see the Sender Identity requirements')” -
class Meta Django
Good evening, In fact I would have liked to have explanations in relation to the Meta class. In my case, if I don't code it, it doesn't change anything. I imagine it's because in the settings I filled in the user model used for the project. But beyond filling in the class linked to the form, I have trouble understanding the fields attribute. Because I can interchange, remove items from the list, it doesn't change anything. Thanks in advance class UserPasswordChangeForm(PasswordChangeForm): old_password = forms.CharField(widget=forms.PasswordInput) new_password1 = forms.CharField(widget=forms.PasswordInput) new_password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model = Shopper fields = ["old_password", "new_password", "new_password2"] Apart from the model, what is the class meta for? -
django serializer dictfield vs jsonfield
I have a column custom_property of type jsonb in postgres. I need to validate a payload for this column. payload: { "description": "test description3", "custom_property": { "access": "Yes" } } I have a serializer: class MySerializer(serializers.Serializer): description = serializers.CharField(required=False, max_length=500) custom_property = serializers.DictField(required=False) Should I use DictField or JSONField for this column? It seems that in both case, it needs to be formatted to json string first with json.dumps(). -
How to get the access_token in Django-all auth with GitHub social account?
I am working on a project and successfully set up the django-allauth using GitHub social account in an app named 'auth'. Now, I need profile details and access to a particular repository of authenticated users in another app, and for that, I need an access token but I am facing errors with that. How to do it? Any suggestion on this? Below is the code I am using to fetch access token: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .utils import get_github_profile_details, get_repo_details @login_required def profile(request): social_account = request.user.socialaccount_set.first() if not social_account: messages.error(request, 'No social account found. Please log in with GitHub.') return redirect('account_login') social_token = social_account.socialtoken_set.first() if not social_token: messages.error(request, 'No access token found. Please log in with GitHub.') return redirect('account_login') access_token = social_token.token profile = get_github_profile_details(access_token) repo_name = f"ProgrammersPost-{profile['username']}" repo_details = get_repo_details(access_token, repo_name) context = { 'profile': profile, 'repo_details': repo_details, } return render(request, 'proprofile/profile.html', context) I need to get the access token. -
How do you solve [Errno 2] No such file or directory In Python Django on VSCode
I have been trying to run the server of code shared by a colleague but I keep getting errno2 C:\Users\lenovo\Desktop\Bsc Comp Scie\Web Projects\main>python manage.py showmigrations python: can't open file 'C:\Users\lenovo\Desktop\Bsc Comp Scie\Web Projects\main\manage.py': [Errno 2] No such file or directory -
Why am I getting Python Django-autotranslate package installation problem on windows?
I try to install Django autotranslate package but it gives error as "Encountered error while generating package metadata." pip install django-autotranslate ERROR : Collecting django-autotranslate Using cached django_autotranslate-1.2.0-py3-none-any.whl (10 kB) Requirement already satisfied: six in d:\pps\venv\lib\site-packages (from django-autotranslate) (1.16.0) Collecting polib Using cached polib-1.2.0-py2.py3-none-any.whl (20 kB) Collecting goslate Using cached goslate-1.5.4.tar.gz (14 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: django in d:\pps\venv\lib\site-packages (from django-autotranslate) (3.2.13) Requirement already satisfied: sqlparse>=0.2.2 in d:\pps\venv\lib\site-packages (from django->django-autotranslate) (0.4.2) Requirement already satisfied: pytz in d:\pps\venv\lib\site-packages (from django->django-autotranslate) (2022.7) Requirement already satisfied: asgiref<4,>=3.3.2 in d:\pps\venv\lib\site-packages (from django->django-autotranslate) (3.5.0) Collecting futures Using cached futures-3.0.5.tar.gz (25 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [25 lines of output] Traceback (most recent call last): File "", line 2, in File "", line 14, in File "D:\PPS\venv\lib\site-packages\setuptools_init_.py", line 18, in from setuptools.dist import Distribution File "D:\PPS\venv\lib\site-packages\setuptools\dist.py", line 32, in from setuptools.extern.more_itertools import unique_everseen File "", line 1027, in find_and_load File "", line 1006, in find_and_load_unlocked File "", line 674, in load_unlocked File "", line 571, in module_from_spec File "D:\PPS\venv\lib\site-packages\setuptools\extern_init.py", line 52, in create_module return self.load_module(spec.name) File "D:\PPS\venv\lib\site-packages\setuptools\extern_init.py", line 37, in load_module import(extant) File "D:\PPS\venv\lib\site-packages\setuptools_vendor\more_itertools_init.py", line … -
Executing celery task through a listener on a RabbitMQ queue
I am trying to run a script for a messaging consumer that listens to a rabbitMQ instance and executes a celery job based on that message value. I am receiving issues with circular dependencies and cannot figure what exactly is the issue and how to fix it. Below are my file examples: celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projectTest.settings") app = Celery( "appTest", broker=os.environ.get("RABBITMQ_CONN_STRING"), backend="rpc://", ) # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) app.config_from_object("appTest.celeryConfig", namespace="CELERY") app.autodiscover_tasks() if __name__ == "__main__": app.start() class_task.py from celery import app logger = get_task_logger("emailSvcCelery") class ClassTask(app.Task): name = "class-task" def run(self): print('Task Ran!') app.register_task(ClassTask) message_consumer.py import os import json import pika from tasks.class_task import ClassTask connection_parameters = pika.ConnectionParameters(os.environ.get("RABBITMQ_CONN_STRING")) connection = pika.BlockingConnection(connection_parameters) channel = connection.channel() queues = ( 'queue-test' ) for q in queues: channel.queue_declare(queue=q, durable=True) def callback(channel, method, properties, body): ClassTask().delay() channel.basic_consume(queue='queue-test', on_message_callback=callback, auto_ack=True) print("Started Consuming...") channel.start_consuming() The error I am recieving is below after running python3 message_consumer.py: Traceback (most recent call last): File "/message_consumer.py", line 4, in <module> from tasks.class_task import ClassTask File "/class_task.py", line 1, in <module> from celery import app File "/celery.py", line 2, in <module> from celery import Celery ImportError: cannot import name 'Celery' from … -
Is it possible to Combine querysets from different models into a single queryset or a list and order by date
models.py # Customer Model class Customer(models.Model): name =models.CharField(max_length=100) primary_contact = models.CharField(max_length=10) secondary_contact = models.CharField(max_length=10, blank=True) address = models.TextField(blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('customers') # Issue Model class Issue(models.Model): date_time = models.DateTimeField(default=datetime.now) date = models.DateField(auto_now_add = True) tt = models.CharField(default='SB', max_length=3) voucher = models.CharField(blank = True, default='', max_length=6) customer = models.ForeignKey(Customer, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, ) quantity = models.PositiveIntegerField() kt = models.IntegerField() rate = models.FloatField() vat = models.IntegerField(default=15) discount = models.IntegerField(blank = True, default = 0) note = models.CharField(blank = True, default='', max_length=100) amount = models.IntegerField(blank = True, default = 0) @property def kt_21(self): return round(self.kt / 21 * self.quantity , 2) @property def vat_amt(self): return (self.quantity * self.rate - self.discount) * self.vat/100 # Total amount exclusive of VAT @property def tot_amount(self): return self.quantity * self.rate # Total amount inclusive of VAT @property def total_amt(self): return self.quantity * self.rate + self.vat_amt def get_absolute_url(self): return reverse('issue-hist') def __str__(self): return str(self.customer) + " - "+ str(self.tot_amount)+' SAR' # Receive Model class Receive(models.Model): date_time = models.DateTimeField(default=datetime.now) date = models.DateField(auto_now_add = True) tt = models.CharField(default='RB', max_length=3) voucher = models.CharField(blank = True, default='', max_length=6) customer = models.ForeignKey(Customer, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, ) quantity = models.PositiveIntegerField() kt = … -
Running django web app over a web path in a sandbox
At the place where I work we have the option to deploy applications through a sandbox. With that a problem arises and that is that for each application running we have a web path, for example: domain.com/path/of/app_django/. With that base path I can access the main view of my application (0.0.0.0:8080/ >> domain.com/path/of/app_django/) however when trying to access other views django uses the main domain, for example domain.com/my_url instead of being domain.com/path/of/app_django/my_url. What can I do to fix this? -
Reduction of queries in ManyToMany field with prefetch_related
I want to reduce further the number of queries. I used prefetch_related decreasing the number of queries. I was wondering if it is possible to reduce to one query. Please let me show the code involved: I have a view with prefetch_related: class BenefitList(generics.ListAPIView): serializer_class = BenefitGetSerializer def get_queryset(self): queryset = Benefit.objects.all() queryset = queryset.filter(deleted=False) qs= queryset.prefetch_related('nearest_first_nations__reserve_id') return qs I have the models used by the serializers. In here, it is important to notice the hybrid property name which I want to display along with reserve_id and reserve_distance: benefit.py: class IndianReserveBandDistance(models.Model): reserve_id = models.ForeignKey(IndianReserveBandName, on_delete=models.SET_NULL, db_column="reserve_id", null=True) reserve_distance = models.DecimalField(max_digits=16, decimal_places=4, blank=False, null=False) @property def name(self): return self.reserve_id.name class Benefit(models.Model): banefit_name = models.TextField(blank=True, null=True) nearest_first_nations = models.ManyToManyField(IndianReserveBandDistance, db_column="nearest_first_nations", blank=True, null=True) Name field is obtained in the model IndianReserveBandName. indian_reserve_band_name.py: class IndianReserveBandName(models.Model): ID_FIELD = 'CLAB_ID' NAME_FIELD = 'BAND_NAME' name = models.CharField(max_length=127) band_number = models.IntegerField(null=True) Then, the main serializer using BenefitIndianReserveBandSerializer to obtain the fields reserve_id, reserve_distance and name: get.py: class BenefitGetSerializer(serializers.ModelSerializer): nearest_first_nations = BenefitIndianReserveBandSerializer(many=True) The serializer to obtain the mentioned fields: distance.py: class BenefitIndianReserveBandSerializer(serializers.ModelSerializer): class Meta: model = IndianReserveBandDistance fields = ('reserve_id', 'reserve_distance', 'name') The above is resulting in two queries which I would like to be one: SELECT ("benefit_nearest_first_nations"."benefit_id") AS … -
Django Channels + Vue + Daphne + Google App engine flex app won't start after deployment
The app loads blank screen, and after inspecting the Network tab in browser I see that only main.css and main.js are requested, no chunk-some_id.js or css files. On top of that the main css and js cause a message in browser console Refused to apply style from 'my_site.appspot.com/static/vue/css/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I am using custom runtime and here is my app.yaml file: runtime: custom runtime_config: operating_system: "ubuntu18" runtime_version: "3.8" env: flex service: development network: forwarded_ports: - 9000/tcp beta_settings: cloud_sql_instances: db_address env_variables: DB_HOST: "DB_HOST" DB_PASSWORD: 'DB_PASSWORD' DB_NAME: 'DB_NAME' REDIS_HOST: 'REDIS_HOST' REDIS_PORT: 'REDIS_PORT' STATIC_ROOT: 'STATIC_ROOT' DEFAULT_FILE_STORAGE: 'DEFAULT_FILE_STORAGE' STATICFILES_STORAGE: 'STATICFILES_STORAGE' GS_PROJECT_ID: 'GS_PROJECT_ID' GS_BUCKET_NAME: 'GS_BUCKET_NAME' GS_STATIC_BUCKET_NAME: 'GS_STATIC_BUCKET_NAME' STATIC_URL: '/static/' MEDIA_ROOT: 'media' MEDIA_URL: '/media/' UPLOAD_ROOT: 'media/uploads/' DOWNLOAD_URL: "media/downloads" resources: cpu: 1 memory_gb: 5 disk_size_gb: 10 manual_scaling: instances: 1 liveness_check: success_threshold: 1 failure_threshold: 2 I have omitted entrypoint in app.yaml as I understand it is not needed since it is defined in Dockerfile. Here is my Dockerfile: # Use the official Python image as the parent image FROM python:3.8-slim-buster # Set the working directory to /app WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y libpq-dev nginx … -
Cancelled Sessions from Student s letting confirmation lapse finding their way into the queue
I'm using django. I'm having an with a website were tutors can connect with students. There is a bug were students who have cancelled there session are still finding there cancelled session back to the queue, I'm seeing the unfulfilled requests has jumped from 34 on Monday to 75 now and I'm wondering how many of those requests are real. I cant find the source code I Cant find the source code and I need to locate it first -
How do I add a Form Object, from the Database, Into the model?
How do I add a Form Object, from the Database, Into the model? models.py class TwoUserModel(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) user2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #Add assigned_number here based on the form below. forms.py class NameForm(forms.Form): assigned_number = models.IntegerField(null=True, blank=True) -
form_valid method not called if post method not overrided
I have a blog that is composed by user's posts and post's comments. In my UpdateView, the model points to Post, so I can show the post in the template. In my form_valid method, I get the comment from the user through a form. The problem is that if I don't override the post method, the form_valid method is not called. When I post something through a form, what happens? What methods are called by django and what methods should I override? class PostDetails(UpdateView): template_name = "posts/details.html" model = Post form_class = CommentForm context_object_name = 'post' # success_url = "posts/details.html" def form_valid(self, form): post = self.get_object() comments = Comments(**form.cleaned_data) comments.post = Post(post.id) if self.request.user.is_authenticated: comments.user = self.request.user comments.save() messages.success(self.request, "Post sent successfully") return redirect("posts:details", pk=post.id) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = self.get_object() comments = Comments.objects.filter(published=True, post=post.id) context['comments'] = comments return context class CommentForm(ModelForm): def clean(self): data = super().clean() author = data.get("author") comment = data.get("comment") if len(comment) < 15: print("Entrou no if do comment") self.add_error("comment", "Comment must be 15 chars or more.") if len(author) < 5: self.add_error("author", "Field must contain 5 or more letters.") class Meta: model = Comments fields = ['author', 'email', 'comment'] {% extends 'base.html' %} {% … -
please help me! when i run the code thes errors apear in my python and django project
MS yacine@yacine-Lenovo-ideapad-110-15IBR:~/Desktop/LMS/LMS$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 04, 2023 - 18:37:16 Django version 4.2, using settings 'LMS.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [04/May/2023 19:10:58] "GET / HTTP/1.1" 200 403643 Not Found: /api.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.css [04/May/2023 19:10:58] "GET /api.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.css HTTP/1.1" 404 3077 Not Found: /api.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.js [04/May/2023 19:10:59] "GET /api.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.js HTTP/1.1" 404 3074 Not Found: /assets/js/theme.min.js [04/May/2023 19:21:01] "GET /assets/img/menu/home-v7.jpg HTTP/1.1" 404 3011 Not Found: /assets/img/menu/home-v11.jpg [04/May/2023 19:21:01] "GET /assets/img/menu/home-v9.jpg HTTP/1.1" 404 3011 [04/May/2023 19:21:01] "GET /assets/img/menu/home-v11.jpg HTTP/1.1" 404 3014 Not Found: /assets/img/menu/home-v12.jpg note:all file are in the right place -
How to read byte strings generated by marshall on the jquery side?
On the Django server side, I form a response: def index(request): if request.method == 'POST': ... url = reverse(settlement_create, args=[settlement_id]) return HttpResponse(marshal.dumps({'url': url}), content_type="application/json") , where url=/settlement/154/create. jQuery cannot decode the byte string correctly and it turns out {� url� /settlement/154/create0. $.ajax({ type : 'POST', url : url, data : {'text': city_info}, success : function(response){ $("#city-href").attr('href', response['url']); }, error : function(response){ console.log(response) } }); If you use a regular json library instead of marshal, then everything works fine. Do you have any ideas? -
checkmark is not shown in django form
I created contact form but checkmark is not showing the option and the box is very narrow. So when login as admin and try to add a contact, I don't see options in there. Here is models.py and forms.py and screenshot. models.py class Location(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Contact(models.Model): LOCATION_INHOME = ( ('kitchen', 'Kitchen'), ('bathroom', 'Bathroom'), ('bedroom', 'Bedroom'), ('livingroom', 'Living Room'), ('basement', 'Basement'), ('garage', 'Garage'), ('office', 'Office'), ('hallway', 'Hallway'), ('stairway', 'Stairway'), ('recreationroom', 'Recreation Room'), ('closet', 'Closet'), ('other', 'Other'), ) location_in_home = models.ManyToManyField(Location) class ContactForm(ModelForm): model = Contact fields = '__all__' class Meta: model = Contact fields = '__all__' forms.py from django import forms from django.forms import ModelForm from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = [ 'location_in_home', ] widgets = { 'location_in_home': forms.CheckboxSelectMultiple(), } Here is the admin.py class ContactAdmin(admin.ModelAdmin): list_filter = ('location_in_home') admin.site.register(Contact, ContactAdmin) -
Django querysets: how to combine two querysets in django one is based on Form and 2nd is based on Q objects
this is my view function as i have a problem to get docks = Docks.objects.filter(Q(dock_1__icontains=query)) to protein.html page.I have two queries one from SearchForm related to Proteins model and other is from Q objects and i want to get both fields pdb_name and dock_1 but i am only getting one pdb_name with its related parameters from Proteins model only but didnot get dock_1 from Docks model. class SearchForm(forms.Form): """Search view showing the top results from the main page of the AMPdb tool.""" query_id = forms.CharField() def create_query(self): """the form fields get put into self.cleaned_data, make a new PDBQuery object from those fields and return""" query = Proteins(name=self.cleaned_data["pdb_name"]) query.save() return query` class SearchView(generic.FormView): """Search view of the AMPdb tool.""" form_class = SearchForm template_name = "abampdb/search.html" success_url = "/" def get_context_data(self, **kwargs): context = super(SearchView, self).get_context_data(**kwargs) query = self.request.GET.get('q', '') category = self.request.GET.get('category', '') docks = Docks.objects.filter(Q(dock_1__icontains=query)) context = {} rows = [] for peptide in itertools.zip_longest(Proteins.objects.all()): rows.append({ 'left': peptide, }) context['rows'] = rows context['proteins'] = Proteins.objects.all() context['dock'] = docks context['query'] = query context['category'] = category try: context["protein"] = Proteins.objects.get( name=self.request.GET.getlist("pdb_name") ) except Proteins.DoesNotExist: context["protein"] = None print(context) return context # return self.render_to_response(context) def form_valid(self, form): params = { "pdb_name": form.cleaned_data.get('pdb_name'), "dock_1": … -
removing added django application from a database
I just posted another question: Django error on deleting a user in the admin interface But realized in that question the project /models it is complaining about I am going a different direction with. So I was curious how I can I just remove a project from the database. i.e. a whole folder under my django application? I will be redoing it anyway and I want my deployed application from the earlier question to keep working along. Is it just a matter of removing all the data in models.py and then doing a new migration? -
The field '' was declared on serializer Serializer, but has not been included in the 'fields' option
I am working on aproject with django and DRF. I am facing this error AssertionError at /barber/info/ The field 'comments' was declared on serializer BarberSerializer, but has not been included in the 'fields' option. I dont know why am I facing this error despite I already have added 'comments' in my fields. this is my serializer: class BarberSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True) rating = serializers.SerializerMethodField(source= "get_rating") customers_rate = serializers.SerializerMethodField() # comments = serializers.SerializerMethodField() # rating = serializers.SerializerMethodField() # comment_body = serializers.CharField(write_only=True, required=False) class Meta: model = Barber fields = ('id','BarberShop','Owner','phone_Number','area','address','rate', "rating", "customers_rate", 'background','logo', 'comments', )# ,"comment_body", ]# "rating"] read_only_fields = ("id", "created_at", "BarberShop", "Owner", "phone_Number", "area", "address" , 'background','logo',"comments", "rate", "rating", "customers_rate") def get_comments(self, obj): comments = obj.comments.all() serializer = CommentSerializer(comments, many=True, context=self.context) return serializer.data def get_rating(self, obj): comments = obj.comments.all() if comments: ratings = [comment.rating for comment in comments] return sum(ratings) / len(ratings) return 0 def get_rating(self,obj): ratings = obj.ratings.all() if ratings : ratings = [rating_instance.rating for rating_instance in ratings] # print(*ratings, sep = "\*n") return round(sum(ratings) / len(ratings), 2) else: return 3.33 def get_customers_rate(self, obj): customer = self.context['request'].user.customer # print(customer, sep = "*****\n") try: rating = obj.ratings.filter(customer=customer).order_by("-created_at").first() # rating = Rating.objects.get(customer= customer, barber = obj) return rating.rating except: return …