Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker: a web service built but failed to execute
I`m trying to build a Django web service with docker. The docker file is ENV DockerHOME=/home/xs1_glaith/cafegard RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 the docker-compose file is like this version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgress - POSTGRES_USER=postgress - POSTGRES_PASSWORD=postgress web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/home/xs1_glaith/cafegard ports: - "8000:8000" depends_on: - db COPY . $DockerHOME RUN pip install --upgrade pip RUN pip install -r $DockerHOME/requirements.txt EXPOSE 8000 CMD python manage.py runserver finally, the result is Starting cafegard_db_1 ... done Creating cafegard_web_run ... done Error response from daemon: OCI runtime create failed: container_linux.go:367: starting container process caused: exec: ".": executable file not found in $PATH: unknown ERROR: 1 I dont really understand whats the problem or what`s make the problem!!! -
Django multi tenany one domain for one or more users
I'm working on a small project using Django/Rest with multi tenancy package : https://django-tenants.readthedocs.io/en/latest/install.html and i would like to know if there is any way to have one domain for multiple users -
how to use SearchVector SearchRank with icontain in Django?
I'm trying to use SearchVector in Django. I read from here that how to use SearchVector with icontains. but I can't seem to find any information on how to use SearchVector and SearchRank and check if string contains the desired string. here is my models.py class Tag(models.Model): Name=models.CharField(max_length=20) def __str__(self): return self.Name class data(models.Model): FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) tag = models.ManyToManyField(to=Tag,blank=True,null=True) def __str__(self): return self.FirstName+" "+self.LastName here is my views.py def searchView(request): if request.method == "POST": form=NameForm(request.POST) if form.is_valid(): vector = SearchVector("FirstName",weight="A")+SearchVector("tag__Name",weight="C")+SearchVector("LastName",weight="B") query = SearchQuery(form.cleaned_data["name"],search_type="phrase") rank = SearchRank(vector, query, weights=[0.8, 0.6, 0.4, 0.2]) data=data.objects.annotate(rank=rank).filter(rank__gte=0.1).order_by('rank') else: data= [] form = NameForm() return render(request, "pdf.html", context={"data": data,"form":form}) else: data=[] form=NameForm() return render(request, "pdf.html", context={"data": data,"form":form}) -
Django 3 - How to create many pages and then show them on menu?
I am new in python Django and practicing it. I have a Wordpress site and I want to migrate it to Django. I can create blogs, pages etc on Django but the problem is I have to make 20+ pages of that site if I move it to Django. And to show them like parent and children of pages. I can create single pages in Django and show them in template. But I want to make it from admin panel. So me and in future, my client can create new pages easily and I want them to automatically view on navigation. I want it just like wordpress, create a page, save it and boom, it will be live on frontpage(if configured in settings). I searched for the help or right direction but cant find anywhere. Please someone point me which is the best way to achieve this ? -
Cannot access "instance" or detail view of an object from react frontend with Django rest framework backend
So, I have this view for my models, on a django-rest-framework project class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer permission_classes = [permissions.AllowAny] This is my serializer: class GenreSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Genre fields = ('name', 'artist', 'albums') depth = 2 On urls: router = routers.DefaultRouter() router.register(r'genre', views.GenreViewSet) urlpatterns = [ path('rest-framework/', include(router.urls)), ] Now, I have a react based frontend app, to access this object, if I access the recordset, meaning, the list of all the objects, then I'm perfectly able to do it, but, if for example, I want to access, just one of the objects in database, something like: path/to/url:8000/object/id Then I got this error, but only from the frontend, the react app: Access to fetch at 'http://127.0.0.1:8000/rest-framework/genre/2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Actually, I do have django-cors-headers installed, and also configured on my settings.py file. As I said, I can access the object list, listing all the objects into db, just not the detail. On my settings.py I have: CORS_ORIGIN_ALLOW_ALL = True … -
I am very confused on what to do
I am currently deploying an app on the heroku website on django. I had been combatting multiple errors, and I managed to pass through the static files and I got stuck on the preparing wheel metadata. I would like to ask what I should do to bypass this error. Here is the error: Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python /app/.heroku/python/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmpa6ent96x cwd: /tmp/pip-install-v0czirbb/pywinpty Complete output (6 lines): Checking for Rust toolchain... Cargo, the Rust package manager, is not installed or is not on PATH. This package requires Rust and Cargo to compile extensions. Install it through the system's package manager or via https://rustup.rs/ ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python /app/.heroku/python/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmpa6ent96x Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed -
ElasticBeanstalk Deployment Failed: WSGI cannot be loaded as Python module
I am facing Django deployment issues related wsgi configuration and wanted to see if everything is fine from project setup and EBS side i.e. correct WSGI, python version. I am following standard project structure: [dhango_project]/ ├── [dhango_project]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py | |── [blog] |── [static]/ | ├── [css] | ├── [Javascript] | └── [Images] | |── [templates] |── manage.py └── requirements.txt dhango_project/.ebextensions/django.config option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: "dhango_project/wsgi.py" "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" I am seeing error : apps.populate(settings.INSTALLED_APPS) [Fri Apr 30 13:26:27.696673 2021] [:error] [pid 28548] [remote xxxxx] File “/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py”, line 83, in populate [Fri Apr 30 13:26:27.696676 2021] [:error] [pid 28548] [remote xxxxx] raise RuntimeError(“populate() isn’t reentrant”) [Fri Apr 30 13:26:27.696688 2021] [:error] [pid 28548] [remote xxxxx] RuntimeError: populate() isn’t reentrant [Fri Apr 30 13:26:38.189812 2021] [:error] [pid 28548] [remote xxxxx] mod_wsgi (pid=28548): Target WSGI script ‘/opt/python/current/app/dhango_project/wsgi.py’ cannot be loaded as Python module. [Fri Apr 30 13:26:38.189855 2021] [:error] [pid 28548] [remote xxxxxx] mod_wsgi (pid=28548): Exception occurred processing WSGI script ‘/opt/python/current/app/dhango_project/wsgi.py’. [Fri Apr 30 13:26:38.189952 2021] [:error] [pid 28548] [remote xxxxxx] Traceback (most recent call last): [Fri Apr 30 13:26:38.189977 2021] [:error] [pid 28548] [remote xxxxxx] File “/opt/python/current/app/dhango_project/wsgi.py”, line 16, in [Fri Apr … -
how to connect oracle database in python django instead of sqlite
I want to make a DBMS projects on Topic Railway Management System for that I choose django framework , but as a database for me it is requires to use oracle 19c as database. So please if someone can help mw how I can remove sqlite from django and install oracle database in it. -
Django - content_type_id not recognised when running test on models using postgresdb
I have a two models Actor and User in my project. Actor is a superset of User with the usage of ContentType. The issue is that, I have two projects same. One using sqlite and other built in docker running postrgres db. The sqlite3 with the same code pass all the tests but the one with postgresql is stuck with a test error ContentType when I try to test the creation of an Actor object. models.py from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models # for testing Actor and ContentType: class Actor(models.Model): """ Actor: the superset for User and Applicant """ choices = models.Q(app_label='core', model='user') content_type = models.ForeignKey(ContentType, limit_choices_to=choices, related_name='entity_types', on_delete=models.CASCADE, null=True) entity_id = models.PositiveIntegerField( null=True) content_object = GenericForeignKey('content_type', 'entity_id') company_id = models.IntegerField() created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.content_type) class User(models.Model): actor_id = models.ForeignKey(Actor, on_delete=models.CASCADE) # having issues to relate two models created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.actor_id) tes_models.py from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission from django.test import TestCase from core.models import Actor, User """ get content_type to get its id in test_actor_relationship() """ CONTENT_TYPE_HELPER = ContentType.objects.get_for_model(User) class TestModels(TestCase): def test_actor_get_entity(self): #<=== PASS """ test if … -
Can I add a form in django in HTML
I want to add comments form a specific html which has it's separate views and models and I don't want to create a new form.html just to display the form and its views. But I'm stuck. I can add comments manually from the admin page and it's working fine, but it seems that I have to create another url and html file to display the comment form and for users to be able to add comments(btw I'm trying to build a sports related website). Thanks in advance! My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py : class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) My views.py : def addcomment(request): model = Comment form_class = CommentForm template_name = 'transfernews.html' My urls.py: path('comment/', views.addcomment, name='comment'), My transfernews.html: <h2>Comments...</h2> {% if not transfernew.comments.all %} No comments Yet... {% else %} {% for comment in transfernew.comments.all %} <strong> {{ comment.user.username }} - {{ comment.date_added }} </strong> <br/> {{ comment.body }} <br/><br/> {% endfor %} {% endif … -
ModelSerializer write with a field and read with other fields
I POST to an API and relate the created Bar object to an existing Foo object. I use the name of Foo, for example: self.client.post('/app/bar/', data={ 'username': 'nikko123', 'foo': 'Nikko' }, In my Bar Serializer, the Foo field has a ModelSerializer to relate it with, class FooSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() link = serializers.SerializerMethodField() class Meta: model = Foo fields = ('name', 'link') def to_internal_value(self, data): # Get name of Foo foo = Foo.objects.get(name=data) return {'foo': foo} def get_link(self, object): print('req', object.id) if object.id and request: return request.build_absolute_uri( '/app/foo/{}'.format(object.id)) return None class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(source='*') ... class Meta: model = Bar My problem is that the response from Bar, I get empty from Foo. {'id': 2, 'username': 'nikko123', 'foo': {'link': None}, # name is also missing } I have tested the Bar object and it saved the Foo, however it is not serializing. What could be the problem here? -
I want to represent a django table header as a checkbox
I'm making a django table using django-tables2. What I want is to create a header cell as a checkbox but the problem is django-tables2 doesn't seem to render html when passed as verbose. Here is my table code : class AllTable(tables.Table): CHECKBOX_TEMPLATE = ' <input id="forms_check" type="checkbox" name="forms_check" pk="{{record.pk}}" /> ' _ = tables.TemplateColumn(CHECKBOX_TEMPLATE) _.verbose_name = "<input type='checkbox'>" class Meta: model = models.All template_name = "django_tables2/bootstrap.html" fields = ("_","id","name") The result i'm getting is as follow : What I want is a checkbox instead. Please if anyone knows the way can you guide me through this. Thanks. -
Limiting the amount of decimals displayed, django
So i have an issue, which is basically i am displaying a model with decimal fields and i cant limit how many zeros are displayed, basically it looks like there is too many of then, and i was wondering how to limit it? Here is the template code, <table class="table table-striped table-dark" width="100%"> <thead> <th>Posicao</th> <th>Marca</th> <th>Modelo</th> <th>Ano</th> <th>Média de lucro</th> </thead> {%for q in query4 %} <tr> <td>{{forloop.counter}}</td> <td>{{q.marca}}</td> <td>{{q.modelo}}</td> <td>{{q.ano}}</td> <td>{{q.medias}} %</td> </tr> {% endfor%} </table> The query backend, query4=DataDB.objects.values('marca','modelo','ano').annotate(medias=Avg('margem_de_lucro')).order_by('-medias') The modals being called marca=models.CharField(max_length = 30,error_messages={'required':'Favor inserir uma marca'}) modelo=models.CharField(max_length = 60,error_messages={'required':'Favor inserir um modelo'}) ano=models.IntegerField( validators=[MinValueValidator(1960,'Favor inserir acima 1960.'), MaxValueValidator(2023,'Favor inserir abaixo 2023.')], error_messages={'required':'Favor inserir uma ano'}) margem_de_lucro=models.DecimalField(max_digits= 12,decimal_places=3,max_length= 12) -
django databaseerror on apache2 with uwsgi
It is a project that deloyed two years ago(no changes for about two years). But today it was reported crash. got the log as below(I replaced real project path with 'PATH/TO/PROJECT'). django.request - INFO - OK: / Traceback (most recent call last): File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/contrib/sessions/backends/base.py", line 189, in _get_session return self._session_cache AttributeError: 'SessionStore' object has no attribute '_session_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/PATH/TO/PROJECT/apps/home/views.py", line 6, in index return render(request, 'index.html') File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/defaulttags.py", line 302, in render match = condition.eval(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/defaulttags.py", line 876, in eval return self.value.resolve(context, ignore_failures=True) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 671, in resolve obj = self.var.resolve(context) File … -
Django internal server error - No module decouple
I am trying to deploy some basic django app on linode but I get error 500 whenever I try to access my website. Here are the files and logs tail -200 mysite-error.log [Mon May 03 17:00:53.788104 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] mod_wsgi (pid=10477): Failed to exec Python script file '/var/www/GreatKart/greatkart/wsgi.py'. [Mon May 03 17:00:53.788180 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] mod_wsgi (pid=10477): Exception occurred processing WSGI script '/var/www/GreatKart/greatkart/wsgi.py'. [Mon May 03 17:00:53.789344 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] Traceback (most recent call last): [Mon May 03 17:00:53.789422 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] File "/var/www/GreatKart/greatkart/wsgi.py", line 16, in <module> [Mon May 03 17:00:53.789429 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] application = get_wsgi_application() [Mon May 03 17:00:53.789439 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] File "/usr/local/lib/python3.9/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon May 03 17:00:53.789443 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] django.setup(set_prefix=False) [Mon May 03 17:00:53.789452 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] File "/usr/local/lib/python3.9/dist-packages/django/__init__.py", line 19, in setup [Mon May 03 17:00:53.789456 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Mon May 03 17:00:53.789464 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] File "/usr/local/lib/python3.9/dist-packages/django/conf/__init__.py", line 82, in __getattr__ [Mon May 03 17:00:53.789468 2021] [wsgi:error] … -
Pycharm - is there a key shortcut to stop automatic closure of brackets?
I'm currently playing around with Django using Pycharm and have never used this IDE for Django development before as I usually just used Visual Studio Code or Atom etc. Pycharm has a useful feature for auto closing brackets and expressions, for example, if I type '{%', it will produce '{% %}' with my cursor in the middle. The problem is sometimes I might not want this to happen say, if I'm editing code rather than writing it. What I'm wondering is, is there a way to temporarily over-ride this feature by pressing a key? I don't want to disable the feature entirely as it is otherwise useful. Any help would be much appreciated. Thanks again everyone. -
AttributeError at /dashboard/2650/files/ 'DashModelDetailFilesView' object has no attribute 'object'
I want to create a page with the class based view that inherit views DetailView and FormView but get the error. Here's the code of the view: views.py class DashModelDetailFilesView(DetailView,FormView): template_name = 'dashboard/dashboard-files.html' queryset = DashModel.objects.all() form_class = AddFile success_url = '/dashboard/search-models/' context_object_name = 'dashmodelFile' def form_valid(self,form): form.save() return super().form_valid(form)``` forms.py class AddFile(forms.ModelForm): class Meta: model = DashModelFile fields = '__all__' widgets = { 'file': forms.FileInput, } I created dashmodelfile model to upload multiple filed for the main model. models.py class DashModelFile(models.Model): file = models.FileField(null=True, blank = True) dashmodel = models.ForeignKey(DashModel, on_delete=models.CASCADE, related_name='files') -
Upload image from swagger_auto_schema
How to upload image from swagger UI? I am using DRF and drf-yasg Swagger. I want to upload image from request body. my current view.py: @api_view(['POST']) def image(request): profile_img = request.FILES.get('profile_img', '') cover_img = request.FILES.get('cover_img', '') ... pass Is it possible to upload image by: @swagger_auto_schema(method='post', request_body=openapi.Schema(type=openapi.TYPE_OBJECT, parameters={ 'profile_img': openapi.Schema(type=openapi.TYPE_FILE, description='Profile picture.'), 'cover_img': openapi.Schema(type=openapi.TYPE_FILE, description='Cover Photo.') }) ) @api_view(['POST']) def image(request): profile_img = request.FILES.get('profile_img', '') cover_img = request.FILES.get('cover_img', '') ... pass -
Django filter out on related field
I have three models, two of them linked to the third by a foreign key, as follows: class A(models.Model): sku = models.ForeignKey("SKU", on_delete=models.PROTECT) production_start = models.DateField(blank=True, null=True) production_end = models.DateField(blank=True, null=True) class B(models.Model): date = models.DateField() sku = models.ForeignKey("SKU", on_delete=models.PROTECT) quantity = models.PositiveIntegerField() last_modified = models.DateTimeField(auto_now=True) class SKU(models.Model): product = models.CharField(max_length=64) design = models.CharField(max_length=64) I would like to filter the foreign keys that can be returned in the A response in an efficient way, such that by defining a date range filter on the endpoint parameters (e.g., /A/?from_date=2021-01-01&to_date=2021-01-02), for all elements of A whose production dates fall within the range, I want it to return the object A containing the elements of B for the same SKU whose date matches the specific dates. Example: "data"=[ { "sku": 7, "production_start": "2021-01-01", "production_end": "2021-01-07", "b": [ { "date": "2021-01-01", "quantity": 100 }, { "date": "2021-01-02", "quantity": 200 } ] }, ... ] So far I've tried adding a filter from django-filters to my views.py. class AViewSet(viewsets.ReadOnlyModelViewSet): class AFilterSet(filters.FilterSet): from_date = filters.DateFilter(field_name="sku__b__date", lookup_expr="gte") to_date = filters.DateFilter(field_name="sku__b__date", lookup_expr="lte") class Meta: model = models.A fields = [] queryset = models.A.objects.all() serializer_class = serializers.ASerializer filterset_class = AFilterSet And my serializers.py: class BSerializer(serializers.Serializer): date = serializers.DateField() quantity … -
Python Permission Denied with ffprobe on NamedTemporaryFile
I'm trying to validate certain parameters of a media file before the file gets saved in Django. So I validate the file using ffprobe (from the ffmpeg pip package). with NamedTemporaryFile(suffix=f'.{self.audio.name.split(".")[-1]}') as fp: fp.write(self.audio.read()) try: # Get duration with ffprobe info = probe(fp.name) self.duration = info['format']['duration'] fp.close() except ffmpeg.Error as e: print('stderr:', e.stderr.decode('utf8')) raise NotAudioFile except: traceback.print_exc() raise NotAudioFile This is the snippet that validates the file. self.audio is a Django FileField. It creates a named temporary file, writes the file from the django file, and then validates it using ffprobe. However, when it runs, ffprobe gives me a Permission Denied error, which is weird, since I checked the file and I have full permission to write that directory/file. stderr: ffprobe version 4.3.2-2021-02-20-essentials_build-www.gyan.dev Copyright (c) 2007-2021 the FFmpeg developers built with gcc 10.2.0 (Rev6, Built by MSYS2 project) configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-lzma --enable-zlib --enable-libsr t --enable-libssh --enable-libzmq --enable-avisynth --enable-sdl2 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libaom --enable-libopenjpeg --enable-libvpx --enable-libass --enable-libfreetype --ena ble-libfribidi --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-libgme --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libtheora --enable-libvo-amrwbenc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-librubberband libavutil 56. 51.100 / 56. 51.100 libavcodec 58. … -
Load data from models into HTML file by clicking button
I am trying to load data from my database into the same fields when a user clicks on load for a certain bla number. I am saving the data just fine and I can see it on the console but how do I get it to show up in the fields of the form? here is what I have: model: class Overview(models.Model): application_path = models.CharField(max_length=100) review_decision = models.CharField(max_length=100) bla_number = models.CharField(primary_key=True, max_length=100) applicant_name = models.CharField(max_length=200) prop_name = models.CharField(max_length=200) non_prop_name = models.CharField(max_length=500) obp_name = models.CharField(max_length=500) dosage_form = models.CharField(max_length=500) strength_potency = models.CharField(max_length=500) route_administration = models.CharField(max_length=500) primary_assessor = models.CharField(max_length=500) secondary_assessor = models.CharField(max_length=500) review_iteration = models.CharField(max_length=500) review = models.CharField(max_length=500) designation = models.CharField(max_length=500) def __str__(self): return self.applicant_name class Meta: db_table = 'kasaapp_overview' Form that is being saved is coming from this file: <form name="overviewForm" method="POST" action="overview#" id="overviewForm" onsubmit="return false"> {% csrf_token %} <!-- NDA Basic Information--> <div class="p-3"></div> <div class="container"> <div class="row"> <div class="col-lg-3"> <div> <label>Application path:</label> </div> </div> <div class="col-lg-9"> <select class="form-control form-control-sm" name="application_path" id="application_path"> <option selected disabled>Select option</option> <option>BLA under 351(a)</option> <option>BLA under 351(k)</option> <option>NDA under 505(b)(1)</option> </select> </div> </div> </div> <div class="p-3"></div> <div class="container review"> <div class="row"> <div class="col-lg-6 custom-control custom-radio"> <input type="radio" name="review" id="radio1" class="custom-control-input review" value="Priority Review"> <label class="custom-control-label" for="radio1">Priority … -
Django: Getting the currently logged-in user in Dash app
I am using Django-Dash-Plotly module and I am trying to grab the currently logged in user in the Dash app. I have a quick example below: import dash import io import spacy import base64 from dash.dependencies import Input, Output, State import dash_table import dash_core_components as dcc import dash_html_components as html import pandas as pd import time from django_plotly_dash import DjangoDash from sqlalchemy import create_engine import psycopg2 import datetime from django.contrib.auth import get_user_model User = get_user_model() users = list(User.objects.all()) print(users) Regarding the last 4 rows - users = list(User.objects.all()) gives me all available users. Is there any way to manipulate the code such that it only returns the currently logged in user and not every user that exists? Thanks -
Reference before assignment in Django
I am trying to display an error message if a request was not successful. I set a duplicate variable to False, and if an exception is thrown then the duplicate variable should be set to True. However, when the exception is triggered, duplicate will still return False. What am I missing? views.py def generate_hardware_milestone(request): get_request = request.POST.get('form') # creating a formset insert_formset = formset_factory(Forms, extra=0) formset = insert_formset(request.POST or None) duplicate = False try: if request.method == 'POST': if get_request: try: # Execute insertion except Exception as e: duplicate = True except Exception: # some code context = {'formset': formset, 'duplicate_error': duplicate} return render(request, 'example.html', context) -
Heroku - App not compatible with buildpack https://github.com/heroku/heroku-buildpack-python.git when uploading a Django-App
I'm new with Heroku and when I try to push my project to Github, I just get the error message: App not compatible with buildpack: https://github.com/heroku/heroku-buildpack-python.git Complete output: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: https://github.com/heroku/heroku-buildpack-python.git remote: -----> App not compatible with buildpack: https://github.com/heroku/heroku-buildpack-python.git remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected remote: To https://git.heroku.com/appname.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/appname.git' I have a Procfile in my root: web:gunicorn Food_Blog.wsgi --log-file - Also I have a requirements.txt and runtime.txt file runtime.txt: python-3.8.1 Anyone an idea how to fix this issue? -
Export in csv a custom admin function
Here is my admin class : from django.contrib import admin from Engine.actions import export_as_csv_action # Register your models here. from .models import Bathroom # Register your models here. class Bathroom_Admin(admin.ModelAdmin): list_display = ("uuid", "nicole_user","modified","getcountproduct") search_fields = ("uuid","nicole_user__firebase_id","modified","getcountproduct") actions = [ export_as_csv_action( "CSV Export", fields=["uuid", "mireille_user","modified","getcountproduct"] ) ] def getcountproduct(self, obj): return obj.products.all().count() admin.site.register(Bathroom, Bathroom_Admin) Here is my action : import csv from django.http import HttpResponse from django.contrib import admin def export_as_csv_action( description="Export selected objects as CSV file", fields=None, exclude=None, header=True, ): """ This function returns an export csv action 'fields' and 'exclude' work like in django ModelForm 'header' is whether or not to output the column names as the first row """ def export_as_csv(modeladmin :admin.ModelAdmin, request, queryset): """ Generic csv export admin action. based on http://djangosnippets.org/snippets/1697/ """ opts = modeladmin.model._meta field_names = set([field.name for field in opts.fields]) many_names =set([field.name for field in opts.many_to_many]) print(many_names) print("opts") print(modeladmin) if fields: fieldset = set(fields) field_names = field_names & fieldset many_names = many_names & fieldset elif exclude: excludeset = set(exclude) field_names = field_names - excludeset many_names = many_names - excludeset print(many_names) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = "attachment; filename=%s.csv" % str( opts ).replace(".", "_") writer = csv.writer(response, delimiter=";") if header: list_all = list(field_names) + list(many_names) …