Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery beat not sending task to worker in heroku, configured in a single dyno in free tier
I am making a website, where the user has to accept an agreement and then an expiration date is set for the user. On that date the contract is supposed to get expired by setting a contract_expired boolean field to True and sending an email to the respective user about the same. I used celery beat for this. Now since the site is in tessting phase, it is hosted in a free tier dyno in heroku, so I had to configure one dyno for web and the other for both celery worker and beat. I scheduled a task for beat where it would run daily on 9 am, to check the exipiries for the users and then do the work as mentioned above. This function was running correctly when I was testing it in the localhost, i.e., by running two seperate terminals for worker and beat. But today at 9 am it did not run in heroku. Below are the codes that i wrote for the entire process procfile release: python manage.py migrate web: gunicorn jgs.wsgi --log-file - celeryworker: celery -A jgs.celery worker & celery -A jgs beat -l INFO & wait -n celery.py from __future__ import absolute_import, unicode_literals import … -
How to use temporary file from form upload - Python Django
I have a form where users can upload up to 1,000 images at a time. I have changed my FILE_UPLOAD_MAX_MEMORY_SIZE in Django settings to 0 so all files uploaded via a form are written to a temp directory in my root folder. I am then trying to process the images with OpenCV. original_img = cv2.imread(temp_image.temporary_file_path()) gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY) temp_image.temporary_file_path() This returns the absolute file path of the temp image in a string format So I put that in the cv2.imread, however, it creates a NoneType instead of a numpy array like it should and then my program cannot run when it reaches gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY) How do I read the temporary file into OpenCV? Any help is much appreciated. -
Issue finding which comment to reply to using django-mptt for nested comments in a blog
I'm trying to create a nested comment system with djano-mptt. I have got it working and the comments are displaying as designed. However, when the issue I'm having is coming up with the logic for the user to choose which comment to reply to. Through the form I can display all the post and parent field and that allows the user to select a post and comment. Although the issue being they can comment on any post and any comment in the list. Trying to implement logic where if the user is on that post they can only comment on that post and can choose which comment (if they want) to reply to. Here is the model: class Comment(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class MPTTMeta: order_insertion_by = ['created_on'] def __str__(self): return f"Comment {self.body} by {self.name}" The view: def CommentView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.name = request.user.username comment = comment_form.save(commit=False) comment.post = post comment.save() else: comment_form = CommentForm() return HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) The form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('post', 'body', 'parent',) labels = { … -
no such table: users_customuser in Django
I am trying to create an extended Custom User model that adds a level field of 0 to the User model which is not displayed on the form. But when I try to do this, I get the error no such table: users_customuser. I am new to Django. How can I implement what I described earlier and what I am doing wrong? Just in case I have done migrations... Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users … -
jQuery .addClass applying to everything
I have a like button that uses jQuery. The like button works as expected however due to the way I have it setup it changes every icon on the page to a heart code: if (data.liked) { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $("i").addClass("fa fa-heart-o liked-heart"); //problem line } else { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $("i").addClass("fa fa-heart-o unliked-heart"); //problem line From what i userstand the issue is that I am appending the class fa fa-heart-o ... to all i elements. How can I just apply it to the like button full code: <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $( "i" ).addClass( "fa fa-heart-o liked-heart" ); } else { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $( "i" ).addClass( "fa fa-heart-o unliked-heart" ); } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> <a class="like-btn" data-href='{{ post.get_api_like_url }}' data-likes="{{ post.likes.count }}" href="{{ post.get_like_url }}"><i class="{% if userliked %}fa fa-heart-o … -
AttributeError: 'FlaubertForSequenceClassification' object has no attribute 'predict'
I am trying to classify new dataset from best model after loading but I get this error: best_model_from_training_testing = './checkpoint-900' best_model= FlaubertForSequenceClassification.from_pretrained(best_model_from_training_testing, num_labels=3) raw_pred, _, _ = best_model.predict(test_tokenized_dataset) predictedLabelOnCompanyData = np.argmax(raw_pred, axis=1) Traceback (most recent call last): File "/16uw/test/MODULE_FMC/scriptTraitements/classifying.py", line 408, in <module> pred = predict(emb, test_model) File "/16uw/test/MODULE_FMC/scriptTraitements/classifying.py", line 279, in predict raw_pred, _, _ = model.predict(emb_feature) File "/l16uw/.conda/envs/bert/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1130, in __getattr__ raise AttributeError("'{}' object has no attribute '{}'".format( AttributeError: 'FlaubertForSequenceClassification' object has no attribute 'predict' -
Run Djano Project On Github
I am new on Full Stack developer. I make a Django project it is run on localhost:8888. I want to run it on github. But I don't know how i do it. Please, Help me. How i run Django project on Github. -
How to get username from user id in template
This is probably a simple answer but I cant figure it out. I have a comment system on my blog. I need to get the username from the user id. I get the id from which is a fk to the users table {{child_comment.parent_userdata_id}} Usually when I need to do this I just user .username but it doesn't seem to work in this case -
How to save MultyPlygon in Django model field
I'm trying to save MultyPlygon to Dajngo MultiPolygonField but get this error: TypeError: Cannot set Plot SpatialProxy (MULTIPOLYGON) with value of type: <class 'shapely.geometry.multipolygon.MultiPolygon'> My actual code is model.py: ... poligon = gis_models.MultiPolygonField(verbose_name=_('Polygon'), blank=True, null=True) ... gml_parser.py: self.plot.poligon = geometry_plot self.plot.save() The geometry_plot object type is <class 'shapely.geometry.multipolygon.MultiPolygon'> Any idea ? Thanks in advance. -
Logging in Django does not work when using uWSGI
I have a problem logging into a file using python built-in module. Here is an example of how logs are generated: logging.info('a log message') Logging works fine when running the app directly through Python. However when running the app through uWSGI, logging does not work. Here is my uWSGI configuration: [uwsgi] module = myapp.app:application master = true processes = 5 uid = nginx socket = /run/uwsgi/myapp.sock chown-socket = nginx:nginx chmod-socket = 660 vacuum = true die-on-term = true logto = /var/log/myapp/myapp.log logfile-chown = nginx:nginx logfile-chmod = 640 Thanks in advance -
Is there any other option for on_delete other than models.CASCADE for a ForeignKey in Django models>
Why is the on_delete property of a ForeignKey in a Django model not default? That should be the case if there is no other option other than models.CASCADE. Is there any other option for the on_delete property? -
URL with multiple parameters throws a NoReverseMatch error
I aim to redirect the view after the form has been saved. However django keeps throwing a NoReverseMatch error. Is there a step that I've missed or a misconfiguration? views.py def add_carpet(request): context_dict = {} carpet_form = forms.CarpetForm() if request.method == "POST": carpet_form = forms.CarpetForm(request.POST) if carpet_form.is_valid(): carpet = carpet_form.save() return redirect(reverse( "dashboard_add_images", kwargs={ "model_type": "carpet", "id": carpet.id } )) context_dict["carpet_form"] = carpet_form return render( request, 'dashboard/add_carpet.html', context_dict ) def add_images(request, model_type, id): ... urls.py urlpatterns = [ path('add_carpet', views.add_carpet, name="dashboard_add_carpet"), path('add_images/<str:model_type>/<uuid:id>', views.add_images, name="dashboard_add_images"),] An example redirect url after a form has been submitted is this: http://127.0.0.1:8000/dashboard/add_images/carpet/97afd259-6ec4-48fc-869f-2a00bbe29c70 Error: Reverse for 'dashboard_add_images' with no arguments not found. 1 pattern(s) tried: ['dashboard/add_images/(?P<model_type>[^/]+)/(?P<id>[^/]+)$'] -
Go to another page without refresh [Django]
How to achieve going to another page without refreshing after for example clicking a link to another URL. More examples, I have a list of books display and when I clicked on one of the book, it will redirect me to the selected book page. This is the example of the code link. <a class="link" href="{% url 'books:view_book_detail' obj.book.name obj.pk %}">View book</a> I know about the history.pushState() but how to actually use it ? Can it be use with URL from Django. Are there any method else then stated ? -
ValueError: Field 'id' expected a number but got 'create'
When I try to request this class: class CourseCreate(CreateView): model = Courses form_class = CoursesForm template_name = 'main_app/courses/course_form.html' success_url = reverse_lazy('courses') def form_valid(self,form): messages.success(self.request, f"Course created successfully") return super().form_valid(form) I got this error: ValueError at /academiaweb/courses/create Field 'id' expected a number but got 'create'. models.py: class Courses(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.TextField() year = models.ForeignKey(SchoolYears,on_delete=models.CASCADE) class Meta(): verbose_name = 'Course' verbose_name_plural = 'Courses' def __str__(self): return self.name Urls.py: path('courses/create',views.CourseCreate.as_view(),name='course_create'), -
How do I prepopulate Foreign key fields on django admin inline?
I have Service Groups and Services. Together, they create a unique relation GroupService which includes some other foreign keys.So, in django admin, upon creation of a group, I want to prepopulate service inlines with two default services' ids. I've tried overriding the BaseInlineFormSet for my inline but no success. Here's what I've tried, now it gives me KeyError: "Key 'id' not found in 'GroupServiceForm'. Choices are: counter, deduction, numerator, service.". When I tried to implement it using self.empty_form, I actually succeeded at displaying default services' foreing keys but could not save the form even if I had all my fields filled in. class CustomInlineFormSet(BaseInlineFormSet): def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None, **kwargs): super().__init__(data=data, files=files, instance=instance, save_as_new=save_as_new, prefix=prefix, queryset=queryset, **kwargs) default_services = Service.objects.filter( is_default=True).values_list('id', flat=True) services = [form['service'].initial for form in self.forms] for default_service in default_services: if default_service not in services: empty_form = self.form(initial={'id': 12, 'group': instance.id, 'service': default_service}) # empty_form.is_valid() self.forms.append(empty_form) class GroupServiceInline(CompactInline): model = GroupService fieldsets = ( (None, {'fields': ('service',)}), ('KPI', {'fields': ('counter', 'deduction', 'numerator')}), ) formset = CustomInlineFormSet extra = 2 -
Selenium: get file URL from WebElement (django, pytest)
I'm trying to test a django web app via Selenium and pytest. My test page has the following link displayed within a table (along with other links of the same format): <a href="/download_file/?file_path=serve/myid/results_XYZ.csv"><input type="button" value="Results (.csv)" /></a> I can get that webelement by using the following code: input_fields = self.driver.find_elements(By.CSS_SELECTOR, '\\input') for elem in input_fields: value = elem.get_attribute("value") if value == "Results (.csv)": csv_link = elem # more elif clauses to get the various links calling .click() on that webelement leads to a successful download of the file, so that works. Now, I also need to extract the actual download link from that element, to get the filename. What I have tried: print(mylink.get_attribute("href")) # prints None print(mylink.get_attribute('outerHTML')) # prints <input type="button" value="Results (.csv)"> print(mylink.get_attribute('innerHTML')) # prints nothing print(mylink.get_attribute("ownerElement")) # prints None The latter is surprising to me, because the following: mydic = mylink.get_property('attributes')[0] for key in mydic: print(f"\t{key}:\t{mydic[key]}") prints, among other things, ownerElement: <selenium.webdriver.remote.webelement.WebElement (session="c470b6e33d0b2fbec3f1a0e7e26dec55", element="81bdc092-0b8b-4069-a1ec-8a685fda18a5")> So I'm confused why I can't get that ownerElement. And also, why .get_attribute('innerHTML'), which I have seen advertized everywhere, does not give me anything. But mostly, I need to know: How do I get the file-url from such a download link? -
Google OAuth2 for Android using python-social-auth
I have a Django project, that implements Google OAuth2 with python-social-auth package. It works fine for Web applications. My config in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv('GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv('GOOGLE_OAUTH2_SECRET') AUTHENTICATION_BACKENDS = ( 'entity.oauth.backends.CustomGoogleOAuth2', 'entity.oauth.backends.CustomFacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_STRATEGY = 'entity.oauth.strategies.CustomStrategy' After completing the request I generate JWT tokens for the user: def jwt_do_complete(backend, login, user=None, redirect_name='next', *args, **kwargs): ... if user: if user_is_active(user): # Get the JWT payload for the user. refresh = TokenObtainPairSerializer.get_token(user) payload = { 'refresh': str(refresh), 'access': str(refresh.access_token) } else: raise RuntimeError('Unauthorized', 'The user account is disabled.', status.HTTP_401_UNAUTHORIZED) else: raise RuntimeError('Unauthorized', 'The user account does not exist.', status.HTTP_401_UNAUTHORIZED) return user, payload So the workflow of the authorization is the following: Frontend authenticates by Google form and receives code and other information. It sends it to the complete route of the Django server. Django verify the code with help of python-social-auth. Django sends back JWT tokens. Here is the complete view: @never_cache @csrf_exempt @psa(f'{NAMESPACE}:complete') def complete_with_jwt(request, backend, *args, **kwargs): """Authentication complete view""" try: user, token_info = jwt_do_complete( request.backend, _do_login, user=request.user, redirect_name=REDIRECT_FIELD_NAME, request=request, *args, **kwargs ) except RuntimeError as e: if len(e.args) != 3: raise return HttpResponse(json.dumps({ 'status': e.args[0], 'message': e.args[1], }), status=e.args[2]) return HttpResponse(json.dumps(token_info)) It works fine as I said … -
Django is taking the templates from virtualenv not from /templates for application
I am using Django 3.2.10 and I also use a template for frontend and for admin panel. My problem is that the website is loading the templates from virtualenv and not from the template folders in the applications. My current configuration is: INSTALLED_APPS = [ 'django.contrib.admindocs', 'apps.admin_volt.apps.AdminVoltConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.app', 'apps.crypto', 'apps.taskmgr', 'django_celery_results', 'apps.home', 'apps.authentication', 'debug_toolbar',] CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(CORE_DIR, "core/templates") # ROOT dir for crypto TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { ... STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = 'static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'core/static'), os.path.join(CORE_DIR, 'apps/admin_volt/static'), os.path.join(CORE_DIR, 'apps/static'), ) How can I change my configuration to ensure that the templates are taken from app/admin_volt/templates/admin and not from venv\Lib\site-packages\admin_volt\templates\admin Thank you -
Empty fields are added to the extended Users table when registering new users in Django
Empty fields are added to the extended Users table when registering new users. How to fix it? Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main models.py: from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractBaseUser): name = models.CharField(null=False, max_length=60) email = models.CharField(null=False, max_length=60) password = models.CharField(null=False, max_length=40) level = models.IntegerField(null=True) USERNAME_FIELD = 'name' def __str__(self): return self.name views.py: from django.contrib.auth import logout from django.contrib.auth.views import LoginView from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import RegisterUserForm, LoginUserForm class RegisterUser(CreateView): form_class = RegisterUserForm success_url = reverse_lazy('login') template_name = … -
Getting com_error when I interact with Django app
I'm getting an error when I try to use a Django app. com_error at /polls/ (-2147024891, 'Access is denied.', None, None) Request Method: GET Request URL: http://192.1.1.100:4455/polls/ Django Version: 2.2.6 Exception Type: com_error Exception Value: (-2147024891, 'Access is denied.', None, None) Exception Location: C:\Python64\Python37\lib\site-packages\appdirs.py in _get_win_folder_with_pywin32, line 481 Python Executable: C:\Python64\Python37\python.exe Python Version: 3.7.4 Python Path: ['.', 'C:\\inetpub\\wwwroot\\Pounce', 'C:\\Python37\\python37.zip', 'C:\\Python37\\DLLs', 'C:\\Python37\\lib', 'C:\\Python37', 'C:\\Python37\\lib\\site-packages', 'C:\\Python37\\lib\\site-packages\\win32', 'C:\\Python37\\lib\\site-packages\\win32\\lib', 'C:\\Python37\\lib\\site-packages\\Pythonwin'] The app had been working fine over the past year. This is the first time I'm getting this error. I recently installed pypiwin32. Otherwise everything is the same. -
Django Login in context processor doesn't work properly
I tried to display login and registration form on all my Django app. For that I use context_processor that ad login form in context this is my context_processors.py in app def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect("visuapp:user_page") else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return {"login_form": form} I then call processors in settings.py TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'myapp.context_processors.login_request', ], }, }, ] And finally I ue declared form in a modal in my base.html template <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#loginModal"> SignIn </button> <!-- Modal --> <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h1>Login</h1> <form method="POST"> {% csrf_token %} {{ login_form }} <button class="btn btn-primary" type="submit">Login</button> </form> <p class="text-center">Forget Password? <a href="{% url 'password_reset' %}">Change password</a>. </p> <p class="text-center">Don't have an account? <a href="#registerModal">Create an account</a>.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close </button> <button type="button" class="btn … -
NoReverseMatch for Django and DjangoCMS App
I am trying to set up some URLs for tags and categories on a forum. The links look like this <a href="{% url 'article-list-by-tag' %}{{ tag }}" class="badge badge-info" >{{ tag }}</a> The URL pattern article-list-by-tag comes from a DjangoCMS app called AldrynNewsblog. It can be found HERE and looks like this url(r'^tag/(?P<tag>\w[-\w]*)/', TagArticleList.as_view(), name='article-list-by-tag'), Note that the NewsBlog does not have app_name declared in its urls.py. The app itself is part of a larger Django app called DjangoCMS. The url entry-point for the latter is declared in project's main urls.py as follows: path('', include('cms.urls')), The error that I am getting is Reverse for 'article-list-by-tag' not found. 'article-list-by-tag' is not a valid view function or pattern name. What should I do to resolve this? I have tried adding namespace to various URL entries as well as app_name to NewsBlog to no avail. The Django version being used is 2.1 -
ochange event only works after the second selection
I have to show some data base on selection drop down list, the form is dynamic, here is my teplates function imeiInfo () { $('select').change(function(e) { e.stopImmediatePropagation(); let elm = $(this); data = {}; data[elm.attr("name")] = elm.val(); $.ajax({ url:'/ajax/return_back_imei_plusinfo/', data:data, success:function(data){ console.log(data.price) if (data.price){ elm.closest("div.child_imeiforms_row").find("input.nrx").val(data.price); } if (data.mobile){ elm.closest("div.child_imeiforms_row").find("input.mobile-type").val(data.mobile); } } }) }) } imeiInfo(); <form action="" method="POST" id="create-permcustomer-invoice">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <i class="fas fa-file-signature"></i> <label>customer</label> {{ main_form.customer | add_class:'form-control' }} </div> <p class="text-danger text-center" hidden id="collection_date_error"></p> </div> <div class="col-md-2"> <div class="form-group"> <i class="fas fa-box-usd"></i> <label>balance</label> <input type="number" disabled class="form-control" id="balance_cus"> </div> <!-- /.form-group --> </div> <!-- /.col --> <div class="col-md-4 pull-right"> <div class="form-group"> <i class="far fa-clock"></i> <label>date</label> {{main_form.created | add_class:'form-control text-center'}} </div> <p class="text-danger text-center" hidden id="company_error"></p> <!-- /.form-group --> </div> </div> <div class="row no-gutters title_info text-center table-bordered text-white"> </div> {{imei_forms.management_form}} <div id="form-imeilists"> {% for imei in imei_forms %} {{imei.id}} <div class="child_imeiforms_row"> <div class="row no-gutters table-bordered"> <div class="col-md-3"> <div class="form-group"> {{imei.item | add_class:'form-control choose'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-3"> <div class="form-group"> <input type="text" disabled class="form-control mobile-type" placeholder='mobile type '> </div> </div> <div class="col-md-2"> <div class="form-group"> {{imei.price | add_class:'nrx'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-1"> <div class="form-group"> {{imei.discount | add_class:'dis'}} … -
Run Django in docker container with GDAL
I am currently trying to run a Django project inside a docker container, to provide the project with a local DB. The Project is depending on GDAL, but when trying to install the requirements it always runs into the same problem. The following is my dockerfile: FROM python:3.9-slim-buster WORKDIR /app RUN apt-get update \ && apt-get -y install netcat gcc postgresql \ && apt-get clean RUN apt-get update \ && apt-get install -y binutils libproj-dev gdal-bin python-gdal python3-gdal RUN pip install --upgrade pip COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . The Error message I get is always: Could not find a version that satisfies the requirement pygdal==3.2.0 (from versions: 1.8.1.0, ..., 3.3.2.10) ERROR: No matching distribution found for pygdal==3.2.0 I am running out of solutions. Thx in advance. -
Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state
I am trying to stream video. The script work fine locally but gives following error when i moved to server Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at sendMessage (https://website.com/video:67:24) at drawCanvas (https://website.com/video:59:17) at HTMLButtonElement.<anonymous> (https://website.com/video:63:17) Here is script i am using <script type="text/javascript"> var socket = new WebSocket('ws://localhost:8888/websocket'); $(document).ready(function () { let video = document.getElementById('video'); let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); let draw_canvas = document.getElementById('detect-data'); let draw_context = draw_canvas.getContext('2d'); let image = new Image(); if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({video: true}).then(function (stream) { video.srcObject = stream; video.play(); }); } function drawCanvas() { context.drawImage(video, 0, 0, 600, 450); sendMessage(canvas.toDataURL('image/png')); } document.getElementById("start-stream").addEventListener("click", function () { drawCanvas(); }); function sendMessage(message) { socket.send(message); } socket.onmessage = function (e) { image.onload = function () { console.log(e)}; }; }) </script> In server I changed to var socket = new WebSocket('wss://10.0.1.232:8888/websocket'); Here is code for websocket class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print ('new connection') def on_message(self, message): from sub_app.py_files.detect import get_face_detect_data image_data = get_face_detect_data(message) if not image_data: image_data = message self.write_message(image_data) def on_close(self): print ('connection closed') def check_origin(self, origin): return True application = tornado.web.Application([ (r'/websocket', WSHandler), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) myIP = socket.gethostbyname(socket.gethostname()) print ('*** …