Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get value of ManyToMany Model rather than their ids?
I have three models, as shown below: class ImagesModel(models.Model): title = models.CharField(max_length=500, default='image') cdn = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='articles/images/', null=True, blank=True) timestamp = models.DateTimeField(auto_now=True) update = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class ArticlesModel(models.Model): title = models.CharField(max_length=1000) category = models.CharField(max_length=40, choices=category_choices, default=('General', 'General')) summary = models.TextField(blank=False, null=True, max_length=5000) tags = models.ManyToManyField(TagsModel, blank=True) publish_date = models.DateTimeField(auto_now=True) update_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(blank=True, null=True, upload_to='articles/article-image/') images = models.ManyToManyField(ImagesModel, blank=True) json = models.JSONField(null=True, blank=True) html = models.TextField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('articles:article_detail', kwargs={'article_id': self.id}) And in the view.py class ArticlesView(APIView): def get(self, request): articles_list = ArticlesModel.objects.all() images_list = ImagesModel.objects.all() images_serializer = ImagesSerializer(images_list, many=True) articles_serializer = ArticlesListSerializer(articles_list, many=True) return Response({ 'images':images_serializer.data, 'articles':articles_serializer.data }) So when I send request I get results like this: The problem here is that I get the ids of Images and tags and not the objects themselves! I am asking if there's a way in django/DRF to get the objects (images, tags) included with the queries of Articles and not only their ids? -
UserWarning on Kubernetes Django app in DigitalOcean
Deployed a Django app on a K8s cluster in Digital Ocean using a GitHub Actions Workflow, and this part run: | export SINGLE_POD_NAME=$(kubectl get pod -l app=django-doapp-web-deployment -o jsonpath="{.items[0].metadata.name}" | tr -d '\r') kubectl exec -it $SINGLE_POD_NAME -- bash /app/migrate.sh kubectl exec -it $SINGLE_POD_NAME -- bash /app/collectstatic.sh Even though it builds most of the time, it gives always the following Unable to use a TTY - input is not a terminal or the right kind of file /app/manage.py:21: UserWarning: Not reading /app/.env - it doesn't exist. dotenv.read_dotenv() As it is still not clear, decided to check the pod logs with kubectl logs -f [POD_NAME] There I can see this error [2022-10-20 04:49:36 +0000] [8] [INFO] Booting worker with pid: 8 /app/django_doapp/wsgi.py:19: UserWarning: Not reading .env - it doesn't exist. dotenv.read_dotenv(str(ENV_FILE_PATH)) This seems to be pointing to a problem in the wsgi.py file. Mine looks like this import os import pathlib import dotenv from django.core.wsgi import get_wsgi_application CURRENT_DIR = pathlib.Path(__file__).resolve().parent BASE_DIR = CURRENT_DIR.parent ENV_FILE_PATH = BASE_DIR / ".env" dotenv.read_dotenv(str(ENV_FILE_PATH)) # This is line 19 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_rentals.settings') application = get_wsgi_application() What is the impact of this and how to solve it? As it may be relevant the project structure is similar to … -
I want to make this website in a tabular format but it only comes in a vertical line
This is the output I am getting https://i.stack.imgur.com/Tqekd.jpg I have copies the bootstrap card code from the offical site and tried many changes to my code but the output always comes in a vertical line. *Please suggest a way to make it in a tabular format(likely 3 columns in a full window) it would be really helpful. * {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col-sm-4"> <div class="card" style="width: 18rem;"> <img src="{{ product.image_url }}" class="card-img-top" alt="..." width="300" height="300"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">${{ product.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> </div> </div>[enter image description here][1] </div> {% endfor %} </div> {% endblock %} -
Foriegn_key overwrite and show some field problem. I want to restock my inventory product
Foriegn_key overwrite and show some field problem. I want to restock my inventory product. enter image description here -
Django Filter by ForeignKey value
Suppose I have two models class DocumentType(BaseModel): name = models.CharField(max_length=128) code = models.CharField(max_length=128) exp_days = models.PositiveIntegerField("Remind me before (Days)", blank=True, null=True) def __str__(self): return str(self.name) class EmployeeDocument(BaseModel): type = models.ForeignKey("masters.DocumentType", on_delete=models.PROTECT) date_of_expiry = models.DateField(blank=True, null=True) attachment = models.FileField(blank=True, null=True) def __str__(self): return str(self.employee) I need to get the documents that will expire in the next {exp_days} mentioned in the type. documents = Document.objects.filter(date_of_expiry__lte=today+timedelta(days=30)) The above filter will return the documents expiring in the next 30 days. But how to apply the exact same condition -
Rotating User inside model in Django
Hi I have two models like below: class ShiftModel(BaseModel): name = models.CharField(max_length=256) class UserShiftModel(BaseModel): user = models.OneToOneField( "user.User", on_delete=models.CASCADE, related_name="user_shift" ) shift = models.ForeignKey( ShiftModel, on_delete=models.CASCADE, related_name="shift_user" ) Now, suppose I have four shifts in my ShiftModel: s1, s2, s3, s4 And in each shift I have unique users stored in UserShiftModel. For example: s1 = [u1, u2] s2 = [u3, u4] s3 = [u5, u6] s4 = [u7, u8] Now what I want is to rotate the shifts backwords that is [u1, u2] will be move from s1 to s4, [u7, u8] will be move from s4 to s3 and so on. How can I achive this? Things I have done so far: current_branch = organization_models.BranchModel.objects.get( id=kwargs.get("branch_id") ) rotating_shifts = current_branch.branch_shift.filter( shift_type="rotating" ).prefetch_related( Prefetch( "shift_user", queryset=models.UserShiftModel.objects.filter(user__is_active=True), ) ) for i in range(len(rotating_shifts)): shift = list(rotating_shifts)[i] previous_shift = list(rotating_shifts)[i - 1] for user in shift.shift_user.all(): user.shift = previous_shift user.save() But the output of the above code is like this: s1 = [u3, u4] s2 = [u5, u6] s3 = [u7, u8, u1, u2] s4 = [] What I want is this: s1 = [u3, u4] s2 = [u5, u6] s3 = [u7, u8] s4 = [u1, u2] Hope I am … -
How to stop Django from rendering result in new tab
I have following views and each time form is submitted, result is rendered in new tab which has empty form. How to render result in same form (with data submitted) without opening new tab? views.py class contact(View): def __init__(self, logger=None, **kwargs): self.logger = logging.getLogger(__name__) def get(self, request): return render(request, 'test.html') def post(self, request): if request.method == 'POST': form = ContactForm(request.POST, request.FILES) if form.is_valid(): self.host = form.data['ip'] messages.success(request, "Successful") else: form = ContactForm() else: form = ContactForm() return render(request, 'test.html', {'form':form}) forms.py class ContactForm(forms.Form): ip = forms.CharField() urls.py urlpatterns = [ path('', contact.as_view()), ] html <body> <form action="/" method= "post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> </body> -
Upgrading up from Heroku-18 for a Django app. Any watchouts?
Title pretty much says it - I have a simple Django app that's been running on Heroku-18 for several years. With the upgrade requirement deadline approaching in spring 2023 I'm concerned with how the upgrade may affect my site. My biggest concern is the the database. The app is configured with just the default SQLite db. Once I deploy it looks like Heroku uses Postgres for the database stored on their side. Basically it just works once I deploy so I don't really care. For some recent sites I've been working on though, when I deploy those on Heroku-22 also with the same db setup it is just continuing to use the SQLite file and the data I've been messing around with locally is now part of the database once in the live app! So I am concerned once I upgrade to Heroku 22 stack my app will disconnect with the Postgres data stored on Heroku and will point to my local SQLite file. Hopefully I'm worried over nothing, but if anyone in similar situation has already worked through the upgrade and can provide some information on my particular concern and/or anything else to watch out for that would be … -
django form isn't inserting values from views.py file
I'm trying to insert values into a Django Database using both HTML and a generated value from views.py This is my views.py def NewPassword(request): if request.method == "POST": if request.POST.get('app_name') and request.POST.get('url') and request.POST.get('username') and request.POST.get('email') and request.POST.get('Category'): form = PasswordsForm() form.app_name = request.POST.get('app_name') form.url = request.POST.get('url') form.username = request.POST.get('username') form.email = request.POST.get('email') form.category = request.POST.get('Category') print(form.app_name,form.url,form.username,form.email,form.category) new_password = GeneratePassword() new_password = HashPassword(new_password) form.password = new_password if form.is_valid(): print("Form saved") form.save() return redirect('/') else: form = PasswordsForm() form.app_name = request.POST.get('app_name') form.url = request.POST.get('url') form.username = request.POST.get('username') form.email = request.POST.get('email') form.category = request.POST.get('category') form.password = request.POST.get('password') print(form.app_name,form.url,form.username,form.email,form.category,form.password) if form.is_valid(): print("Form saved") form.save() return redirect('/') if form.is_valid() != True: print("Invalid Form") else: form = PasswordsForm() form = PasswordsForm() return render(request,'manager/create.html',{'form':form}) I get the Invalid Form error because the form fails the if form.is_valid() != True I don't think it's a form error because it's fully generated by Django. It is failing the is_valid condition but all the specific values have been added to the form. This is the models.py file TECH = 'TECH' NONE = 'NONE' BIZ = 'BIZ' EMAIL = 'EMAIL' ENT = 'ENT' FIN = 'FIN' GAMES = 'GAMES' NEWS = 'NEWS' OTHER = 'OTHER' SHOP = 'SHOP' SOCIAL = … -
New object not added to queryset in Django
Here is the model class Student(models.Model): """Student info""" id = models.CharField( max_length=7,primary_key=True) name = models.CharField(_('name'),max_length=8, default=""); # help_text will locate after the field address = models.CharField(_('address'),max_length=30,blank=True,default="") #blank true means the GENDER_CHOICES = [("M", _("male")),("F",_("female"))] student_number = models.CharField(max_length=10,blank=True) gender = models.CharField(_("gender"),max_length=6, choices = GENDER_CHOICES, default="M"); I user shell to create two users as below: But the queryset number didn't increase although I created two users. #I hate Django. Q = Q -
Google App Engine is consistently returning 400 response to non-custom domain
My use case is a Django app running in an app-engine service and I am using cloud tasks to execute async work in the background. Django creates task -> task posts back to Django to execute long-running task That post back is consistently encountering a 400 response from the server. After looking through the logs it appears that it is posting back a relative url with the host being the default google given domain i.e. sample-development-app.uc.r.appspot.com. When I navigate to that location in the browser I also encounter a 400 response. However, I have a custom domain set up and working on this application i.e. app.development.sample.com. When I navigate to this location in a browser I get the expected webpage. I have tried mapping both urls with a dispatch.yaml to the same default service, but that didn't change the result. My working assumption is that the task postback is encountering the same issue I am seeing in the browser. This is my first project on gcp app engine, so I am thinking I am missing something in a menu someplace to allow it to accept multiple urls, one of them being the default google supplied one. Thanks for reading this … -
django app on heroku keeps logging me as the same user regardless of what credentials I use
I've tried from authenticating from different devices but to no avail. Any suggestions as to why this is happening and how to fix it? -
render_to_string returning in a class based view
I have a django form that is made through a CreateView and ajax. The form is created fine through render_to_string however when i try to post it, the render_to_string line returns a NoReverseMatch error. Found this super confusing as im trying to store the render to string in a dictionary and return it as a JsonResponse: class ProjectFileCreateView(LoginRequiredMixin, CreateView): model = MyModel form_class = MyForm def get(self, request, *args, **kwargs): """Handle GET requests: instantiate a blank JSON version of the form.""" data, context = dict(), dict() form = MyForm() context = {'form': form, 'slug': self.kwargs['slug']} data["html_form"] = render_to_string("app/includes/partial_create.html", context, request=request) return JsonResponse(data) def post(self, request, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ data = dict() context = dict() form = MyForm(request.POST) if form.is_valid(): form.save() data["form_is_valid"] = True context = {'files': MyModel.objects.filter(project__slug=self.kwargs['project_slug']), 'project_slug': self.kwargs['project_slug']} data["html_form_list"] = render_to_string("project/file_list.html", context) else: data["form_is_valid"] = False data["html_form"] = render_to_string("project/includes/partial_create_file.html", {'form': form}, request=self.request) return JsonResponse(data) I comment out the the render_to_string and no error is thrown, however no object is created either. The full traceback is: Traceback (most recent call last): File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\asgiref\sync.py", line 472, in thread_handler raise exc_info[1] File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\core\handlers\exception.py", … -
Django: use update_or_create having the foreign key value but not a foreign key object instance
I have a data from a raw sql query which has records that look like this: "product_id": 12345 "date": 2022-12-25 "qty": 10 this is to go into a table with model "ProductMovement". Its unique key is product_id and date. product_movement has product_id as a foreign key to the Product model. ProductMovement.objects.update_or_create() requires me to provide an instance of the Product model, not merely the unique key. This is inconvenient. I guess I can use raw sql (backend is postgresql) but I wonder if there is another way. Can I add something to the model manager that intercepts the key value and replaces it with the instance, so at least I can hide this complexity from this part of the code? (I have never worked with model manager overrides). -
Pytest-django - testing creation and passing a required User object
Apologies if this has already been answered elsewhere. I cannot find an answer which I can retrofit into my situation. I'm new to django so I feel the problem is me not getting a fundamental grasp of a presumably basic concept here... Using DRF and pytest-django, i'm trying to be diligent and write tests along the way before it becomes too time consuming to manually test. I can see it snowballing pretty quickly. The issue I face is when I try to test the creation of a Catalogue, I can't get it to pass an User instance to the mandatory field 'created_by'. The logic works fine when I test manually, but writing the test itself is causing me headaches. Many thanks in advance! The error is: TypeError: Cannot encode None for key 'created_by' as POST data. Did you mean to pass an empty string or omit the value? Code provided. # core/models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True) # workshop/models.py from django.conf import settings from django.db import models class CatalogueItem(models.Model): TYPE_GOODS = 'GOODS' TYPE_SERVICES = 'SERVICES' TYPE_GOODS_AND_SERVICES = 'GOODS_AND_SERVICES' TYPE_CHOICES = [ (TYPE_GOODS, 'Goods'), (TYPE_SERVICES, 'Services'), (TYPE_GOODS_AND_SERVICES, 'Goods & Services') ] catalogue = models.ForeignKey( Catalogue, on_delete=models.CASCADE, related_name='catalogueitems') … -
Can Flask or Django handle concurrent tasks?
What I'm trying to accomplish: I have a sensor that is constantly reading in data. I need to print this data to a UI whenever data appears. While the aforementioned task is taking place, the user should be able to write data to the sensor. Ideally, both these tasks would / could happen at the same time. Currently, I have the program written using flask; but if django would be better suited (or a third party) I would be willing to make the switch. Note: this website will never be deployed so no need to worry about that. Only user will be me, running program from my laptop. I have spent a lot of time researching flask async functions and coroutines; however I have not seen any clear indications if something like this would be possible. Not looking for a line by line solution. Rather, a way (async, threading etc) to set up the code such that the aforementioned tasks are possible. All help is appreciated, thanks. -
PyGraphViz isnt running with Django error when django is installed
Django is running into an issue where when I try to run the PyGraphViz manage.py script it errors when it tries to import django.core.management Traceback (most recent call last): File "/home/zoctavous/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 259, in fetch_command app_name = commands[subcommand] KeyError: 'graph_models' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/zoctavous/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/zoctavous/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/zoctavous/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 266, in fetch_command settings.INSTALLED_APPS File "/home/zoctavous/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/home/zoctavous/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/home/zoctavous/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in … -
Deploy django channels to dcoker and use nginx has a proxy server
Im trying to deploy django channels using docker, and im using the daphne protocol to serve the application. when i run that its starts successfully but i'm unable to connect with the websocket. i can connect with the application in other routes but cannot connect with the websocket the websocket is served in HTTPS://EXAMPLE.COM/WS/SOCK this is my asgi.py application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ))}) Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /myproject ADD . /myroject RUN pip install -r /myprjoect/requirements.txt EXPOSE 8000 CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "myproject.asgi:application"] nginx.conf location / { proxy_set_header Host $http_host; proxy_set_header X-Forward-Proto https; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://localhost:8443/; } #path to proxy my WebSocket requests location /ws/ { proxy_pass http://localhost:8443; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } and im using the docker-compose to up the application anf its configuration is version: "3.8" services: myservice: image: myimage container_name: my_container ports: - 8443:8000 -
How to get many2many queryset of a model while creating it (while save() is running)
I have a model "Team" for soccer team and a model "Contest" for soccer match. For a Contest model creation, the name is automatically assigned. Then, while save() I want to modify the name of contest to something related to the teams that compete. So in my Contest model I have a ManyToMany field 'teams' related to my 'Team' model. While save(), I used super().save(*args, **kwargs) before get my item so it exists. Then I want get a queryset by self.objects.teams.all() but each time the queryset is empty : <QuerySet []>. Yet, the object exists. Feel like Django has not yet related the teams or something. How can I do that ? Contest model : class Contest(models.Model): name = models.CharField(max_length=16, primary_key=True, unique=True, default="InactiveContest", blank=True) # Ex: PSGvMNC_09/2017 id = models.IntegerField(default=1) teams = models.ManyToManyField(Team, verbose_name="opposants") date = models.DateTimeField(blank=True) winner = models.ForeignKey(Team, verbose_name='gagnant', related_name='winner', on_delete=models.SET_NULL, blank=True, null=True) loser = models.ForeignKey(Team, verbose_name='perdant', related_name='loser', on_delete=models.SET_NULL, blank=True, null=True) active = models.BooleanField(default=False) def save(self, *args, **kwargs): if self._state.adding: self.active = False # Django's id imitation last_id = Contest.objects.all().aggregate(Max('id')).get('id__max') if last_id is not None: self.id = last_id + 1 super().save(*args, **kwargs) # Now I can get it teams = self.teams.all() if not teams: raise ValueError("Not teams.") # … -
Django model method paramter with default value from related
I need a model method with parameter with default value: class MyModel(modelsModel): parameter1 = models.DecimalField(max_digits=8,decimal_places=6, default=0) def my_method(self, parameter = parameter1) return parameter so if use print("{} - {}".format(object.my_method(),object.my_method(12.6)) it's ok But i need it more nested: class MySubModel(modelsModel): parameter1 = models.DecimalField(max_digits=8,decimal_places=6, default=0) class MyModel(modelsModel): submodel = models.ForeignKey(MySubModel, on_delete = models.RESTRICT) def my_method(self, parameter = submodel.parameter1) return parameter And this raises error: AttributeError: 'ForeignKey' object has no attribute 'parameter' Ideas? -
Updating database data from websocket
I would like to update database data from a websocket. Specifically, when a user connects to a websocket, I would like to update a field in one of my models with the timestamp of when the user connected. However, with the logic I have implemented, I am getting this error: Exception inside application: __init__() takes 1 positional argument but 2 were given Traceback (most recent call last): File "C:\Users\15512\anaconda3\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, receive, send) File "C:\Users\15512\Desktop\django-project\peerplatform\signup\middleware.py", line 47, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\15512\anaconda3\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\15512\anaconda3\lib\site-packages\channels\utils.py", line 51, in … -
Set and call a variable in HTML (potentially including javascript) in django
I have a HTML code in Django, if certain conditions are met I want to set the colour of a div container. As can be seen in between the script tags, if one condition is met the colour should be set to success, if another is met the colour should be set to danger, then later on in the code in the div class description where I have put (colour) is where this variable should be called. Any advice would be greatly appreciated -
500 internal server error while using Django and React
I faced some problem using react and django. When I made a http request to django server, I got 500 Internal Server Error. My code looks like. urls.py from usercontrol.views import * urlpatterns = [ path('admin/', admin.site.urls), path('auth/', UserView.as_view(), name="something") ] usercontrol/views.py from http.client import HTTPResponse from django.shortcuts import render from rest_framework.views import APIView from . models import * from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, AllowAny # Create your views here. class UserView(APIView): permission_classes = [AllowAny] def get(self, request): if request.user.is_authenticated: print ("HELO") return HTTPResponse("Hello") def post(self, request): return HTTPResponse("Hello") React Code axios.get("http://localhost:8000/auth/") .then((res) => { console.log(res); }) .catch((err) => {}); Why do I get 500 Internal Server Error? Please help me to fix this error. -
Modelformset extra field pk is rendered as next instance in Django
I don't get why my extra fields in Modelformset are rendered with next instance pk, when form where I have already saved data is showing relevant related model instance pk. Is this something why Django suggests to render pk field explicitly in the templates, so user to choose right related model pk? looks to me unbelievable, so please help me here... # My views.py from django.forms import modelformset_factory from .models import PreImplement # Pre Implement View def pre_implement_view(request, pk): moc = get_object_or_404(Moc, pk=pk) print(moc.pk) PreImplementFormSet = modelformset_factory(PreImplement, fields=('__all__'), can_delete=True, can_delete_extra=False) formset = PreImplementFormSet(queryset=PreImplement.objects.filter(moc_id=moc.pk), initial=[ {'action_item': 'go'}, {'action_item': 'nogo'}, {'action_item': 'na'}, ]) formset.extra=3 queryset=PreImplement.objects.filter(moc_id=moc.pk) print('babr', queryset) if request.method == 'POST': formset = PreImplementFormSet(request.POST, initial=[{'action_item': 'babrusito'}, {'action_item': 'go'}, {'action_item': 'nogo'}, {'action_item': 'na'}, ]) if formset.is_valid(): formset.save() return redirect('index') return render(request, 'moc/moc_content_pre_implement.html', context={'moc': moc, 'formset': formset}) This is continuation of my previous SO post struggles: Populate model instance with another model data during instance creation Here is snapshot from my template: -
Issues with looping through an object in django channels
Am Trying to loop through an a model object in django, I think this the error is coming from consumer.py file this file in particular, I keep getting this error for message in messages: TypeError: 'Messages' object is not iterable and i think the error comes from this code in particular def messages_to_json(self, messages): result = [] for message in messages: result.append(self.messages_to_json(message)) return result My models.py class Messages(models.Model): sender = models.ForeignKey(User, related_name='messages', on_delete=models.CASCADE) msg = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.sender.username def last_30_messages(self): return Messages.objects.order_by('-timestamp').all()[:20] My consumer.py from django.contrib.auth import get_user_model import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Messages User = get_user_model() class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Messages.last_30_messages() content = { 'messages': self.messages_to_json(messages) } self.send_chat_message(content) def new_messages(self, data): sender = data['from'] author_user = User.objects.filter(username=sender)[0] message = Messages.objects.create(sender=author_user, msg=data['message']) content = { 'command': 'new_messages', 'message': self.messages_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.messages_to_json(message)) return result def message_to_json(self, message): return { 'sender': message.sender.username, 'msg': message.msg, 'timestamp': str(message.timestamp) } command = { 'fetch_messages': fetch_messages, 'new_messages': new_messages } def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_link"] self.room_group_name = "chat_%s" % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( …