Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Error while installing psycopg2 in windows
Hi I am working on a Django project and I am getting errors while installing psycopg2 on windows pip install psycopg2 I also tried pip install psycopg2-binary but still getting error ERROR: Command errored out with exit status 1: command: 'c:\users\theuser\appdata\local\programs\python\python39\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\theuser\\AppData\\Local\\Temp\\pip-install-zh83zqbg\\psycopg2\\setup.py'"'"'; __file__='"'"'C:\\Users\\theuser\\AppData\\Local\\Temp\\pip-install-zh83zqbg\\psycopg2\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j' cwd: C:\Users\theuser\AppData\Local\Temp\pip-install-zh83zqbg\psycopg2\ Complete output (23 lines): running egg_info creating C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info writing C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Remove app default when migrate in Django
I'm been confused when migrating class models in Django the class name automatically change and it add app_ in the beginning of the table name, for example I have these models class lib_year(models.Model): year = models.CharField(max_length=40) class lib_period(models.Model): period = models.CharField(max_length=40) class lib_semester(models.Model): semester = models.AutoField(primary_key=True) When migrate it the table name change to app_lib_year, app_lib_period, app_lib_semester is there anyway how to remove default app_? when migrate models -
Django model accessing relationship model
How to access Articles through Reporter model with below code? from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) for example in Sqlalchemy we would create realtionship inside Reporter model with: reporter_article = db.relationship('Article', backref='reporter_article ', lazy='dynamic') that would be inside Reporter model and then we can call directly Reporter.query.reporter_article.all() How would I call to get all articles from reporter? -
window.location.href does not redirect
my functions are as follows <a onClick="check_claims(this)" type="button" href="javascript:void(0)" redirurl="www.facebook.com" >Invite</a> function check_claims(ele){ var select_claims = document.getElementById('select_claims').value; if (select_claims == '1') { var result = confirm("do you wish to continue?"); if (!result) { check_email_address(); return; } } check_email_address(); window.location.href = ele.getAttribute('redirurl'); } function check_email_address(){ if ('{{broker.email_address}}' == 'None') { console.log('this worked till here'); window.location.href = 'www.google.com'; } } I just added the second function check_email_address. the function gets called and the log gets printed but the windows.location.href of this function does not get evaluated and the page keeps redirecting to url mentioned in the window.location.href of first function. -
Problem with calling an AJAX modal with Django
Hi am new to django concept . so the problem is I have two pages where i can perform crud operations using AJAX , Product and Server . The problem comes when i create new user for Server , the Product create modal works fine , but server create modal also gives the same modal of Product . with name , id and others and not the field of server . Can anyone help me in this . urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.IndexPage,name='IndexPage'), url(r'^products/$', views.product_list, name='product_list'), url(r'^create/$', views.product_create, name='product_create'), url(r'^products/(?P<pk>\d+)/update/$', views.product_update, name='product_update'), url(r'^products/(?P<pk>\d+)/delete/$', views.product_delete, name='product_delete'), url(r'^servers/$', views.server_list, name='server_list'), url(r'^create/$', views.server_create, name='server_create'), url(r'^servers/(?P<pk>\d+)/update/$', views.server_update, name='server_update'), url(r'^servers/(?P<pk>\d+)/delete/$', views.server_delete, name='server_delete'), ] partial_server_create.html <form method="post" action="{% url 'server_create' %}" class="js-server-create-form"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"></span> </button> <h4 class="modal-title">Create</h4> </div> <div class="modal-body"> {% include 'includes/partial_server_form.html' %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Create Customer</button> </div> </form> script.js var loadForm1 = function () { var btn1 = $(this); $.ajax({ url: btn1.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-server .modal-content").html(""); $("#modal-server").modal("show"); }, success: function (data) { $("#modal-server .modal-content").html(data.html_form); } }); }; var saveForm1 = function () { var form = $(this); … -
How to validate input from TinyMCE on server side in django?
I am trying to validate text input from tinymce rich text editor on the server side in django. I have created a custom filter to allow those tags which are allowed in tinymce. register = template.Library() _ALLOWED_ATTRIBUTES = { 'img': ['src', 'class'], 'table': ['class'] } _ALLOWED_TAGS = ['b', 'i', 'ul', 'li', 'p', 'br', 'h1', 'h2', 'h3', 'h4', 'ol', 'img', 'strong', 'code', 'em', 'blockquote', 'table', 'thead', 'tr', 'td', 'tbody', 'th'] @register.filter() def safer(text): return mark_safe(bleach.clean(text, tags=_ALLOWED_TAGS, attributes=_ALLOWED_ATTRIBUTES)) This prevents simple tags from going into the database but the problem is arises in case the attacker enters something like <img src=alert(1)></img> or any other javascript inside the src or any other attribute which accepts javascript. Furthermore, the html could be base64 encoded. For example, <script>alert('hi');</script> in base 64 is PHNjcmlwdD5hbGVydCgnaGknKTs8L3NjcmlwdD4= This poses many security issues for the application. Is there any standard library which handles are such potential threats? If not, how can I go about making it secure against such attacks ? -
djnago StreamingHttpResponse showing loading
I am writing api to convert RTSP to HTTP URL I convert it using Django StreamingHttpResponse . I will attach the code below def gen(url): """Video streaming generator function.""" cap = cv2.VideoCapture(url) while (cap.isOpened()): ret, img = cap.read() if ret == True: img = cv2.resize(img, (0, 0), fx=1.5, fy=1.5) frame = cv2.imencode('.jpg', img)[1].tobytes() yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') time.sleep(0.1) else: break @api_view(['GET']) @permission_classes([]) def video_feed(request,cam_id): """ Converting RTSP stream to HTTP stream https://publicurl/api/video_feed/camera_id """ try: camera = Camera.objects.get(pk=cam_id) response = StreamingHttpResponse(gen(camera.CameraUrl), content_type='multipart/x-mixed-replace; boundary=frame') response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Headers"] = "*" return response except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) also installed Django core headers while calling the api http://127.0.0.1:8000/api/video_feed/1 (my pubic URL is https) in browser I am getting the video but while trying to use in urlstreaming link no video is showing . only showing loading how can I solve this -
Django LDAP auth: simple_bind_s works but authentication fails: Authentication failed for user: user DN/password rejected by LDAP server
I am having a very difficult time implementing authentication in Django using ldap. My Configuration is as follows in the settings.py: AUTH_LDAP_SERVER_URI = "ldap://192.168.10.5" # AUTH_LDAP_BIND_DN = "cn=admin,dc=my,dc=domain,dc=com" # AUTH_LDAP_BIND_PASSWORD = "adminPass" # AUTH_LDAP_USER_SEARCH = LDAPSearch( # "dc=dc=my,dc=domain,dc=com", ldap.SCOPE_SUBTREE, "(cn=%(user)s)" # ) AUTH_LDAP_USER_DN_TEMPLATE = 'sAMAccountName=%(user)s,dc=my,dc=domain,dc=com' AUTH_LDAP_USER_QUERY_FIELD = 'username' AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "dc=dc=my,dc=domain,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=group)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_REQUIRE_GROUP = "dc=my,dc=domain,dc=com" AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "dc=my,dc=domain,dc=com", "is_staff": "dc=my,dc=domain,dc=com", "is_superuser": "dc=my,dc=domain,dc=com", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( "django_auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", ) Then a simple test here: def test(request): #1 test authentication obj = LDAPBackend() me = obj.authenticate(request, 'admin', 'adminPass') #2 Test Connection and auth con = obj.ldap.initialize(uri='ldap://192.168.10.5') t = con.simple_bind_s('admin', 'adminPass') # return HttpResponse('Empty') I have noted the following from the above test Test 1 never successds no matter what. I tried changing from sAMAccountName, to cn to principalName whatever seemed unique from AD explorer. The result is consistently the same: Authentication failed for admin: admin DN/password rejected by LDAP server. Test 2 seems to succeed if and only if I suffix the username with "@my.domain.com". Without this suffix it fails dismally with error: {'msgtype': 97, … -
How to get total number of votes for each choice in django Detail view?
I'm working on a django based restaurant review site. When user sends reviews they fill in a form which consists of two choice fields. Currently I can display all reviews for a specific restaurant in a Detailview page. I would like to take the information from the choice fields from the comment form to display this data for the user in both the detail view (1 specific restaurant) as well as the list view (all restaurant listed): Question: I would like to get the total number of "votes" for each choice and display it with for example Chart Js in the detail view. What is the prefered way or doing so in django? I have tried to do this filtering in javascript, however I know that this could be done more efficiently directly in the model or in the view. Code Models.py class Restaurant(models.Model): name = models.CharField(max_length = 100) class Comment(models.Model): STATUS_1 = ( ('one', 'one'), ('two', 'two'), ('three', 'three'), ) STATUS_2 = ( ('cheap', 'cheap'), ('normal', 'normal'), ('expensive', 'expensive'), ) restaurant = models.ForeignKey(Restaurant, on_delete = models.CASCADE, related_name='comments') comment = models.TextField(max_length = 500) status_1 = models.CharField(max_length = 100, choices=STATUS_1) status_2 = models.CharField(max_length = 100, choices=STATUS_2) views.py class RestaurantDetailView(DetailView): model = … -
Django filter products using mulitple stock prices
I have 2 models first store product (Product) and second store product related stock record (Stockrecord). My model class Product(models.Model): """Model to store product""" product_name = models.CharField(...) product_upc = models.CharField(..., unique=True) class Stockrecord(models.Model): """Model to store product""" product = models.ForeignKey(Product, related_name="stockrecords", on_delete=models.CASCADE) price1 = models.DecimalField(...) # required price2 = models.DecimalField(...) # optional price3 = models.DecimalField(...) # optional price4 = models.DecimalField(...) # optional I want to sort the product base on the price (low - high), based on all prices (price1 --- price4) qs = Product.objects.all() qs = qs.order_by('stockrecords__price1', 'stockrecords__price2', ....) the above query is working as expected. I give below o/p 1000, 2000, 300, 4000, 1300, 5000 -
Adding filter in django OrderingFilter
Is there any way to add a filter in OrderingFilter? I want to have this filter for ordering: F('created').desc(nulls_last=True) here is my code: class ProductFilter(filters.FilterSet): ordering = filters.OrderingFilter(fields=['price', 'created']) class Meta: model = Product -
Using other models's attribute as default
Below are some parts of my code from django.db import models from django.contrib.auth.models import User from places.fields import PlacesField class DonorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dropoff_location = PlacesField(blank=True, null=True) ... from django.db import models from register.models import DonorProfile from django.contrib.auth.models import User class ResourcePost(models.Model): donor = models.ForeignKey(User, on_delete=models.CASCADE, default=None) dropoff_location = PlacesField(blank=True, null=True, default=###) ... My question is on the ### part. I want to have the value of DonorProfile's dropoff_location be the default value of ResourcePost's dropoff_location. So basically put something like default=DonorProfile.objects.get(donorprofile_id).dropoff_location) as the default value. How can I do this? -
could not find js files in Django project
I used python 3.7 in widows 10 to create a Django project. I used superuser to create some normal user. But the normal user account could not login the website, and in the power shell, the below error occurs: [02/Nov/2020 13:33:03] "POST /login/?next=/ HTTP/1.1" 200 14278 Not Found: /login/vendor/fontawesome-free/css/all.min.css [02/Nov/2020 13:33:04] "GET /login/vendor/fontawesome-free/css/all.min.css HTTP/1.1" 404 19761 Not Found: /login/vendor/jquery/jquery.min.js [02/Nov/2020 13:33:04] "GET /login/vendor/jquery/jquery.min.js HTTP/1.1" 404 19713 Not Found: /login/vendor/bootstrap/js/bootstrap.bundle.min.js [02/Nov/2020 13:33:04] "GET /login/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 19777 [02/Nov/2020 13:33:19] "POST /login/?next=/ HTTP/1.1" 200 14278 Not Found: /login/vendor/bootstrap/js/bootstrap.bundle.min.js [02/Nov/2020 13:33:19] "GET /login/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 19777 Not Found: /login/vendor/jquery/jquery.min.js Not Found: /login/vendor/fontawesome-free/css/all.min.css [02/Nov/2020 13:33:19] "GET /login/vendor/fontawesome-free/css/all.min.css HTTP/1.1" 404 19761 [02/Nov/2020 13:33:19] "GET /login/vendor/jquery/jquery.min.js HTTP/1.1" 404 19713 Not Found: /login/vendor/jquery/jquery.min.js [02/Nov/2020 13:33:19] "GET /login/vendor/jquery/jquery.min.js HTTP/1.1" 404 19712 Not Found: /login/vendor/bootstrap/js/bootstrap.bundle.min.js [02/Nov/2020 13:33:19] "GET /login/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 19776 But I have checked that I do have there files in that folder: enter image description here enter image description here I have tried to run python manage.py collectstatic but error occurs: raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. -
Cannot access django behind traefik v2 in docker swarm
I am trying to deploy my django application on a remote ubuntu server, using docker swarm, but I am unable to view the website. If I type just the servers ip address I get "404 page not found" however if I search the domain name, it just perpetually loads. I am however, able to access the traefik dashboard but this is using the servers ip address. I've checked that all the services are running with "docker service ls" and there are no issues. The traefik dashboard My production docker stack version: "3.7" services: traefik: image: traefik:v2.1 deploy: restart_policy: condition: on-failure placement: constraints: - node.role == manager labels: # enable traefik - "traefik.enable=true" # Swarm Mode - "traefik.http.services.traefik.loadbalancer.server.port=80" # Global redirection - http to https - "traefik.http.routers.http-catchall.rul=hostregexp(`{host:(www\\.)?.+}`)" - "traefik.http.routers.http-catchall.entrypoints=websecure" - "traefik.http.routers.http-catchall.middlewares=redirect-to-https" # Global redirection - https://www to https - "traefik.http.routers.https-catchall.rule=hostregexp(`{host:(www\\.).+}`)" - "traefik.http.routers.https-catchall.entrypoints=websecure" # traefik.http.routers.https-catchall.tls: "true"" - "traefik.http.routers.https-catchall.middlewares=redirect-to-https" # Middleware redirection - "traefik.http.middlewares.redirect-to-https.redirectregex.regex=^https?://(?:www\\.)?(.+)" - "traefik.http.middlewares.redirect-to-https.redirectregex.replacement=https://$${1}" - "traefik.http.middlewares.redirect-to-https.redirectregex.permanent=true" # traefik.http.middlewares.redirect-to-https.redirectscheme.scheme: https command: # Traefik dashboard - "--api=true" - "--api.insecure=true" - "--api.dashboard=true" # Traefik logs - "--log.filePath=/etc/traefik/traefik.log" - "--log.level=DEBUG" # Access Logs - "--accesslog=true" - "--accesslog.filepath=/etc/traefik/access.log" - "--accesslog.bufferingsize=100" - "--accesslog.filters.statuscodes=200,300-302,404" - "--accesslog.filters.retryattempts" - "--accesslog.filters.minduration=10ms" # Docker - "--providers.docker" - "--providers.docker.endpoint=unix:///var/run/docker.sock" - "--providers.docker.exposedByDefault=false" # Docker … -
Run a script everyday in django-rest api on heroku
I want to run a particular script every day in the morning for my rest api deployed on heroku the script itself it's only a database filler. how can that be done? I forgot to mention that i'm using django rest_framework -
Adding manager in django form
I want to create user from extended Profile model , its done using api request , but from form it is not working . In api request body I am passing three fields only name,email,and phone_number, so that password is making through random automatically. class ProfileManager(model.Manager): def create(self, email,phone_number, **kwargs): password=str(random.random())[2:8] user = User(username=phone_number) user.set_password(password) user.save() profile = Profile( auth_user=user, email=email, **kwargs ) profile.save() if am using form like class CustomerCreateForm(forms.ModelForm): name =forms.CharField(label='Name', max_length=32) phone_number = forms.CharField(label='Name', max_length=32) class Meta: model=Profile fields=['email','name','phone_number'] this ,it making error like user (1048, "Column 'user_id' cannot be null") because my profile model look like class Profile(models.model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.CharField(max_length=50,null=True, blank=True) phone_number = models.CharField(max_length= 15, null=True, blank=True) So from here i understood that ProfileManager is not dependent with form, so i need to make def validate(self,attrs) like function and differet manger for form , but i don't know how to do this due to newbie. Any help is appreciated -
Increasing cooloff time for djano-axes AXES_COOLOFF_TIME
The django-axes docs state you can use a callable as the input for AXES_COOLOFF_TIME. I'm wondering if it's possible to have the cooloff time increase each time a user enters an incorrect password beyond value for the AXES_FAILURE_LIMIT. -
I have to pass the multiple <int:pk> in a single endpoint for django rest api?
Here in the above picture, I have all the packages shown for single destination id ie pk=1. Now, what i want to show is single package of single destination ie my endpoint should be localhost/api/destination/1/package/1 or something like this. My views and serializers are as shown below: class DestinationPackageSerializer(serializers.ModelSerializer): class Meta: model = Package # fields = ['id', 'destination'] fields = '__all__' class DestinationwithPackageSerializer(serializers.ModelSerializer): packages = DestinationPackageSerializer(many= True,read_only=True) class Meta: model = Destination fields = ['id', 'name', 'dest_image', 'packages'] # fields = '__all__' # depth = 1 class DestinationFrontSerializer(serializers.ModelSerializer): class Meta: model = Destination # fields = ['id', 'package'] fields = '__all__' # depth = 1 My views are: class DestinationFrontListAPIView(ListAPIView): queryset = Destination.objects.all().order_by('?')[:4] # queryset = Package.objects.all().order_by('-date_created')[:4] serializer_class = DestinationFrontSerializer class DestinationPackageListAPIView(RetrieveAPIView): queryset = Destination.objects.all() serializer_class = DestinationwithPackageSerializer My urls are: path('api/destinations', views.DestinationFrontListAPIView.as_view(), name='api-destinations'), path('api/destinations/<int:pk>', views.DestinationPackageListAPIView.as_view(), name='api-destinations-packages'), -
How to Make Looping through a Dataframe Faster in my Django Project
I have this code that runs through a model converted to a Dataframe having 7k entries and run some calculations on that, and then i run through another model of 2k entries and do certain calculations and also use the calculations made in the first dataframe run and then return the Output as a response [in Excel File] but that take very long to execute in my django project[4-5 minutes] which is not an acceptable time. Please suggest how do i make this Operation faster? I have tried df.iterrows() also but that doesnt bring about much difference. -
How to access ODBC Driver on Azure App service
I'm trying to run a Django (3.0) app on Azure App Service in Linux, connected to an Azure SQL Database. In my staging App Service instance, this works perfectly, however, when I set up my production instance on a different Azure account, my Django app can no longer access the database. When I hardcoded the ODBC Driver 17 into database settings, I got this error in my Oryx build logs: pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") When I switched to the non-hardcoded version suggested here, I got this error: 'driver': sorted(pyodbc.drivers()).pop(), IndexError: pop from empty list How does one go about installing an ODBC Driver on Azure App Service? -
Error installing django-heroku Error: pg_config executable not found
I tried installing django-heroku via pip so I can deploy my project on heroku but during installation of django-heroku it tried to install psycopg2 along only to produce an error: Error:pg_config executable not found. pg_config is required to build psycopg2 from source.please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext--pg-config/path/to/pg_config build... or with the pg_config option in 'setup.cfg'. And I also wish to know if I'm required to pip install it since heroku installs the libaries specified in the requirements.txt file,if not required are there changes I need to make to my project before deployment. -
Django view template can't show model data
I defined a Model called Visit. There are several models. In models.py class Visit(models.Model): case = models.ForeignKey(Case, on_delete = models.CASCADE) location = models.ForeignKey(Location, on_delete = models.CASCADE) date_from = models.DateField() date_to = models.DateField() category = models.CharField(max_length = 20) Then, I made a view template. It is to view all the visits made by a specific case. So that if the url is "sth/visit/1", it shows all the visits of case with pk1. in views.py class VisitView(TemplateView): template_name = "visit.html" def get_context_data(self, **kwargs): case_pk = self.kwargs['case'] context = super().get_context_data(**kwargs) context['visit_list'] = Visit.objects.filter(case = case_pk) print("context[visit_list]: ",context['visit_list']) I printed the context['visit_list'] in the console for url "sth/visit/1", it shows context[visit_list]: <QuerySet [<Visit: Visit object (1)>, <Visit: Visit object (2)>]> for url "sth/visit/2", it shows context[visit_list]: <QuerySet [<Visit: Visit object (3)>]> so I assume up to this moment, it works. but in the html document <ul> {% for visit in visit_list %} <li>[{{visit.date_from }}] {{ visit.date_to }} </li> {% empty %} <li>No visit yet.</li> {% endfor %} </ul> it shows no visit yet. for both 1 and 2. No error message. Just No visit. May I know what's the problem? Thank you very much please help TOT. I have been stucking here for several … -
Unable to migrate using ModelState and ProjectState using of migrations API in Django 3.0.3
I am using ProjectState to migrate to a new attributes of a table. I am trying to understand the ModelState and ProjectState using of migrations API in Django 3.0.3. I am unable to migrate to the new state which has new fields. Can someone help me with the ProjectState and ModelState usage of what to apply for new model_definition migration to work? The following code does not migrate to DB but doesnt give any error. I want to migrate from a DB table state to another state and there are some metadata _meta. The current DB state model_state.fields is: [('id', <django.db.models.fields.AutoField>)] The future DB state after migrations should be this using the above models_definition: [('id', <django.db.models.fields.AutoField>), ('name', <django.db.models.fields.CharField>)] This is the code I am using: from django.db.migrations.state import ProjectState from django.db.migrations.migration import Migration from django.db.migrations.state import ModelState from django.db.migrations import operations # model_definition is coming from a function as the following object model_definition = {'__module__': 'testmodule', 'app_label': 'testmodule', '__unicode__': <function ModelScript.model_create_config.<locals>.<lambda> at 0x000002047275FF70>, 'attrs': {'name': <django.db.models.fields.CharField>}, '__doc__': 'SampleModel(id)', '_meta': <Options for SampleModel>, 'DoesNotExist': <class 'testmodule.SampleModel.DoesNotExist'>, 'MultipleObjectsReturned': <class 'testmodule.SampleModel.MultipleObjectsReturned'>, 'id': <django.db.models.query_utils.DeferredAttribute object at 0x00000204727F9430>, 'objects': <django.db.models.manager.ManagerDescriptor object at 0x00000204727F9490>} model_state = ModelState.from_model(model_definition) fieldsets = [] for k,v in field_attrs.items(): model_state.fields.append((k, v)) … -
What are good choices for setting up asynchronous django?
I need to set up a system where actions taken by client A can trigger events for client B. Our project is written with a python server and javascript/react client. Previously, we used Flask and Socketio to get the asynchronous configuration. However, we have recently switched flask out for django. I've googled around a bit, but most of what I've found is three or more years old: asynchronous web development with django. too much technologies Can I use Socket.IO with Django? -
Git subtree fails to push to Heroku
I tried to push my Django app to Heroku git subtree push --prefix TEST heroku master It gives me something like this 'TEST' does not exist; use 'git subtree add' If I use git subtree add, it gives me Working tree has modifications. Cannot add. I am not sure what is the problem and how to fix it. Has Anyone encountered the same problem before?