Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels __init__() got an unexpected keyword argument 'scope'
I have been trying to set up a basic Django Channels project based on the tutorial, but I am getting this error. I used the Django python shell to test if Redis is working and it is. I am running Daphne with 'Daphne my_project.asgi:application. I could not find any similar questions or documentation on the problem. Please let me know if you need to see any other parts of my code. Any help is greatly appreciated! consumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class TestConsumer(WebsocketConsumer): def connect(self): self.group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.group_name, { 'type': 'chat_message', 'message': message } ) def chat_message(self, event): message = event['message'] self.send(text_data=json.dumps({ 'message' : message })) project routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import main.routing import sockets.routing application = ProtocolTypeRouter ({ 'websocket' : AuthMiddlewareStack( URLRouter( sockets.routing.websocket_urlpatterns ) ) }) asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'socialapp.settings') django.setup() application = get_default_application() project settings ASGI_APPLICATION = 'socialapp.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } -
AJAX not redirect in Django
Hi I have been reading this Django view not rendering after Ajax redirect and have code as below that intends to redirect to /main if successfully authenticated or alert if otherwise. $(document).ready(function(){ $(".btn").click(function (ev) { ev.preventDefault() // cancel form submission if ($(this).attr("value") == "auth") { console.log("CHECK 1"); $.ajax({ type:'POST', url:'/getotp2', data:{ username:$('#username').val() ,csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function server_response(response) { //console.log('POST1 success') } }); } else if ($(this).attr("value") == "login") { console.log("CHECK 2"); $.ajax({ type:'POST', url:'/otpcheck', data:{ username:$('#username').val(), otp:$('#otp').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function server_response(response) { const r = JSON.parse(response); console.log(r.authresult); if (r.authresult=='success'){ window.location.href='/main'; //also tried with './main','../main',''http://127.0.0.1:8000/main', none worked } else{ alert("Auth Failed"); } } }); } }); }); views.py def otplogin(request): return render(request,'esearch/otplogin.html') def getotp2(request): logout(request) global otp username =otp = '' if request.POST: username = request.POST.get('username','') otp = pyotp.TOTP('base32secret3232').now() OTPEmail('You Auth',username,[],'Your auth is '+otp) print ('POST'+username) print ('POST'+otp) return JsonResponse(json.dumps({'username':username,'otp':otp}),safe=False) def otpcheck(request): if request.POST: otpentered=request.POST.get('otp','') print(otpentered) authresult='fail' if otpentered==otp: authresult='success' print('POST'+authresult) else: print('POST'+authresult) return JsonResponse(json.dumps({'authresult':authresult}),safe=False) @login_required(login_url='/otplogin') def search_index(request): ###### urls.py urlpatterns = [ path('main', views.search_index, name='main'), path('otplogin', views.otplogin,name="otplogin"), path('getotp2', views.getotp2, name="getotp2"), path('otpcheck', views.otpcheck, name="otpcheck"),] Console prints everything fine, but the page get redirected to http://localhost:8000/otplogin?next=/main instead of wanted http://localhost:8000/main. I also tried to set window.location.href='/main' to ='./main', ='../main' … -
Installing psycopg2 command 'gcc' failed with exit status 1
I'm trying to install psycopg2 but pip install psycopg2 brings to error: command 'gcc' failed with exit status 1 Command line tools are installed MacOS 10.15 -
Error when fetching the logged in user details
Login Code class loginController(View): def post(self, request): username = request.POST.get('username') password = request.POST.get('password') userobj = authenticate(username = username, password = password) if(userobj != None): login(request, userobj) return redirect('myprofileapp:profile') Once the user is authenticated, navigated to profile page. When this line executes if(request.user.is_authenticated):, I get an error. class accountController(View): def get(self, request): if(request.user.is_authenticated): return HttpResponse(request.user) 'User' object is not iterable -
Nginx append a trailing slash to the url
I am having an issue in Safari and IE where a django redirect does not include the authorization headers. This leads to the requests being rejected. These redirects happen with the URL does not end with a /. So I am trying to handle adding the / in the nginx config before it is passed to the app. Here is my nginx config: server { server_name ~^((stage|prod)-)?chalktalk-react-40.*; listen 28000 default_server; location ~ ^/static/(?P<file>.*) { root /chalktalk/var/chalktalk-react-40; add_header 'Access-Control-Allow-Origin' $cors_origin; # Inform downstream caches to take certain headers into account when reading/writing to cache. add_header 'Vary' 'Accept-Encoding,Origin'; try_files /staticfiles/$file =404; } location ~ ^/media/(?P<file>.*) { root /chalktalk/var/chalktalk-react-40; try_files /media/$file =404; } location / { if ($request_uri ~ ^([^.\?]*[^/])$) { return 301 $1/; } } # API endpoints have their own authentication and authorization # schemes, so we bypass basic auth. location ~ ^/(api|admin|ws)/ { try_files $uri @proxy_to_app; } rewrite ^(.*)/favicon.ico$ /static/pages/homepage/logo-nonname.png last; location @proxy_to_app { proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_set_header X-Forwarded-Port $http_x_forwarded_port; proxy_set_header X-Forwarded-For $http_x_forwarded_for; proxy_set_header Host $http_host; proxy_read_timeout 1200; proxy_redirect off; proxy_pass http://chalktalk-react-40_app_server; } # Forward to HTTPS if we're an HTTP request... if ($http_x_forwarded_proto = "http") { set $do_redirect "true"; } # Run our actual redirect... if ($do_redirect = "true") … -
How do i create product with category and show the categories in the product list along with the uploaded product
here's my problem, i wanted to add products with category like the admin interface but from my product create page. i created models,forms and views for category but it is not working ...how to do this? models.py #added category model class Category(models.Model): name = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique=True ,db_index=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Product(models.Model): # added category as a foregn key category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) title = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10000) summary = models.TextField(blank=False, null=False) featured = models.BooleanField(default=False) # null=True, default=True slug=models.SlugField(unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) def get_absolute_url(self): return reverse("products:product-detail", kwargs={"id": self.id}) forms.py # when submitting form it says not NULL constraint failed:: products_product.category_id, tried by deleting the migrations and db as well. after deleting the migrations it works (but not PERMANENTLY, shows the same for the next 2nd or 3rd submit) but shows nothing in product list page class ProductForm(forms.ModelForm): title = forms.CharField(label='', widget=forms.TextInput(attrs= {"placeholder": "Product Name"})) description = forms.CharField( required=False, widget=forms.Textarea( attrs={ "placeholder": "Your description", "class": "new-class-name two", "id": "my-id-for-textarea", "rows": 5, 'cols': 50 } ) ) summary = forms.CharField( required=False, widget=forms.Textarea( attrs={ "placeholder": "Your summary", "class": "new-class-name two", "id": "my-id-for-textarea", "rows": 5, … -
Issue while redirect from one page to another
I am using DJango 2.2.6 Profile App app_name = 'myprofileapp' urlpatterns = [ path('profile', accountController.as_view(), name='account') ] Auth App app_name = 'authapp' urlpatterns = [ path('login', loginController.as_view(), name='login') ] Below is the code to login user. In case logged in successfully then sends to profile page. class loginController(View): def post(self, request): username = request.POST.get('username') password = request.POST.get('password') userobj = authenticate(username = username, password = password) if(userobj == None): return HttpResponse("Not Found") else: login(request, userobj) return redirect('profile') After this code login(request, userobj) if I write return render(request, 'profile.html') then the url remains login. and when I write return redirect('profile'), it says Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name. Am I missing anything? -
How to create a new column for Django Model field and add it to the existed function?
from django.db import models class Proline(models.Model): ln_num = models.CharField( primary_key=True, max_length=32, blank=True) ev_key = models.CharField(max_length=32, blank=True) ln_id = models.CharField(max_length=32, blank=True) pro_id = models.CharField(max_length=32, blank=True) def getProId(self): return self.pro_id I have a following model in models.py where i use getProId() in different parts of the code. Now i have a new column(key_id) to be added on certain condtion(if rules = 'Q' and i import rule column from other python file ) and i dont want to change the function in all parts of the code where i have getProId() so instead i wrote from django.db import models from something.rules import * class Proline(models.Model): ln_num = models.CharField( primary_key=True, max_length=32, blank=True) ev_key = models.CharField(max_length=32, blank=True) ln_id = models.CharField(max_length=32, blank=True) pro_id = models.CharField(max_length=32, blank=True) key_id = models.CharField(max_length=32, blank=True) def getProId(self): if rules == 'Q': return self.key_id else: return self.pro_id so does this work without effecting the other parts of the code where i need to not write this condition everywhere and handle this in Models.py? -
how to make drf HyperlinkedModelSerializer elegantly work with app_name?
I am using drf in a django project in a dedicated app which I namespaced via app_name as following: # api/urls.py from django.urls import include, path from rest_framework import routers from . import views app_name = 'drf' router = routers.SimpleRouter() router.register('segments', views.SegmentViewSet) urlpatterns = [ path('', include(router.urls)), ] # api/serializers.py from rest_framework import serializers from segment.models import Segment class SegmentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Segment fields = ['id', 'url', 'name'] # api/views.py from rest_framework import viewsets from .serializers import SegmentSerializer from segment.models import Segment class SegmentViewSet(viewsets.ModelViewSet): queryset = Segment.objects.all() serializer_class = SegmentSerializer calling endpoint /drf/segments/ results in the following error: ImproperlyConfigured at /drf/segments/ Could not resolve URL for hyperlinked relationship using view name "segment-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Request Method: GET Request URL: http://localhost:8000/drf/segments/ Django Version: 2.2.7 Python Executable: /Users/udos/.virtualenvs/ts/bin/python Python Version: 3.6.4 . . . to "fix" this, I have to add the following code to the serializer: url = serializers.HyperlinkedIdentityField( view_name='drf:segment-detail', ) resulting in: # api/serializers.py from rest_framework import serializers from segment.models import Segment class SegmentSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='drf:segment-detail', ) class Meta: model = Segment fields = ['id', 'url', 'name'] … -
Set media url and media root for django production. Ckeditor
I have the following media url and media root settings in my django application. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'app/media') #ckeditor data CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, 'uploads') CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' CKEDITOR_MEDIA_PREFIX = '/media/ckeditor/' CKEDITOR_UPLOAD_PREFIX = 'http://media.lawrence.com/media/ckuploads/' CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_IMAGE_BACKEND = "pillow" I am using a ckedidor which receives the following error: Not Found: /media/home/app/app/app/media/uploads/zen404/2019/11/08/1234_thumb.jpg but my path to this file looks like this /home/app/app/app/media/uploads/zen404/2019/11/08/1234_thumb.jpg how to properly configure the cekidor to refer to the path written above?Any help will be appreciated. -
Djano Modelform Many2Many problem: [{'id': ['Select a valid choice. That choice is not one of the available choices.']}]
I am implementing an interface where you can setup relationships between categories. Therefore, I use a many to many relationship and want to use a formset to set relationships. The problem is that I cannot save the formset. It always fails with the error: [{'id': ['Select a valid choice. That choice is not one of the available choices.']}] Models class Category(TimeStampedModel): name = models.CharField(_('Name'), max_length=255) active = models.BooleanField(_("Active"), default=False) relationship = models.ManyToManyField('Category', through='CategoryRelationship', related_name='category_relationship') objects = models.Manager() categories = CategoryManager() def __str__(self): return "{}".format(self.name) class Meta: ordering = ("name",) class CategoryRelationship(TimeStampedModel): child_category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name='is_child', null=True, default=None) parent_category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name='is_parent', null=True, default=None) country = CountryField() Forms class CategoryRelationShipFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = 'post' self.layout = Layout( Tr( Td(HTML("""{{ form.instance }}""")), Td(Field('child_category')), Td(HTML("""{{ form.DELETE }}""")) ), HTML("{{ form.id }}") ) class CategoryRelationShipForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.initial['child_category'] = self.instance class Meta: model = CategoryRelationship fields = ['child_category'] #widgets = { # 'child_category': forms.HiddenInput() #} CategoryRelationShipFormSet = modelformset_factory(CategoryRelationship, CategoryRelationShipForm, can_delete=True, extra=0) -
How to keep the original text formatting in TextField django admin
How to keep the original text formatting (e.g. new lines, bold text) in TextField django admin. For example, I want to place text on two lines. But in html code I see only one line "Line1 Line2" I found solution --- usage of html tags, but it's not suitable for me. How to keep the original text formatting without html tags in django? Any design advises? -
Saving a Pandas DataFrame column to a ForeignKey Django model field
So let me explain briefly first. I have some DataFrames that I want to save as a Django model. I use the Pandas to_sql function for this, which has worked brilliantly for me untill now. So for example I have this Order model: class Order(models.Model): id = models.BigIntegerField(primary_key=True) item_id = models.CharField(max_length=255, null=True, blank=True) ean = models.BigIntegerField(null=True, blank=True) date = models.DateTimeField(null=True, blank=True) My DataFrame has exactly the same columns that match the Django model fields. So I run this to save it to the Django model: # Save to SQL user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) # Use replace for tables that already exist and set appropiate types with sqlalchemy | https://docs.sqlalchemy.org/en/13/core/type_basics.html#sql-standard-and-multiple-vendor-types df_final.to_sql('orders_order', dtype={'id': sqlalchemy.types.BIGINT(), 'item_id': sqlalchemy.types.VARCHAR(), 'ean': sqlalchemy.types.BIGINT(), 'date': sqlalchemy.DateTime(), }, con=engine, if_exists='replace', index=False) All good, works perfect. The DataFrame gets saved and I can view all seperate entries in the Django Admin. However I would like to save a DataFrame to a Django model which has a ForeignKey relationship with the Orders model. So in my point of view I should just populate the fields with the appropiate data. So for this model with a … -
How to correctly display data stored in an external model without refreshing the page?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) I was reading … -
Why does a particular model cause migrations every time I use `makemigrations`?
I have a Django application called "proxy". It's models.py content looks like this: from __future__ import unicode_literals from django.db import models class Proxy(models.Model): class Meta: verbose_name = u"Прокси" verbose_name_plural = u"Прокси" TYPE = ((1, "http"), (2, "socks4"), (3, "socks5")) name = models.CharField(max_length=200, verbose_name=u'Прокси') label = models.CharField(max_length=200, verbose_name=u'Лейбл') ip = models.CharField(max_length=200, verbose_name=u"IP") port = models.CharField(max_length=200, verbose_name=u'Порт') login = models.CharField( max_length=200, verbose_name=u'Логин', null=True, blank=True) password = models.CharField( max_length=200, verbose_name=u'Пароль', null=True, blank=True) kind = models.IntegerField( verbose_name='Тип Прокси', default=1, choices=TYPE) expiration_date = models.DateTimeField( verbose_name="Срок окончания валидности", null=True, blank=True) def __str__(self): return self.name class ProxyList(models.Model): class Meta: verbose_name = "Лист" verbose_name_plural = "Листы" name = models.CharField(max_length=200, verbose_name=u'Название листа') alias = models.SlugField(max_length=300, verbose_name=u'Адрес листа') proxies = models.ManyToManyField(Proxy, verbose_name=u'Прокси') def __str__(self): return self.name The problem I am facing is that, every time I try to run makemigrations, it creates meaningless migration files, as shown below: makemigrations output: Migrations for 'proxy': proxy/migrations/0112_auto_20191110_1658.py - Alter field proxies on proxylist Migrations for 'serversettings': serversettings/migrations/0052_auto_20191110_1658.py - Alter field top50_proxy on serversettings Migrations for 'top50': top50/migrations/0066_auto_20191110_1658.py - Alter field proxy on scriptproxy generated migration file: # Generated by Django 2.2.1 on 2019-11-10 13:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proxy', '0111_auto_20191110_1640'), ] operations = [ migrations.AlterField( model_name='proxylist', name='proxies', … -
Initial form value for Tempus Dominus TimePicker field in Django
I'm trying to figure out a way to load an initial value into Tempus Dominus TimePicker field, but I'm failing miserably... I have configured my forms/views/templates in the following way: forms.py from tempus_dominus.widgets import TimePicker class FormUpdate(forms.Form): time = forms.TimeField( required=True, widget=TimePicker( options={ 'format': 'HH:mm A', 'icons': { 'time': 'far fa-clock', 'date': 'far fa-calendar-alt' }, }, attrs={ 'input_toggle': True, 'input_group': True }), ) views.py f_form = FormUpdate({'time':'12:00'}) context.update({'form': f_form}) template = "update.html" return render(request, template, context) update.html <div class="container"> <form method="post"> {% csrf_token %} <div class="row"> <div class='col text-left'> {{ form.as_p }} </div> </div> </form </div> I have also tried f_form = FormUpdate(initial=={'time':'12:00'}) but neither worked. I found a similar issue here: Tempus Dominus Set Loaded Value but wanted to check if there is really no other way to achieve this or have I missed something? -
Django GeoIP2 installation
I have been trying to install GeoIP2 in my Django project without any success, I have seen similar questions here but have not find a solution for my project. I suspect my issue is within my settings.py, I am not quite sure that I have linked to the files in a correct matter. Any thoughts what I did wrong? My Middleware MIDDLEWARE = ( ..., 'django.contrib.sessions.middleware.SessionMiddleware', 'geoip2_extras.middleware.GeoIP2Middleware', ... ) Here is my settings.py #GEOIP_PATH = os.path.dirname(__file__) GEOIP_PATH = '/djangos/project/app/Geoip/' GEOIP_COUNTRY = 'GeoLite2-Country.mmdb' GEOIP_CITY = 'GeoLite2-City.mmdb' How I import GeoIP2 from django.contrib.gis.geoip2 import GeoIP2 In my template {{ request.geo_data.city }} -
Problem with staticfiles while DEBUG=FALSE Django
When DEBUG = TRUE the site is working fine, but in my log file i have: WARNING [django.server:154] "GET /static/bootstrap/css/bootstrap.min.css HTTP/1.1" 404 1717 When DEBUG = FALSE error 500 occurs and in log file i have: ERROR [django.request:228] Internal Server Error: /topics/ Traceback (most recent call last): ... File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\staticfiles\storage.py", line 420, in stored_name raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'bootstrap/css/bootstrap.min.css' Here my settings.py: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Static files (CSS, JavaScript, Images) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_TMP = os.path.join(BASE_DIR, 'static') os.makedirs(STATIC_TMP, exist_ok=True) os.makedirs(STATIC_ROOT, exist_ok=True) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) django_heroku.settings(locals()) In my base.html: <link href="{% static '/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> I tried changing this line to: <link href="static/bootstrap/css/bootstrap.min.css" rel="stylesheet"> The site has earned, but the errors in log file remain the same. And in CLI i have: The system cannot find the specified path: 'C:\\Users\\admin\\Desktop\\my_project\\staticfiles/bootstrap/css/bootstrap.min.css' -
How to store fetched JSON data in SQLite using Django/Python
this is my very first attempt to work with Django Models and I keep making small steps but got stuck for the moment. I would like to store fetched data from a third party API into my SQLite DB using Python/Django (I build my webapp on top of Django). My idea in theory is as follows: Fetch the data using the request library. Manipulate it to make it Python conform extract the data by assigning it to variables push the data to the SQLite DB using Django model fetch the SQLite data to render the frontend Now this is what I have so far: Quotes_app/Models.py: from django.db import models import json import requests class ratesEUR(models.Model): timestamp = models.IntegerField() base = models.CharField(max_length=3) date = models.DateField(auto_now=False, auto_now_add=False) rates = models.DecimalField(max_digits=8, decimal_places=4) def __str__(self): return self.rates response = requests.get("http://data.fixer.io/api/latest?access_key=XXX&base=EUR") print(response.json()) rates_EUR = json.loads(response.content.decode('utf-8')) timestamp = rates_EUR[timestamp] base = rates_EUR[base] date = rates_EUR[date] rates = rates_EUR[rates] rates_new = ratesEUR.objects.create(timestamp=timestamp, base=base, date=date, rates=rates) rates_new.save() The json response looks like follows: { "success": true, "timestamp": 1573382946, "base": "EUR", "date": "2019-11-10", "rates": { "AED": 4.047045, "AFN": 86.223727, "ALL": 123.086065, "AMD": 525.791674, [...] } Besides the following error, I have some more questions on this setup shown at … -
Setup the VSCode debugger for python 2.7 and Django 1.11
I already setup a debugger for an existing django 1,11 project on vscode with the Microsoft python extension, but this will only works on http://127.0.0.1:5000/ (the homepage) I need this debugger to be hooked to my already running server on http://localhost:8000/ I need a setup that allows me to debug on vscode, make the code stop at specific breakpoints, debug code for various URLs using google chrome. This is my launch.json { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true } ] } Python 2.7 Django 1.11 Visual Studio Code MacOS Catalina Please help. -
Django "POST" request by using button and "Reverse for 'parsepdf' not found. 'parsepdf' is not a valid view function or pattern name." error
I pass "dictionary" data to the template And template HTML code looks like this <h1>PDF paths</h1> <!DOCTYPE html> <html lang="en"> <head> <title>PDF paths</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <td><B>id</B></td> <td><B>uuid</B></td> <td><B>user_web_uuid</B></td> <td><B>inspectionUploadType</B></td> <td><B>uploadRoute</B></td> <td><B>createdAt</B></td> <td><B>status</B></td> <td><B></B></td> </tr> </thead> <tbody> {% for one_row in out_list %} <tr> <form action="{% url 'pdfparseapp:parsepdf' %}" method="POST" class="post-form"> {% csrf_token %} <td>{{one_row.0}}</td> <td>{{one_row.1}}</td> <td>{{one_row.2}}</td> <td>{{one_row.3}}</td> <td>{{one_row.4}}</td> <td>{{one_row.5}}</td> <td>{{one_row.6}}</td> <td><button type="submit" class="save btn btn-default">Parse</button></td> </form> </tr> {% endfor %} <tbody> </table> </body> The output screen looks like this And if I click "Parse" button, I want to grab "one row data (red squre)" and want to go to another view's function to process data, for example, def process_data(request): id=request.POST["id"] uuid=request.POST["uuid"] user_web_uuid=request.POST["user_web_uuid"] inspectionUploadType=request.POST["inspectionUploadType"] uploadRoute=request.POST["uploadRoute"] createdAt=request.POST["createdAt"] status=request.POST["status"] # Perform algorithm code using above data....... Since I'm new to web and django, I'm not sure how to do it. And I got "Reverse for 'parsepdf' not found. 'parsepdf' is not a valid view function or pattern name." error, with above template HTML code Please guide me. -
Displaying framework message.error DJANGO
I am creating an app when a user can search for recipes by inputing some ingredients in search-field. I would like to do that when search-field is empty or string is empty a user get error.message 'Please put input.' But after i have implemented message.error into views and template it only returns the same page without this informaton 'Please put input.'. Do you know what i made wrong here? My views: from django.shortcuts import render from django.db.models import Q #new from .models import Recipe from .models import Ingredient from django.contrib import messages from django.shortcuts import redirect def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') if not query or query == ' ' or query == ' ' or query == ' ': messages.error(besos, "Please put input") return redirect('drink_list') else: q = Q() for queries in query.split(): q |= (Q(ingredients__ingredient_name__icontains=queries)) #why it look for 'sok z cytryny' and show as well sok z limonki results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) My template search_results: {% if results %} {% for drink in results %} <div> <p>{{ drink.recipe_name }}</p> <p>Preparation: {{ drink.preparation }}</p> <p>Ingredients: {% for ingredient … -
Does not work for photo uploads in cekidor. After uploading the application to the production. Django
I uploaded my application to my production server and I can't understand why photo upload is not working. Everything works great on my local machine. My configuration for cekidor and media files looks like this. settings.py INSTALLED_APPS = [ [...], 'ckeditor', 'ckeditor_uploader', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'app/media') STATIC_ROOT = os.path.join(BASE_DIR, '../static/') #cekidor data CKEDITOR_UPLOAD_PATH = os.path.join(MEDIA_ROOT, 'uploads') CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' CKEDITOR_MEDIA_PREFIX = '/media/ckeditor/' CKEDITOR_UPLOAD_PREFIX = 'http://media.lawrence.com/media/ckuploads/' CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_IMAGE_BACKEND = "pillow" urls.py urlpatterns = [ [...], path('ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Errors visible in the file gunicorn-error.log [...] Not Found: /media/home/app/app/app/media/uploads/zen404/2019/11/08/projekt-bez-tytuu-81-1.jpg Not Found: /media/home/app/app/app/media/uploads/zen404/2019/11/10/img21_tliORIo.jpg Not Found: /media/home/app/app/app/media/uploads/zen404/2019/11/10/img21_tliORIo.jpg Not Found: /media/home/app/app/app/media/uploads/zen404/2019/11/10/img21_tliORIo.jpg My gunicorn file #!/bin/sh NAME="app" DIR=/home/app/app USER=app GROUP=app WORKERS=3 BIND=unix:/home/app/run/gunicorn.sock DJANGO_SETTINGS_MODULE=app_rama.settings DJANGO_WSGI_MODULE=app_rama.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- How can I start debugging this? I have no idea why this may not work. Only files sent by cekidor are not displayed. Normal photos uploaded using admin and models.ImageField are displayed correctly. The local machine displays everything correctly (cekidor image and upload by ImageField). I tried to change the folder permissions … -
send my response for 2 groups via self.channel_layer.group_send()
I'm using django channels 2 , for making a one to one private chat. And after spending a LOT OF TIME i'm just out of any other solution for my problem I have two html files: inbox.html shows list of all user history that i had chat with them and it is ordered by last updated time(last chat with each user) and if you click on one of them then you see the other file showing the chat room. I want to use my ChatConsumer for two urls. I send my_response in websocket_receive function and then receive it in socket.onmessage in template THE PROBLEM IS I can't do it for both urls. I want to send it into my inbox too because I want to reOrder the chat user lists every time I send a message.so I made a group for inbox in my consumers as I did for my chat_room in websocket_connect function: inbox_room = f"inbox_{me.id}" self.inbox_room=inbox_room await self.channel_layer.group_add( inbox_room, self.channel_name ) and then I tried two ways: 1- just use channel_layer.group_send for both of them: await self.channel_layer.group_send( self.chat_room, self.inbox_room, { "type": "chat_message", "text": json.dumps(my_response) } ) and then using : async def chat_message(self,event): await self.send({ "type": "websocket.send", "text":event['text'] … -
Django throwing 'there is no unique constraint matching given keys for referenced table' error ForeignKey relationship
So I have these two models: class Shipment(models.Model): id = models.BigIntegerField(primary_key=True) reference = models.BigIntegerField(null=True, blank=True) date = models.DateTimeField(null=True) order_id = models.ForeignKey('orders.Order', null=True, blank=True, on_delete=models.SET_NULL) transport_id = models.BigIntegerField(null=True, blank=True) class Order(models.Model): id = models.BigIntegerField(primary_key=True) item_id = models.CharField(max_length=255, null=True, blank=True) ean = models.BigIntegerField(null=True, blank=True) date = models.DateTimeField(null=True, blank=True) price = models.DecimalField(null=True, blank=True, max_digits=10, decimal_places=2) quantity = models.IntegerField(null=True, blank=True) title = models.TextField(null=True, blank=True) delivery_date = models.DateTimeField(null=True, blank=True) fulfilment_method = models.CharField(max_length=3, choices=FULFILMENT_CHOICES, default='FBB') Why is Django giving me this error: ile "/home/raf/Development/ehibol/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "orders_order" I want to connect the order_id field of the Shipment model to the ID field of the Order model. Which I set as a primary key. Why am I still getting this error then?