Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering multiple image blob ulrs using react result in corrupted images
I'm trying to build an app that takes an image file as input, posts it to the server, and receives a styled image as blob URL. The problem is that some of the received images are sometimes corrupted. There is no pattern here and some of them are randomly corrupted. And sometimes it works fine with no corrupted images. Here are the relevant code snippets. I'm using django-rest framework for the backend. var styled_images = [] function StyleTransferCarousel() { const [styledImages, setStyledImages] = useState([]) const [styled, setStyled] = useState(false) // this function gets the image blob from server const getStyledImage = async (model) => { var formData = new FormData() ... try { const { data } = await axios.post('/style_transfer/stylev2/', formData, config) return data } catch (error) {...} } // this function gets the image blob untill the size of image list is equal to available models and re-renders async function getStyledImages() { var styledImageDict = {} for (let i = 0; i < models.length; i++) { var model_i = models[i] var data = getStyledImage(model_i) data.then(data => { styledImageDict = { image: "data:image/png;base64," + data.image, model: models[i] } styled_images = styled_images.concat([styledImageDict]) if (styled_images.length !== models.length) { setLoader(false) setStyledImages(styled_images) //react hook … -
Django CKEditor add YouTube plugin
I was trying to find answer for my question, but still couldn't figure it out. I have my model with field: description = RichTextUploadingField(verbose_name='Description', config_name='special') In settings.py I have: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', "removePlugins": "stylesheetparser", 'toolbar_Custom': [ ['Bold', 'Link', 'Unlink', 'Image'], ], }, 'special': { 'toolbar': 'Special', 'enterMode': 2, 'height': 500, 'width': 1100, "removePlugins": "stylesheetparser", 'extraAllowedContent': 'iframe[*]', 'toolbar_Special': [ ...... { 'name': 'youtube', 'items': ['Youtube',] }, ], } } And it works, but youtube icon doesn't display on my toolbar. Searching for solution I read I have to put youtube-plugin in ckeditor config. So in my folder project (where all apps are created) I created ckeditor/ckeditor/plugins/youtube/. Like on attached image. . Unfortunately the option to add youtube video still don't display on toolbar. Is there something I'm doing wrong or need to do something else? -
How i change url in Django framework
i'm try to make some website using django and i got some error message like this Request URL: http://127.0.0.1:8000/store.html Using the URLconf defined in greatkart.urls, Django tried these URL patterns, in this order: admin/ [name='home'] store/ ^media/(?P<path>.*)$ The current path, store.html, didn't match any of these. the problem is when i tried to click button it's allways print ./store.html not the ./store it's my html code for the button <a href="./store.html" class="btn btn-outline-primary float-right">See all</a> and this is my django for urls.py (main) urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('store/', include("store.urls")) ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) this urls.py(store) urlpatterns = [ path('', views.store, name='store'), path('<slug:category_slug>/', views.store, name='product_by_category'), ] views.py def store(request, category_slug = None): return render(request, 'store/store.html', context) anyone have some idea? i want to fix it without change html code because I've tried it and when i click on the buttons twice that make some error because the url print the ./store twice -
Django authentication: index for staff and index for user (2 templates)
I have 2 functions currently working, one is a specific view for is_staff users, the other for any users. Right now after staff logs in they can add path /dashboard to the URL and can access the route, while normal users cannot view it. That is expected and good. Problem: I want to at login, to redirect user.is_staff straight to this path /dashboard, instead of going to index first. The functions somehow I think I have to merge: (views.py) 1 @staff_member_required 2 def staff_dashboard(request): 3 users = User.objects.all() 4 customer = Customer.objects.all() 5 accounts = Account.objects.all() 6 context = { 7 'users': users, 8 'customer': customer, 9 'accounts': accounts 10 } 11 return render(request, 'bank_app/dashboard.html', context) 12 13 14 @login_required 15 def index(request): 16 customer = Customer.objects.filter(user=request.user) 17 accounts = Account.objects.filter(user=request.user) 18 context = { 19 'customer': customer, 20 'accounts': accounts 21 } 22 return render(request, 'bank_app/index.html', context) (urls.py:) urlpatterns = [ path('dashboard', views.staff_dashboard, name='staff_dashboard'), path('', views.index, name='index'), path('create', views.create, name='create'), path('createaccount', views.createaccount, name='createaccount'), path('details/<int:pk>', views.details, name='details'), ] When user is_staff, show "dashboard/"(dashboard.html), not ""(index.html) *I also have extension template seen below but that did not fix the issue: 28 <p>Welcome {{ user }}</p> 29 30 {% if user.is_staff %} … -
Default/Initial value for Django forms field (required=True) after POST-request (bound forms)
I tried all the solutions here on Stackoverflow but they all use required=False. How can I set a default value for a required form-field every time, even after a post request (when the form is bound)? # forms.py class MyForm(forms.Form): name = forms.CharField(required = True) def __init__(self, *args, **kwargs): super(editSonde_KundenAdminPanel, self).__init__(*args, **kwargs) self.initial['name'] = "foo bar" #Views.py def index(request): if request.method == 'GET': form = MyForm() if request.method == 'POST': form = MyForm(request.POST) #After this step, the form doesn't have an initial value anymore... if form.is_valid() #Do Stuff -
login a user without login() function in django
I have used the User model for storing data of normal user but I want to store data of some special user in other model but than how will I be able to authenticate these special users and login them .Can I use the authenticate() and login() functions with other model also other than User model? -
How can I get one object when we select object from dependent dropdown list in django
(I am working on dependent dropdown list in Django) I have two dropdown lists first is Company and second is Car. when I select company Name from first dropdown list like Toyota all cars are coming related to Toyota Company, when I select any car from second dropdown (Car Dropdown) then it's showing nothing against Toyota I only need one car which I have selected, How can I do this ? Any one can help ? It is showing empty page like this Here is my code models.py class Car(models.Model): CarID = models.AutoField(primary_key=True) CarName = models.CharField(max_length=500, blank=True, null=True, verbose_name="Car Name") company = models.ForeignKey(Company, verbose_name="Company Name", on_delete=models.CASCADE, default="") type = models.ForeignKey(CarType, verbose_name="Vehicle Type", on_delete=models.CASCADE) CarImage = models.ImageField(upload_to='productimg', verbose_name="Vehicle Image") RefNo = models.CharField(max_length=500,verbose_name="Ref No", null=True, blank=True) ChassisNo = models.CharField(max_length=500,verbose_name="Chassis No", null=True, blank=True) ModelCode = models.CharField(max_length=500,verbose_name="Model Code", null=True, blank=True) EngineSize = models.CharField(max_length=500,verbose_name="Engine Size", null=True, blank=True) Location = models.CharField(max_length=500,verbose_name="Location", null=True, blank=True) Version = models.CharField(max_length=500,verbose_name="Version/Class", null=True, blank=True) Drive = models.CharField(max_length=500,verbose_name="Drive", null=True, blank=True) Transmission = models.CharField(max_length=500,verbose_name="Transmission", null=True, blank=True) mfdate = models.DateField(auto_now_add=False, blank= True,null=True, verbose_name="Manufacturing Date") Mileage = models.CharField(max_length=500,verbose_name="Mileage", null=True, blank=True) EngineCode = models.CharField(max_length=500,verbose_name="Engine Code", null=True, blank=True) steering = models.ForeignKey(Steering, verbose_name="Steering", on_delete=models.CASCADE, default="") ExtColor = models.CharField(max_length=500,verbose_name="Ext Color", null=True, blank=True) Fuel = models.CharField(max_length=500,verbose_name="Fuel", null=True, blank=True) Seats = models.CharField(max_length=500,verbose_name="Seats", … -
Getting no reverse match at /post in django
I have been facing this issue. And I have a url name post-page-detail but then also getting error please See the error screenshot below. My html page <a href="{% url "post-detail-page" slug=post.slug %}"> <h2>{{post.tractor_company}} || {{post.tractor_model}}</h2> <pre><h5>{{post.implimentaion}}</h5> {{post.farmer}} Uplode Date : {{post.date}}</pre> </a> </div> URLs.py from . import views urlpatterns = [ path("",views.starting_page,name = "starting-page"), path("posts",views.posts,name = "post-page"), path("posts/<slug:slug>",views.post_detail,name="post-detail-page"), ] -
Celery SchedulingError - Redis : Authentication required
I have'a scheduled task in celery like this. #my_app.tasks @shared_task(ignore_results=True) def my_task(): print("running") #settings.py CELERY_BEAT = { 'my_scheduled_task': { 'task': 'my_app.tasks.my_task', 'schedule': datetime.timedelta(minutes=5) }, } I'm using rabbitMQ for broker. When i run the celery worker with beat. I'm getting this error : SchedulingError("Couldn't apply scheduled task my_scheduled_task: Authentication required.",) versions: celery==4.3.0 django-redis==4.8.0 -
nginx: [emerg] host not found in upstream when dockerizing a django/react project
I'm trying to dockerize a django/react project but i'm running into this error when running docker-compose up. i don't understand where the error come from. i'm new to docker. my goal is to deploy the frontend and the backend separately in one server. nginx: [emerg] host not found in upstream [emerg] 1#1: host not found in upstream "backend:8000" in /etc/nginx/conf.d/default.conf:2 nginx_1 | nginx: [emerg] host not found in upstream "backend:8000" in /etc/nginx/conf.d/default.conf:2 here is my code django's Dockerfile ENV DJANGO_SECRET_KEY $DJANGO_SECRET_KEY ENV DJANGO_CORS_ORIGIN_WHITELIST $DJANGO_CORS_ORIGIN_WHITELIST RUN mkdir /backend WORKDIR /backend COPY requirements.txt /backend/ EXPOSE 8000 RUN pip install -r requirements.txt COPY . /backend/ RUN python manage.py makemigrations RUN python manage.py migrate react's Dockerfile FROM node USER root WORKDIR /frontend COPY . /frontend ARG API_URL ENV REACT_APP_HOST_IP_ADDRESS $API_URL RUN yarn RUN yarn config set ignore-engines true RUN yarn build server's config upstream api { server backend:8000; } server { listen 8080; location /api/ { proxy_pass http://api$request_uri; } # ignore cache frontend location ~* (service-worker\.js)$ { add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; expires off; proxy_no_cache 1; } location / { root /var/www/frontend; try_files $uri $uri/ /index.html; } } docker-copose.yml version: '3' services: backend: build: context: ./ruelle_backend args: DJANGO_ALLOWED_HOSTS: http://ruelle-online.fr DJANGO_SECRET_KEY: anis1807 DJANGO_CORS_ORIGIN_WHITELIST: … -
It is possible to modify a env variable in django constance without reloading server?
I'm working with django constance to define some dynamic variables. When I modify some variable, the changes are not applied, so I have to stop django server and run again to see the applied changes according to that variable. Is there any way to change these variables without reloading the server? django constance painel -
Further filter the results of queryset in django
I have two basic models in django named Applications and Status and a third one to track the application statuses, named TrackApplicationStatus. So, every time the status of the application changes, a new record is added to the TrackApplicationStatus table. The current status of each application is the status of the most recent record of that table. The models are defined as: from django.db import models class Application(models.Model): name = models.CharField(max_length=100) class Status(models.Model): name = models.CharField(max_length=100, blank=False, unique=True) class TrackApplicationStatus(models.Model): created_at = models.DateTimeField(auto_now_add=True) application = models.ForeignKey(Application, on_delete=models.CASCADE, related_name='statuses') status = models.ForeignKey(Status, on_delete=models.SET_NULL, related_name='applications_status', null=True) class Meta: get_latest_by = ['created_at'] ordering = ['-created_at'] On the first step, I am retrieving the current statuses of each application with the following django query: current_statuses = TrackApplicationStatus.objects.order_by('application_id', '-created_at').distinct('application_id') The produced SQL query is the following: SELECT DISTINCT ON ("api_trackapplicationstatus"."application_id") "api_trackapplicationstatus"."id", "api_trackapplicationstatus"."created_at", "api_trackapplicationstatus"."application_id", "api_trackapplicationstatus"."status_id" FROM "api_trackapplicationstatus" ORDER BY "api_trackapplicationstatus"."application_id" ASC, "api_trackapplicationstatus"."created_at" DESC What I want to do next, is to get all applications with a specific status. In SQL terms I would apply a WHERE clause on the above result table as follows: SELECT sub.application_id FROM ( SELECT DISTINCT ON ("api_trackapplicationstatus"."application_id") "api_trackapplicationstatus"."created_at", "api_trackapplicationstatus"."application_id" as application_id, "api_trackapplicationstatus"."status_id" as status FROM "api_trackapplicationstatus" ORDER BY "api_trackapplicationstatus"."application_id" ASC, "api_trackapplicationstatus"."created_at" … -
make admin interface accessible while using uwsgi
I added uwsgi to serve up the Django app. but I wanted to still have access to the Django admin. but I seem to have made it so that all addresses on the localhost:8000 always point to that same index.html file. I'm fresh to the whole WSGI thing and setting up for production. What did I do wrong and how can I get the admin interface to correctly rout and display? I appreciate any help. Thank you. wsgi app application( { "REQUEST_METHOD": "GET", "SERVER_NAME": SimpleLazyObject(get_allowed_host_lazy), "REMOTE_ADDR": "127.0.0.1", "SERVER_PORT": 80, "PATH_INFO": "/admin/", "wsgi.input": b"", "wsgi.multiprocess": True, }, lambda x, y: None, ) urls.py urlpatterns += static("/media/", document_root=settings.MEDIA_ROOT) + [ url(r"^static/(?P<path>.*)$", serve), url(r"^", views.homepage, name="homepage"), url(r"^admin/", admin.site.urls), ] views.py def homepage(request): application_url = os.environ.get("APPLICATION_URL", "") dashboard_url = os.environ.get("DASHBOARD_URL", "") admin_url = os.environ.get("ADMIN_URL", "") return TemplateResponse( request, "home/index.html", {"application_url": application_url, "dashboard_url": dashboard_url, "admin_url": admin_url}, ) uwsgi.ini [uwsgi] die-on-term = true enable-threads = true http = :$(PORT) module = project.wsgi:application static-map = /static=/app/static master = true processes = 4 ignore-sigpipe = true ignore-write-errors = true disable-write-exception=true -
django celery kombu.exceptions.EncodeError
from sys import pycache_prefix when i run this gettging below error celery_task.delay(event_data) error: File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps return cls( File "/usr/lib/python3.8/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/home/ubuntu/baby_prod_backend/env/lib/python3.8/site-packages/kombu/utils/json.py", line 58, in default return super().default(o) File "/usr/lib/python3.8/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' kombu.exceptions.EncodeError: Object of type AttributeDict is not JSON serializable my celery task app = Celery("settings", broker=BASE_REDIS_URL) app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() CELERY_EAGER_PROPAGATES_EXCEPTIONS = True app.conf.broker_url = BASE_REDIS_URL app.conf.update( task_serializer="pickle", result_serializer="json", accept_content=["json", 'pickle'] ) @app.task(serializer='json') def partial_bid_created_event(event): transactionHash = transactionHash.hex() transaction_processed = ProcessTransaction.objects.filter(tnxid=transactionHash, event=event["event"]).count() if transaction_processed: return {"msg": "transaction already created"} please take a look what can be the issue . here using this task i am doing something in my django database below i added inside setting.py CELERY_EAGER_PROPAGATES_EXCEPTIONS = True CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' CELERY_ACCEPT_CONTENT = ['pickle', 'json'] tryed using json and pickle both not working . -
Migration does not create column in database
makemigrations and migrate are working fine with no error. but when i check database it does not created heres the model: class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,related_name='sub_service') service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) service_description = models.TextField( null=True, blank=True) duration = models.CharField(max_length=100,null=True,blank=True) I have added duration field later and its not giving me any error while running api django.db.utils.ProgrammingError: column service_list_services.duration does not exist LINE 1: ...", "service_list_services"."service_description", "service_l... i have tried deleting migration files and then migrating but still.. its not giving error while migrating but doesnot create row. tried this python manage.py migrate --fake still same -
'SettingsReference' object has no attribute '_meta'
Getting this error after changing the custom user table in the mid-project also after changing the name of the custom user class. -
Different URL Based On Condition In Django
I have a url like this: app_name = 'vineyards' urlpatterns = [ path('<str:parent>/<str:region>/<slug:slug>/', vineyard_detail, name="detail"), ] This is the absolute url in model: def get_absolute_url(self): return reverse('vineyards:detail', kwargs={'parent': self.region.region_parent, 'region': self.region.slug, 'slug': self.slug}) The <str:parent>/ is optional, it can be null. I want to ignore the <str:parent>/ if it is None So for example, i want the url is something like this: .../something/ Instead of this : .../None/something/ How can i do that? Is it possible? -
Subscription button with data validation
<form class="row row-cols-lg-auto g-2 align-items-center justify-content-end"> <div class="col-12" id="my_form"> <input id="emailfield" type="email" class="form-control" placeholder="Ingresa tu Email" required="required"> </div> <div class="col-12" id="thank_you" style="display: none;"> Gracias por subscribirse! </div> <div class="col-12"> <button type="submit" class="btn btn-primary-soft m-0" name="subscribirse" id="nextStep">Subscribirse</button> </div> </form> enter image description here what the script does is hidde the input element and show the "thanks message" this is fine, but before do this i need it to validate if input emailfield is validated. and show the "thanks message" only if that happent. Thanks! <script> var nextStep = document.querySelector('#nextStep'); nextStep.addEventListener('click', function (e) { e.preventDefault() // Hide first view document.getElementById('my_form').style.display = 'none'; // Show thank you message element document.getElementById('thank_you').style.display = 'block'; }); </script> -
Django Rest Framwork return serializer create() method response from view?
I want to bulk entry of product order. Here is my two models one is Order and another is OrderMap Order model is summary of order and OrderMap stores all of product order details. I have write a create method in OrderSerializer and everything is working ok but i can not trigger response to the view. How to do it? Please help me. Thanks in advanced. Here is my code: serializers.py class OrderMapSerializer(serializers.ModelSerializer): OrderNo = serializers.ReadOnlyField(source='order.orderno') class Meta: model = OrderMap fields = ('id', 'OrderNo', 'ItemCode', 'OrderQty', 'ReceivedQty') class OrderSerializer(serializers.ModelSerializer): OrderMapData = OrderMapSerializer(many=True, source='ordermaporder') class Meta: model = Order fields = "__all__" def create(self, validated_data): ordermap_set = validated_data.pop('ordermaporder') add_pro = Order.objects.create(**validated_data) for data in ordermap_set: OrderMap.objects.create( OrderNo=add_pro, OrderQty=data.get('OrderQty'), ItemCode=data.get('ItemCode'), ReceivedQty=data.get('ReceivedQty') ) return add_pro I want to return response from my view like this: if(): dict_response = {"error": False, "Title": "Success", "ico": "successIcon", "message": "Wellcome! Product item successfully added."} else: exceptions = [] for key in serializer.errors.keys(): exceptions.append({"field": key, "message": serializer.errors[key][0]}) dict_response = { "error": True, "status": 400, "message": "Your submitted data was not valid - please correct the below errors", "exception": exceptions } return Response(dict_response) -
Django Common Field Methods name and
clean(value, instance)—Validates the given value is appropriate for the model, and the instance it's assigned to. Internally, this defers to both to_python() and validate(), as well as processing a list of validators that were defined when the field was instantiated. It will return a corrected value if everything was valid, and will raise django.core.exceptions. ValidationError otherwise. • contribute_to_class(cls, name)—Configures the field for the class it’s attached to. One of the most important methods on fields, this is called when ModelBase is processing the attributes that were assigned to the model’s class definition. The cls argument is the model class it was assigned to, and name is the name it was given when it was assigned there. This allows fields the opportunity to perform any additional setup or configuration, based on this information. It usually doesn’t need to be called directly, but can be a useful way of applying a field to a previously-processed model. • db_type(connection)—Returns the database-specific column definition necessary for this field to store its data. Typically, this is only used internally, but as with some of the other attributes listed, if an application needs to access the database directly using some other tool, this can be a … -
How to scroll lock a Django HTML Web Page
I am currently using a page that has a list of in-line forms However when the user enters submits each form (line) they are sent back to the top of the page. This becomes really tedious as the users need to enter data quickly and can't when they need to scroll for 2 minutes every time they add an entry. Does anyone know how to implement a scroll lock to stock this from happening -
Why same lines of code taking longer time to execute in Django's project environment than running as python script?
I have executed few line of code inside my Django project environment as well as a simple python script. Their code execution times are as follows Django project's environment (django_env) vak@vishal:/vk$ python3 cev05_script.py speed: 691.2 mm/s Code Execution Time : 43.4 sec Run outside Django's environment as a python script. (py_practice) vak@vishal:/vk$ python3 cev05_script.py speed: 691.2 mm/s Code Execution Time : 0.67 sec I have created environments with 'pipenv' package. Why this is happening? Thanks! -
Django Custom Storage System
I want to build a custom storage system in Django, so that users can upload files to a mounted location. I already saw the official Django guide on this matter (https://docs.djangoproject.com/en/3.2/howto/custom-file-storage/), but I can't wrap my head around it. The idea is to use another location on the server, not the MEDIA_ROOT, and it should also be possible to access the files outside the app. Could someone give me some ideas? -
Filter List in Django JSON Field with string contains
My Django JSON field contains a list of values like ["N05BB01", "R06AX33"]. atc_code = JSONField(default=list()) I would like to filter this field, for 'does any string in list contain "N05"?'. -
postgres wont list my database in heidisql
I seem to have done everything right, but still it wont populate my table in heidisql. I am using docker. My Heidi is like this. I have put my database name in database which is hidden above. Also my docker is up with both django and postgres running. After opening heidisql, it is empty in public, authentication is working but it wont populates the tables. My local.yml is like this: env_file: - ./.envs/.local/.postgres ports: - "5432:5432" my postgres file in local env POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=example POSTGRES_USER=aYeyCmaatmik POSTGRES_PASSWORD=oyOucWOu185tUIPavYeyCmXUncS Here in heidi, i have used the superuser postgres which was initally setup during the installation not the above one in postgres file which is the correct way i think.