Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TLS with MQTT ASGI?
I want to use the MQTT ASGI Protocol Server for Django (https://pypi.org/project/mqttasgi/) but need a TLS connection for my MQTT client (I use HiveMQ as a broker). When I use port 8883 to start the server, it 'reconnects' inifinitely. Is there some way to configure TLS? Thanks in advance -
Django if check always goes into else
I'm trying to use if inside the for loop in Django, but it keeps getting into the else part. What causes this problem? yazilar.html {% for yazi in yazilar %} {{ yazi.tur }} # output : 2 {% if yazi.tur == 1 %} standart format {% elif yazi.tur == 2 %} quote format {% elif yazi.tur == 3 %} link format {% else %} nothing {% endif %} {% endfor %} -
Ajax and Django Like button
I made a like button with Ajax and it works, but only when I click on the 1st post, the like_count counter updates the instant value. The like_count value does not change after clicking the button for the 2nd and subsequent posts. ** When I click on the like button of the second and subsequent posts, I see a change in the like_count value of the first post. When I refresh the page, I see that the value of the 2nd and subsequent posts has changed.** My problem is that I want the like count value to change instantly for the 2nd and subsequent posts. could this be the problem (id="like_count") myviews.py @login_required(login_url="login") def like(request): if request.POST.get('action') == 'post': result = '' id = request.POST.get('postid') post = get_object_or_404(Post, id=id) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 result = post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result, }) mybutton.html {% if request.user.is_authenticated %} {% if post.like_count >= 2 %} <button style="margin-top: 10px;" class="btn btn-light like_button_true like-button" value="{{ post_item.id }}"> <img style="width: 32px; height:32px;" src="{% static 'img/likeTrue.png' %}" /> <br> <span id="like_count">{{post_item.like_count}}</span> </button> {% else %} <button style="margin-top: 10px;" class="btn btn-light like_button_detail like-button" value="{{ post_item.id }}"> <img … -
Prefetch with few filters
There is a table Order, which is connected to table Signal through FK. I loop through the records from table Signal and access the child elements from table Order. As a result, I get N+1 query. Tried to do prefetch_related, Prefetch, but nothing helps. for signal in profile.signals.prefetch_related('orders').all(): filter1 = signal.orders.filter(position_direction=OrderDirectionChoice.ENTER).order_by("exchanged_at") filter2 = signal.orders.filter(position_direction=OrderDirectionChoice.ENTER) filter3 = signal.orders.filter(position_direction=OrderDirectionChoice.EXIT) filter4 = signal.orders.filter(exchanged_at__isnull=False).first() print(filter1, filter2, filter3, filter4) -
django - saving list of base64 images
i have a django and django restframework project with postgres as database. so i send a payload from frontend to this django project and this payload is json and have one field named images. images is contain list of base64 images. so i want to save them in database and i use code below for this field: images = ArrayField(base_field=models.ImageField(upload_to='hotel_images/')) but when i want to save images i get this error: images: ["The submitted data was not a file. Check the encoding type on the form."] i understand that i have to decode base64 so that i can save them in imageField but how should i do that? how can i decode base64 this images in list one by one? or do you know a better way for this? this are some of my codes: serializer.py class HotelsSerializer(serializers.ModelSerializer): class Meta: fields = ("id", "name", "stars", "address", "description", "number_of_floors", "number_of_rooms", "room_delivery_time", "room_empty_time", "images", "features") model = Hotel models.py class Hotel(models.Model): """ model for create a hotel """ name = models.CharField(max_length=60, unique=True) stars = models.IntegerField() address = models.CharField(max_length=150) description = models.TextField(default="nitro hotel") number_of_floors = models.IntegerField() number_of_rooms = models.IntegerField() room_delivery_time = models.TimeField() room_empty_time = models.TimeField() images = ArrayField(base_field=models.ImageField(upload_to='hotel_images/')) features = models.JSONField() def __str__(self) … -
send json from template to django view and then redirect to that view
I have a template cat1.html with a listing of products . When a customer selects an item, it builds an object with properties of the selected product. If the customer clicks 'add to cart' button, axios sends a request + params stringified product object to /cart ulElement.addEventListener('click', function(event) { let targetClasses = Array.from(event.target.classList); if(targetClasses.includes('dropdown-item')) { /* code to build the item */ } if(targetClasses.includes('btn-cart')) { axios.get('/cart', { params: { item: JSON.stringify(item) } } ); } }); so far this is working fine, I can print the object/json from the server so I know it makes it through. def cart(request): item_dict = json.loads(request.GET.get('item')) user_cart.append(item_dict) print(user_cart); # this seems to work fine /* return redirect('cart') this results in error TypeError(f'the JSON object must be str, bytes or bytearray, ' */ The problem happens when I try to add a redirect to the /cart view. I get the error the JSON object must be str, bytes or bytearray, not NoneType I've tried to get around this using window.location.href and also wrapping the button in an but I get the same error, so I get the sense I'm using the wrong approach. -
How to find the no of people following a hashtag - Django
I have used Django-Taggit in the posts to add tagging in my project. My post model schema is like this : class Feed(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='feedposts') publish =models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add=True) *** tags = TaggableManager() In order to make user follow the hashtags. I have added this field in the User Model Schema which looks like this. class Profile(models.Model): **** following_tags = TaggableManager() Then if the user follows the particular tag, I add that particular tag in the listed field. Now we can get the feed according to the hashtags user is following. But now I want to find out the total number of people following a particular hashtag and this is something I am not able to do. Also, Please tell me if there is any other implementation from which I can achieve this feature using django-taggit since it is easy without using it by just making a simple table of FollowedHashtags like below class FollowedHashtags(models.Model): name = models.CharField(unique = True) user = models.ManyTOManyField(User) We can get the no of people following the Hashtags: hashtag = FollowedHashtags.objects.get(id=1) nooffollowers = hashtag.user.count() I have tried some filtering queries but no success yet. So if know any other implementation … -
How to make a button show the appropriate message in Django?
I am trying to create asocial media type site that allows users to follow other users through a Django model. For some reason, the Follow Button says "Unfollow" when a user is not following the user and says "Follow" when the user is following the other user. Do you know how to display the appropriate message? (I have tried switching the True and False values but that just makes the button say "Follow" permanently.) views.py follow_or_unfollow = '' try: following = get_object_or_404(Follower, Q( user=user) & Q(followers=request.user)) print(following) except: following = False if following: follow_or_unfollow = True else: follow_or_unfollow = False if request.method == "POST": if request.POST.get('follow'): follower = Follower.objects.create(user=user) follower.followers.add(request.user) #Follower.objects.create(user=user, followers.set()=request.user) follow_or_unfollow = False elif request.POST.get('unfollow'): follower = Follower.objects.get(followers=request.user) follow_or_unfollow = True follower.remove() code in html template <form action = "{% url 'username' user %}" method = "POST"> {% csrf_token %} {% if follow_or_unfollow == True %} <input type="submit" value = "Follow" name = "follow"> {% else %} <input type="submit" value = "Unfollow" name = "unfollow"> {% endif %} </form> -
Django: Broken migration => remove old migration files
I was trying to remove on my dev machine old migration files with manage.py myapp zero But it failed at some point and I messed up. I have a project with ~1000 migration files. Unfortunately I have no backups for my dev sql database. (I have to build everything from scretch) But on my prodiction system I have also this ~1000 migration files and was wondering if it is possible to delete all migration files and just use the last state. So that each migrations folder has only one migration file left. Is this possible? This would save my life ... -
Django Foreign Key or ManyToMany is throwing an error
I am trying to connect two tables without success in Django. I have 2 models in my code: class IngredientFoodPortion(models.Model): food_code = models.ForeignKey(Ingredient, on_delete=DO_NOTHING, related_name="ingredients2") modifier = models.CharField(max_length=200, blank=True, null=True) gram_weight = models.DecimalField(decimal_places=6, max_digits=10, default=0) class MealIngredients(models.Model): meal = models.ForeignKey(Meal, on_delete=DO_NOTHING, related_name="details" , verbose_name='Meal Name', default='defaultMeal') ingredient = models.ForeignKey(Ingredient, on_delete=DO_NOTHING, related_name="ingredients" , verbose_name='Ingredients', default='defaultIngredient') serving = models.ManyToManyField(IngredientFoodPortion) amount = models.DecimalField(decimal_places=3, max_digits=10, default=0) the tables look like this: The issue is in this link: serving = models.ManyToManyField(IngredientFoodPortion) The way it should work is that if we choose the ingredient code (first column in screenshot), we should be getting back the 2nd & 3rd columns, which are usually multiple row. i tried both ForeignKey which failed because the FK is not unique, and ManyTOManyField as you can see. Any help would be appreciated. Thanks in advance, -
Update is_online field to true when user logs in
Building logic that, when a user logs in would change a boolean field in my Profile model to true and then turn that to false when the user logs out. The problem is I have an api_end point where I can see a list of all users and information related to said users. If I login as two different users (using different browsers), When I console log their information both users are shown as online: email: "user@gmail.com" ... is_online: true ... However, when I check the api_end point showing me the list of all users, only 1 user appears to be online (the last user I logged in as). This is the view related to api_end point to view all users: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = RegisterSerializer @action(detail=True, methods=['POST']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.validated_data['new_password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is my RegisterSerializer: class RegisterSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'password', 'first_name', 'last_name', 'profile'] extra_kwargs = { 'password': {'write_only': True}, } def validate_password(self, value): validate_password(value) return value def create(self,validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(**profile_data, user=user) return user … -
Get particular attribute value from django queryset (password authentication)
I am trying to implement a login system into my web page and i want to check if the password entered inside the form is equal to the users password inside the database. I can get the password from the database inside a dictionary which is inside a queryset. How can i just get the value from this dictionary? I want password_from_DB to equal to "password1234" views.py def login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get("email") password_entered = form.cleaned_data.get("password") find_person_by_email = Person.objects.filter(email=email) password_from_DB = find_person_by_email.values("password") print(password_from_DB) if password_from_DB != password_entered : print("INCORRECT") else: print("CORRECT") context = {"title": "Login"} return render(request, "myApp/login.html", context) The output from print(password_from_DB): <QuerySet [{'password': 'password1234'}]> -
Why I cannot save my template's content in my postgres database?
I have a model to rate a rented car in my Django project. However, when I submit the template's content, it seems that they are saved in the database but when I check in my data base, the table is empty. I've check all my code, I cannot find the error. Please, here are my model, views, the urls and my template respectively. Model: class tb_CARS_COMMENTS(models.Model): SCORE_CHOICES = zip(range(6), range(6) ) nom_client = models.CharField(max_length=250) vehicule = models.ForeignKey(tb_CARS, on_delete=models.CASCADE, null=True) qualite = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) prix = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) confort = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) conduite = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) email = models.EmailField(max_length=254) site_web = models.CharField(max_length=250, null=True, blank=True) Commentaires = models.TextField() def __str__(self): return 'Évaluation(Véhicule ='+ str(self.vehicule)+', Qualité ='+ str(self.qualite)\ +', Prix ='+ str(self.prix)+', Confort ='+ str(self.confort)+', Conduite ='+ str(self.conduite)+')' class Meta: verbose_name='COMMENTAIRE' verbose_name_plural='COMMENTAIRES' The views: def AddComment(request): detail=get_object_or_404(tb_CARS_CONDITIONS,id=id) form=CARS_COMMENTForm(request.POST or None) if request.method == 'POST': if form.is_valid(): print('Hello chef') obj, created = tb_CARS_COMMENTS.objects.update_or_create( vehicule=detail.vehicule_id, nom_client=request.GET.get('nom_client'), qualite=request.GET.get('qualite'), prix=request.GET.get('prix'), confort=request.GET.get('confort'), conduite=request.GET.get('conduite'), email=request.GET.get('email'), site_web=request.GET.get('site_web'), Commentaires=request.GET.get('Commentaires') ) else: print('We are not reaching here') context={ } return render(request,'Cars/comments.html', context ) The urls: app_name = 'website' urlpatterns = [ path('', views.HompePage, name='home_page'), path('about_page/', views.AboutPage, name='about_page'), path('contact_page/', views.ContactPage, name='contact_page'), path('service_page/', views.ServicePage, name='service_page'), path('liste_voiture/', views.ListeVoiture, name='liste_voirute'), path('vehicule/<int:id>/detail/', views.DetailsVoiture, name='vehicule_detail'), path('addComments/', views.AddComment, name='add_comments'), … -
Value Error in Django admin/spirits_trackers/entry
I am a noob at Django and coding in general. I am building a web app using Django to track libations and rate them as an addition to my GitHub portfolio and I am stuck. I am running into a Value Error exception when trying to add an entry or access entries to a spirit via the admin site. I've been racking my brains trying to understand why but I have no clue. I am hoping that the smarter folks on here can point me in the right direction. I am using a VENV in case that helps. Below is my models.py, views.py, spirit.html, and traceback error message. models.py from django.db import models # Create your models here. # A spirit the user is enjoying or has enjoyed. class Spirit(models.Model): text = models.CharField(max_length=50) date_added = models.DateField(auto_now_add=True) # Returns a string representation of the model. def __str__(self): return self.text # Information specific to a spirit. class Entry(models.Model): spirit = models.ForeignKey(Spirit, on_delete=models.CASCADE) type = models.CharField(max_length = 20) bottle_label = models.CharField(max_length = 150) distillery = models.CharField(max_length = 150) location = models.CharField(max_length = 50) cask_strength = models.BooleanField() proof = models.IntegerField() #abv = proof / 2 age = models.CharField(max_length = 20) barrel_select = models.BooleanField() price … -
How do I fix "ValueError: time data '\nJuly 4, 2022\n' does not match format '%B %d, %Y'"?
While scrapping a site for data i got that error. Some of the dates are in mm d, yyyy format while others are in mm dd,yyyy. I've read the documentation and tried different solutions on stackoverflow but nothing seems to work. import requests from datetime import datetime def jobScan(link): the_job = {} jobUrl = link['href'] the_job['urlLink'] = jobUrl jobs = requests.get(jobUrl, headers = headers ) jobC = jobs.content jobSoup = BeautifulSoup(jobC, "lxml") table = soup.find_all("a", attrs = {"class": "job-details-link"}) postDate = jobSoup.find_all("span", {"class": "job-date__posted"})[0] postDate = postDate.text date_posted = datetime.strptime(postDate, '%B %d, %Y') the_job['date_posted'] = date_posted closeDate = jobSoup.find_all("span", {"class": "job-date__closing"})[0] closeDate = closeDate.text closing_date = datetime.strptime(closeDate, '%B %d, %Y') the_job['closing_date'] = closing_date return the_job however i get this error ValueError: time data '\nJuly 4, 2022\n' does not match format '%B %d, %Y' and when i try the other format i get this ValueError: '-' is a bad directive in format '%B %-d, %Y' What could I probably be doing wrong? -
Is there any way to have my html page refresh/reload itself after a function in the django view.py tab completes?
I want to have my page refresh itself after a successful download of a zip file since successive attempts to click the submit button result in an error, and the only way to remedy it fairly easily is to manually refresh/reload the page. I was wondering if there is a way to set it up so that once the zip is completed the page will refresh itself without the user having to worry about it. Doing it this way also kills two birds with one stone, since I want to disable the submit button to prevent users from spamming it, but if I end up having the page refresh I could just out right remove it after it's clicked. Here is my HTML code: {% load static %} <html> <head> <link rel="stylesheet" href="{% static '/styleSheet.css' %}"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edstore"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--BOOTSTRAP ASSETS--> <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&display=swap" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <div class="main_Body"> <div class="section"> <h1>Fileconverter</h1> <br> <label for="file_field" class="custom-file-upload"> <i class="fa fa-cloud-upload"></i>Updload File(s)</label> <input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple> <label id="file_name"></label> <br> <br><br><br> <br> <button type="submit" class="file-submit__button" onclick="formDisableButton()" id="submitButton">Testing</button> <!--onclick="formDisableButton"--> </div> </form> </body> <footer> <p>Click "Choose File(s)" and select … -
For loop inside a IF condition to show right category on django template
i'm trying to show the correct articles in the category section using a if condition with a for loop inside, so far i'm displaying all the categories and not the only ones that suposed to be in the certain place. here my template: {% if articles.category == Sports %} {% for article in articles %} <div class="position-relative"> <img class="img-fluid w-100" src="{{article.cover.url}}" style="object-fit: cover;"> <div class="overlay position-relative bg-light"> <div class="mb-2" style="font-size: 13px;"> <a href="">{{article.title}}</a> <span class="px-1">/</span> <span>{{article.created_at}}</span> </div> <a class="h4 m-0" href="">{{article.description}}</a> </div> </div> {% endfor %} {% endif %} and here my views.py: def home (request): cats = Category.objects.all() articles = Article.objects.filter( is_published=True).order_by('-category') return render (request,'pages/home.html', context={ 'cats': cats, 'articles': articles }) -
jwt token expiring every 5 minunts in django SIMPLE_JWT
I have added expire functionality in SIMPLE_JWT on login but every 5 minutes token is expiring this is my code. added I want to expire token in 7 days. Can you see and tell me what is the issue in my code. Thanks PyJWT==2.4.0 class LoginAPIView(APIView): def post(self, request): email = request.data.get('username') password = request.data.get('password') user = Users.objects.filter(email=email).first() if user is None: db_logger.error('User not found!') raise AuthenticationFailed('User not found!') if not user.check_password(password): db_logger.error('Invalid password!') raise AuthenticationFailed('Invalid password!') if user.is_verified: payload = { "id": user.id, "email": user.email, "exp": datetime.datetime.now(tz=timezone.utc) + datetime.timedelta(minutes=1440), "iat": datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() user = db.table('users').where('email', email).first() response.data = { "token": token, "data": { "user": user, "is_admin": True if user.role == 'admin' else False, }, "message": "Logged in successfully!" } db_logger.info('Logged in successfully!') #if password correct return response else: db_logger.error('Your account is not activated!!') return Response({'message': 'Your account is not activated!!'}, status=status.HTTP_400_BAD_REQUEST) -
Deploying a Django app on azure - No module named django
I am trying to deploy a django web app on azure but I am having no success with it! I have tried different methods for deployment (VSCode, Zip file, github..)and have followed different Qs on StackOverflow and other forums but in vain. Now I am trying to deploy using a zip file and getting the following error in logs: 2022-07-07T17:48:18.453487609Z Traceback (most recent call last): 2022-07-07T17:48:18.453492410Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-07-07T17:48:18.453496310Z worker.init_process() 2022-07-07T17:48:18.453515311Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-07-07T17:48:18.453519511Z self.load_wsgi() 2022-07-07T17:48:18.453522711Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-07-07T17:48:18.453526111Z self.wsgi = self.app.wsgi() 2022-07-07T17:48:18.453529411Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-07-07T17:48:18.453532912Z self.callable = self.load() 2022-07-07T17:48:18.453536112Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-07-07T17:48:18.453539512Z return self.load_wsgiapp() 2022-07-07T17:48:18.453542712Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-07-07T17:48:18.453546112Z return util.import_app(self.app_uri) 2022-07-07T17:48:18.453549312Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-07-07T17:48:18.453552813Z mod = importlib.import_module(module) 2022-07-07T17:48:18.453556013Z File "/opt/python/3.9.7/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-07-07T17:48:18.453559413Z return _bootstrap._gcd_import(name[level:], package, level) 2022-07-07T17:48:18.453562713Z File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-07-07T17:48:18.453566713Z File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2022-07-07T17:48:18.453570113Z File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2022-07-07T17:48:18.453573514Z File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2022-07-07T17:48:18.453576814Z File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2022-07-07T17:48:18.453580214Z File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2022-07-07T17:48:18.453583614Z File "/home/site/wwwroot/CricketWebsite/wsgi.py", line … -
Send list of filtered users to redis instance when function is triggered in frontend
Trying to create a function that when triggered in the frontend, will get a list of all users who are currently logged in and create key value pairs for all these users in my redis cache. This is what I am currently trying. I have this function in my views: def postToRedis(request): online_users = User.objects.filter(is_online='true').order_by('-date_joined') queue_of_users = { d['username'] for d in online_users } keys = list(queue_of_users.keys()) values = list(queue_of_users.values()) for i in range(0, len(keys)): redis_instance.set(keys[i], values[i]) response = { 'msg': f"{keys} successfully set to {values}" } return Response(response, 201) My intention here is to get a list of all users, filter for users who are online, get a list of all keys and correspondent values, loop through these lists and write each pair as a key value pair in my redis instance. I then have an API end point for my frontend to interact with my backend and trigger this function to run path("/post", postToRedis, name="postToRedis"), However when I try to trigger this function I do not get any of the desired output written into my redis_instance. Would love to get help on this -
Django AppRegistryNotReady when running another multiprocessing.Process
Problem I needed to run multiple UDP servers on different ports that exchange data with a Django core, so I defined a Django command which calls a method (start_udp_core) that runs each UDP server in a separate process. I used socketserver.UDPServer and stored the needed data for the socket using a Django model called ServerData. The Django version is 4.0.5 So I came up with this code: from core.models import ServerData from .data_receiver import UPDRequestHandler def create_and_start_server(host, server_data): with UDPServer((host, server_data["port"]), UPDRequestHandler) as server: try: logger.info(f"server is listening ... {server.server_address}") server.serve_forever() except KeyboardInterrupt: print("... going off ...") except Exception as e: logger.error(str(e)) def start_udp_core(): all_servers = ServerData.objects.values() logger.info(f"servers data ... {all_servers}") db.connections.close_all() default_host = "0.0.0.0" for server_data in all_servers: multiprocessing.Process(target=create_and_start_server, args=(default_host, card_data)).start() After running the command using manage.py, AppRegistryNotReady: Apps aren't loaded yet is being raised: INFO - start_udp_core - servers data ... - <QuerySet [{'id': 1, 'type_id': 1, 'ip': '192.168.0.50', 'port': 5000}, {'id': 2, 'type_id': 1, 'ip': '192.168.0.51', 'port': 5001}]> Traceback (most recent call last): File "<string>", line 1, in <module> Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\...\python\python39\lib\multiprocessing\spawn.py", line 116, in spawn_main File "c:\...\python\python39\lib\multiprocessing\spawn.py", line 116, in spawn_main exitcode = _main(fd, parent_sentinel) File … -
DJANGO TO HEROKU ImportError win32 only
i'm a begginer and i've been trying to upload my first django project to heroku and all worked fine untill i tried to run the app in heroku. I get this win32 only error and I can't seem to find an answer. This is the error I get and I cant figure it out. If you need any further info about the project so here is the git to it https://github.com/dngbr/Marut . Thank you Exception Type: ImportError Exception Value: win32 only Exception Location: /app/.heroku/python/lib/python3.10/asyncio/windows_events.py, line 6, in Python Executable: /app/.heroku/python/bin/python -
How can I set an attribute to use in both POST and GET methods in django class-based views?
So I'm building a class-based view that uses data from a table on my db, both on POST and GET methods. I've been trying to set an attribute with the table to mitigate the time that it would take to pull the table again for the sake of performance. Because of how functions/methods work I can't set an attribute like this: class MyClass (View): @md(login_required(login_url='login',redirect_field_name=None)) def get(self, request): con = create_engine('mysql+mysqlconnector://user:password@localhost:8000/schema') #function to get a dict with db tables tabs = get_tables(con) #Trying to make the attribute self.table = tabs['table_That_I_need'] context{'data':tabs} return render(request, 'markowitz/markowitz.html',context) @md(login_required(login_url='login',redirect_field_name=None)) def post(self, request): #this gives me an error since the attribute was not set table = self.table form = MarkowitzForm(request.POST,table) if form.is_valid(): pass return render(request, 'markowitz/results.html') I've been trying to use setattr but it doesn't seem to be working -
Why adding FilteredSelectMultiple widget to ModelMultipleChoiceField form field is not posting values selected?
I've been stuck around this issue for a while now and no existing post helped me solve it. I have a form with the following field declared in my forms.py: class SignRequestForm(forms.ModelForm): dental_codes = forms.ModelMultipleChoiceField( label='Select Proccedure Codes', queryset = CDTADACodes.objects.all() ) And this is processed in the views.py as it follows: class CreateInsuranceView(CreateView): def post(self, request, *args, **kwargs): #Declare and process patient_valid object if request.POST.get('eligibility_type') != 'Orthodontic': patient_valid.save() patient_valid.dental_codes.set\ (CDTADACodes.objects.filter\ (pk__in=request.POST.getlist('dental_codes'))) patient_valid.save() which works as expected. The problem is that when i want to add the FilteredSelectMultiple widget to dental_codes field the field is no longer posted in the form Here is the forms.py with the widget applied: class SignRequestForm(forms.ModelForm): class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) dental_codes = forms.ModelMultipleChoiceField( label='Select Proccedure Codes', queryset = CDTADACodes.objects.all(), widget = FilteredSelectMultiple('Dental Codes Selection', is_stacked=True) ) Finally this is the html template for the field INSIDE the <form>: <section> <div class="row justify-content-md-center"> <label>{{form.dental_codes.label}}</label> </div> <div class="row justify-content-md-center"> <div class="form-group" id="dental_codes"> {{form.media}} {{form.dental_codes.errors}} {{form.dental_codes}} </div> </div> </section> No errors are raised, it's just that in the request payload the field is no longer posted. Any help is more than welcomed, thanks in advance -
Can`t verify the email address with Django Rest and React
friend, I'm new and trying to figure it out. I have some problems with verification user via email. I have backend on 8000 port with Django rest framework and frontend on 3000 port with React. After registration I receive an email with link to submit email, like this: http://localhost:8000/activate/NDQ/b87jb3-6f86c3a304f606f584203f4d4e5ecfe8 If I click on this link, I receive an error Page not found (404). But if I change in address string Port on 3000: http://localhost:3000/activate/NDQ/b87jb3-6f86c3a304f606f584203f4d4e5ecfe8 verification submit and have no problem. What do I need to do to get verification through the link that comes in the letter, because there is port 8000, and the frontend has 3000