Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTML not rendering properly
I'm trying to render an HTML in my django project on the basis of data that I'm receiving from the backend but can't understand on how to do it. If somebody can help me out that would be super awesome. Thanks Here is the structure of the data that I have { "structure":"linear", "layout":[ { "structure":"Rubber_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"Model_duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "MuteQuack", "No Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"grid", "layout":[ { "structure":"Mallord_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"Rubber_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"Rubber_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"Rubber_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true } ] }, { "structure":"linear", "layout":[ { "structure":"Model_duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "MuteQuack", "No Quack!" ] }, "custom_behaviour":"", … -
Can I serve static files (css, html, etc.) from a different server in Django
So I'm trying to serve templates, images, css and other static files from a Web Server (frontend) running Apache into an App Server (backend) running Django, the Django app is already proven to work locally so I splited static files and push them into the Web server and the .py files into the App Server, so far I've seen that I need to use mod_wsgi package from Apache and then run $ python manage.py collectstatic So it makes a copy of those static files into the App Server. But the problem comes when changing the urls of every template. Also I saw this other solution but I'm not sure if I implement that solution I still need to do the mod_wsgi thing. Can someone please help me out here please? Or give me some advice on how to do it? Thanks -
AWS Elastic Beanstalk : Deploying Django application Failed
I've been trying to deploy my Django backend for my react application on EB but I can running into an error when I try deploying.I'm not sure how to pull up more details from the log, but I have also attached by requirements.txt file below the error results. 2020-11-22 23:44:27 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2020-11-22 23:44:30 ERROR [Instance: i-0da4be9088c225a28] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2020-11-22 23:44:31 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2020-11-22 23:45:33 ERROR Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. asgiref==3.3.1 attrs==20.3.0 awsebcli==3.19.2 bcrypt==3.2.0 blessed==1.17.11 boto3==1.16.23 botocore==1.19.23 cached-property==1.5.2 cement==2.8.2 certifi==2020.11.8 cffi==1.14.3 chardet==3.0.4 colorama==0.4.3 cryptography==3.2.1 Django==3.1.3 django-cors-headers==3.5.0 django-environ==0.4.5 django-storages==1.10.1 djangorestframework==3.12.2 docker==4.3.1 docker-compose==1.25.5 dockerpty==0.4.1 docopt==0.6.2 environ==1.0 future==0.16.0 idna==2.10 jmespath==0.10.0 jsonschema==3.2.0 mysql-connector-python==2.0.4 mysqlclient==2.0.1 paramiko==2.7.2 pathspec==0.5.9 Pillow==8.0.1 pycparser==2.20 PyMySQL==0.10.1 PyNaCl==1.4.0 pyrsistent==0.17.3 python-dateutil==2.8.1 pytz==2020.4 PyYAML==5.3.1 requests==2.24.0 s3transfer==0.3.3 semantic-version==2.5.0 six==1.15.0 sqlparse==0.4.1 termcolor==1.1.0 texttable==1.6.3 urllib3==1.25.11 wcwidth==0.1.9 websocket-client==0.57.0 -
How to pass 2 parameters in for loop in django templates
i want to pass 2 parameters in for loop in my template {% for x, y in text %} <p>{{ x }}</p><h1>{{ y }}</h1> {% endfor %} my views: text = [("e", "w"), ("1", "2")] return render(request, "my_template.html", {"text": text}) this isn't even loop and it does absolute nothing what I need to write in the template or in "text" to make this work? -
Django Post Deployment Issues - Scripts and Models
Hi it's my first time deploying a Django app. I'm using PythonAnywhere to host and learn more. I am aware that deployment requires additional steps and code changes versus dev and believe I have taken these steps researching the documentation and other issues on Stack Overflow. After separating out javascript from the html, migrating the models and collecting the static files I'm having a major issue with the style of the index file not inheriting the base layout as well as being running the javascript. Additionally drop downfields that are reading from models are not working. Note all other pages are inheriting the base file but are not linking to models either for dropdowns. I've reviewed the models and they are in place and populated. Likely I am missing something with the base layout file and the models. Greatly appreciate if someone can point me in the right direction. Layout.html (base layout file) <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> <script src="{% static 'app/scripts/modernizr-2.6.2.js' %}"></script> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" /> </head> … -
Restricting Signal Notifications in a Django Project to specific Attribute in Model
I have added a notification everytime a user submits a Like button to a post, the owner of the liked post receives a notification. I have set Value options for each Like button to be Like or Unlike so now I am trying to restrict the notification to be sent only if the Value of the like clicked is Like only. So, now in the Like Model I have added signal and a condition that if the Like.value== Like the signal activates but for some reason it is not working and I am not sure why. My question is: How do I set the notification signal to be sent only when the Like.value== Like? Here is the post models.py: class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the like models.py: LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" def user_liked_post(sender, instance, *args, **kwargs): if Like.value=='Like': like = instance post = like.post sender = like.user notify = Notification(post=post, sender=sender, user=post.author, notification_type=1) notify.save() else: None def user_unlike_post(sender, … -
how to set a timer or schedule non-periodical task in Django > 3.0 and DRF
Im new to async programming and new Django's docs aren't really specific what should and should not be done so here is my question. How to set some kind of a timer in Django (or django-programatically in server) after which some Django code will be run. To visualize this I will present an example: Student has 10 minutes to write a test. Student starts a test (enters some view). Student can post his test results within those 10 minutes but if he crosses the 10 minute barrier, the test should stop and such event should be saved in database. This sounds like an async job but I don't know the good practise for coding that. If it can be done synchornousily it would be much better. To clarify - I'm using Django REST framework and the student is on a mobile client. (setting a timer in mobile app is not an option due to security reasons). I know about Celery but it seems like an overkill when Django already has async. I will add that there will be several tousand student tests running at the same time so performance is important. Can anyone help me or point me to a … -
How to add two Field Instances in a Django Model into a variable?
Good day! I'm trying to understand if there is a proper way of adding name_first & name_last Fields in the Customer Model into name_full Field. The name_full Field will be used as ftring renurn value for the Model. Relation with the Order Model via Foreign Key. class Customer(models.Model): name_first = models.CharField(max_length=30, null=False, blank=False) name_last = models.CharField(max_length=30, null=False, blank=False) # name_full = ... name_first+name_last def __str__(self): return self.name_full I've tried looking for similar question and there is a slight chance of not knowing how to ask a proper question) Cheers! -
Store a matrix in Django
I have the following matrix: item_1 item_2 item_3 item_1 1 0 0 item_2 0 2 0 item_3 0 0 3 What is the best way to store this matrix into django, so that in the future I can retrieve an entire column (being able to see the ID of each row), and use it to perform some calculations in a view? Obs: This matrix is going to have thousands of columns and rows. -
Passing id in url to get object info
I'm like 3 days trying to find the solution to this problem. I have a dashboard with items, every single item is called board. The dashboard is populated with object that i've stored in my local db. Data like the name of this board is shown in the html page called dashboard. What i want to do is, when i click on the link named 'Scopri di più' , to be redirected in the board.html populated with the clicked item data. At the time i'm only getting the error 'NoReverseMatch'. What am i doing wrong? dashboard.html {% extends "base.html" %} {% block content %} <h3>{{title}}</h3> <a href="/new_board/" class="text-dark">Aggiungi Board</a> <div class="row mt-5"> {% for bn in user_board_list %} <div class="col ml-4"> <div class="card"> <div class="card-body"> <h5 class="card-title"> {{ bn.board_name}} </h5> <p class="card-text">Breve descrizione della board</p> <a href="{% url 'board_view' pk=board.id %}">Scopri di più</a> </div> </div> </div> {% endfor %} </div> {% endblock %} views.py class Board_dets_view(DetailView): template_name = "board.html" def board_view(request, pk): title="Board" #board = get_object_or_404(request,pk=pk) board = Board.objects.get(pk=pk) context = {'title': title, 'board': board} return render(request, 'board.html', context) models.py class Board(models.Model): board_name = models.CharField(unique=True, max_length = 200, verbose_name='board_name', error_messages= {'unique': 'Nome della board già utilizzato. Per favore inseriscine un … -
Where is the error ???? KeyError: 'start_date'
I havent put any body arguments (start_date, end_date) in my GET request , should work else statement but appears strange mistake , so there is issue ?? class MoviesTop(APIView): def get(self, request): if request.data.get('start_date', 'end_date'): start_timestamp = request.data['start_date'] end_timestamp = request.data['end_date'] topMovie = Movie.objects.annotate( num_comments=Count( 'Comments', filter=Q(Comments__pub_date__range=( start_timestamp, end_timestamp)) ) ).order_by('-num_comments') else: topMovie=Movie.objects.annotate( num_comments=Count('Comments')).order_by('-num_comments') serializer=MoviesTopSerializator(topMovie, many=True) return Response(serializer.data) -
Django values_list returns only one result
i'm just stucked into a problem while returning values from table, here you can look at my Django Model: class Server(models.Model): organization = CustomCharField( choices=get_choices('organizations'), max_length=255, blank=True ) Here you can see my Choice model: class Choice(models.Model): organizations = JSONField(default=list) def __str__(self): return self._meta.model.__name__ So if i try this: Choice.objects.values_list('organizations', flat=True).distinct() I got that: <QuerySet [[['Company1', 'Company1'], ['Company2', 'Company2'], ['Company3', 'Company3'], ['Company4', 'Company4']]]> The main problem contains in this line of code: Server.objects.values_list('organization', flat=True).distinct() And it returns this: <QuerySet ['Company3', '']> What's wrong with this? Can someone explain me. Feel free to answer. -
MultiValueDictKeyError at /meeting/user-location-update/
I have this form on my django template which gets a user info and updates it and when i want to save the update i get this error : MultiValueDictKeyError at /meeting/user-location-update/ 'avatar' and avatar is the user profile photo on models.py this is my form : <html> <body> <form action="" method="post" name="updatelocation_form" enctype="multipart/form-data"> {%csrf_token%} <label for="your_name">latitude </label> <input id="lat" type="text" name="lat" value="{{user_info.lat}}"> <input id="lng" type="text" name="lng" value="{{user_info.lng}}"> <input id="user_address" type="text" name="user_address" value="{{user_info.user_address}}"> <input type="file" id="avatar" name="avatar" value="{{user_info.avatar}}"> <input type="submit" value="submit"> </form> {%if messages%} {%for message in messages%} {{message}} {%endfor%} {%endif%} </body> and this is views.py : @login_required def userlocation_update(request): user_info= get_user_model().objects.get(username=request.user) if request.method=="POST": updatelocation_form = UserLocation_updated(request.POST or None, request.FILES or None,instance=request.user) if updatelocation_form.is_valid(): updatelocation_form.save() return redirect('index') else: messages.error(request, "error") else : updatelocation_form = UserLocation_updated() return render(request, '../templates/templates_v2/update_location.html', {'updatelocation_form': updatelocation_form,'user_info':user_info}) -
Shared Django field across model instances
I'm new to Django, and need help with something quite basic. Suppose we created a model representing a worker, and we wanted to create a function to calculate how much each worker made after taxes. For simplicity, a worker has a take-home pay of their gross income times their tax rate, and the tax rate is a variable that all workers share. class Worker(models.Model): gross_income = models.FloatField(null=True, blank=True) def take_home_pay(self): return self.gross_income * tax_rate I know how to store each worker's gross income in the database. I did it using models.FloatField. Here's my questoin: how would I store the tax rate, which is shared across workers, in the database? -
Static files 404 in production
None of my static files are loading after deploying my app. When I check in the dev tools they're all 404. I ran python3 manage.py collectstatic My static folder has the following permissions and ownership: drwxr-xr-x 8 root root 4096 Nov 17 23:28 static My /etc/apache2/sites-enabled/example.conf: <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/example-error.log CustomLog ${APACHE_LOG_DIR}/example-access.log combined WSGIDaemonProcess example processes=2 threads=25 python-ho> WSGIProcessGroup example WSGIScriptAlias / /srv/example/example/wsgi.py Alias /robots.txt /srv/example/static/robots.txt Alias /favicon.ico /srv/example/static/favicon.ico Alias /static /srv/example/static/ Alias /media /srv/example/media/ <Directory /srv/example/example> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /srv/example/static> Require all granted </Directory> <Directory /srv/example/media> Require all granted </Directory> </VirtualHost> -
How to add Conditionals for a Notifications System in a Django Project
I have set a Notification system for my Django project when a user likes or comments on a post the Author received a notifications of this activity. I am trying to add an option so that the Author of the Post can receive a Notification also when the num_likes reaches a certain no. So, here is what I have tried but nothing happened. Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Blog Posts' #---------------------------My trial------------------------------------------ def like_progress(sender, instance, *args, **kwargs): post = instance if post.num_likes == 1: notify = Notification(post=post, user=post.author, notification_type=3) notify.save() # num_likes post_save.connect(Post.like_progress, sender=Post) #---------------------------My trial------------------------------------------ Here is the notifications model.py class Notification(models.Model): NOTIFICATION_TYPES=((1,'Like'),(2,'Comment'),(3,'Admin')) post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name="noti_post", blank=True, null=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="noti_to_user") notification_type= models.IntegerField(choices=NOTIFICATION_TYPES) text_preview= models.CharField(max_length=90,blank=True) date=models.DateTimeField(auto_now=True) is_seen=models.BooleanField(default=False) def __str__(self): return self.notification_type here is the notifications app views.py def ShowNotifications(request, *args, **kwargs): user=request.user notifications= Notification.objects.filter(user=user).order_by('-date') Notification.objects.filter(user=user, is_seen=False).update(is_seen=True) template= loader.get_template('notifications/notifications.html') context = { 'notifications': notifications, } return HttpResponse(template.render(context, request)) here is … -
Docker "Error During Connect" (Duplicate)
This is a duplicate but I decided to post because the version for other posts are not on the same version as mine and not on the same OS So I am running on windows 10 and docker version 19. I have this issue where when I run some commands such as docker version or docker run , it throws an error with something like: error during connect ..... this suggest docker daemon might not be running So I decided to check if docker daemon is running, I opened Docker Destop but the setting run when log in is checked and I looked in task manager and it shows a process called docker service is running in the background so meaning that it should be running (right?) So I decided this might be another problem, does anyone have suggestions on what I should try to resolve the problem? Thanks -
How to get data from the following form?
What's the right way to get data from the following form? I would like to get it into a Django view or just JQuery and make ajax call to Django. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/css-toggle-switch@latest/dist/toggle-switch.css" rel="stylesheet"/> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <fieldset> <legend>View</legend> <div class="switch-toggle alert alert-light"> <input id="week" name="view" type="radio" checked> <label for="week" onclick="">Week</label> <input id="month" name="view" type="radio"> <label for="month" onclick="">Month</label> <a class="btn btn-primary"></a> </div> </fieldset> -
How to display data in a given time range in Django?
Sort films by number of comments topMovie = Movie.objects.annotate( num_comments=Count('Comments')).order_by('-num_comments') model.py: class Movie(models.Model): Title = models.CharField(max_length=200) Year = models.CharField(max_length=25, blank=True) Rated = models.CharField(max_length=10, blank=True) class Comment(models.Model): comment_text = models.CharField(max_length=200) movie_id = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='Comments') pub_date = models.DateTimeField(blank =True,default = now) how to transfer the time frame to display this field topMovie = Movie.objects.annotate( num_comments=Count('Comments')).order_by('-num_comments') within the specified time frames -
Wagtail and Django-Tenants, does it work together?
Does anyone have experience in this topic? Is it fully incompatible or might it be possible to customize certain parts of the app to make it work. -
Date filters fail in django
I have a function: def update_coins_table(): # Check if the currency has been updated in the last hour up_to_date_currency = Currency.objects.filter( currency_value_in_dollars_date= [datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)] if up_to_date_currency.exists(): # Return if it is return if not do_greeting(): print("Gecko crypto board not reachable. Db setup") return crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd') datetime_now = datetime.now() for coin_key in crypto_coins_prices: coin = Currency( currency_name=coin_key, currency_value_in_dollars=crypto_coins_prices[coin_key]['usd'], currency_value_in_dollars_date=datetime_now) coin.save() and get the following error on executing filter(), up_to_date_currency = Currency.objects.filter( currency_value_in_dollars_date= [datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)] Error message: Internal Server Error: /get_currency/ Traceback (most recent call last): File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\views.py", line 21, in get_latest_currency update_coins_table() File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\get_coins_scheduler.py", line 38, in update_coins_table up_to_date_currency = Currency.objects.filter( File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup lookup = lookup_class(lhs, … -
Websocket close with 200 status
I have setup websocket using nginx and daphne. I am also using gunicorn for handling http request. I apply the same setting in previous server it works fine now in the new server with the same setting the websocket is returning 200 satus and not connecting. Console log: WebSocket connection to 'wss://ubl.mn/ws/2/' failed: Error during WebSocket handshake: Unexpectedresponse code: 200 Daphne log: 127.0.0.1:25894 - - [22/Nov/2020:18:35:51] "GET /ws/2/" 200 3146 127.0.0.1:25900 - - [22/Nov/2020:18:36:02] "GET /ws/2/" 200 3146 The log of where the websocket is working is: 127.0.0.1:9596 - - [22/Nov/2020:18:49:09] "WSCONNECT /ws/6512/" - - 127.0.0.1:9596 - - [22/Nov/2020:18:49:54] "WSDISCONNECT /ws/6512/" - - So it seems the difference between working and not working server is in daphne log one has GET and another request has WSCONNECT like that. I don't want to post all code here at first, can someone please point to me where I may have made the mistake I can provide further info about it. -
How could I save multiple users by using a checkbox with a ManyToMany relationship?
I already did create 4 objects in Role table which refers to the role of users in website. the Role was a list but I created it in User model as a checkbox input to allow the user to choose what he wants among roles but I can't save my data that comes through cleaned_data which refers to roles data, I get the following error: 'RegisterForm' object has no attribute 'roles' in forms.py file what I miss here? here is my code: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import User, Profile, Role class RegisterForm(UserCreationForm): password1 = forms.CharField(min_length=4, widget=forms.PasswordInput(attrs={ 'placeholder': 'Password' }), label='password') password2 = forms.CharField(min_length=4, widget=forms.PasswordInput(attrs={ 'placeholder': 'Confirm Password' }), label='Confirm Password') class Meta: model = User fields = ['email', 'first_name', 'last_name', 'roles', 'password1'] widgets = { 'roles': forms.CheckboxSelectMultiple() } def clean_password2(self): password = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password and password2 and password != password2: raise forms.ValidationError("password and confirm password is not same") if len(password) < 4: raise forms.ValidationError('Password is very weak please enter 4 words at least') return password def save(self, commit=True): user = super().save(commit=False) if commit: user.staff = True user.set_password(self.cleaned_data['password1']) self.roles.add(self.cleaned_data['roles']) user.save() return user models.py from django.db import models from django.contrib.auth.models import … -
getting unexpected/unwanted url path when clicking on an href link in django
so, here are all the urls i defined: path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("new", views.new.as_view(), name="new"), path("<int:user>/watchlist", views.watchlist, name="watchlist"), path("<int:user>/<str:name>", views.name, name="name"), path("<str:user>/<str:name>/watchlist/remove", views.remove, name="remove-from-watchlist"), path("<int:user>/<str:name>/watchlist/add", views.add, name="add-to-watchlist"), path("<str:user>/<str:name>/bid", views.bid, name="bid"), path("<str:user>/<str:name>/close", views.close, name="close-bid"), path("<str:user>/<str:name>/comment", views.comment, name="comment"), path("add-category", views.addC, name="add-Category"), path("categories", views.categories, name="categories"), path("<str:cat>/category", views.cat, name="category-page") From experience, the problem is with all the 'watchlist' related URLs. For example, when i am on index view, the path to path("<int:user>/watchlist", views.watchlist, name="watchlist"), is <a class="nav-link" href="{{ user.id }}/watchlist">Watchlist</a> and the url path shows the same - http://127.0.0.1:8000/2/watchlist where 2 is the user id. Then when i go to a url <a class="nav-link" href="categories">Categories</a> the url path followed is http://127.0.0.1:8000/2/categories the '2' should not be there! I specifically hard coded the path in the anchor tag I am facing another problem: when i am at the index view and i click on the anchor tag containing <a href=/{{ user.id }}/{{ item.Title }} where item.Title is say "Magic Broom", the url path i am getting is http://127.0.0.1:8000/2/Magic while it should have been http://127.0.0.1:8000/2/Magic Broom Can someone please explain what's going on here... -
Django: problem to create nested serializers
I'm trying to create a nested serializers but I'm getting this error: raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Pessoa() got an unexpected keyword argument 'endereco_pessoa' This is my serializers.py: class EnderecoSerializer(serializers.ModelSerializer): class Meta: model = Endereco exclude = ('id_endereco', 'id_pessoa',) # id_endereco is pk and id_pessoa because we'll create one while sending the post request class PessoaSerializer(serializers.ModelSerializer): endereco_pessoa = EnderecoSerializer() class Meta: model = Pessoa fields = ('cpf', 'nome', 'nome_social', 'sexo', 'data_nascimento', 'cor_raca', 'estado_civil', 'municipio_naturalidade', 'uf_naturalidade', 'pais_nascimento', 'endereco_pessoa', ) def create(self, validated_data): enderecos_data = validated_data.pop('endereco_pessoa') endereco = Endereco.objects.create(**enderecos_data) pessoa = Pessoa.objects.create(endereco_pessoa=endereco, **validated_data) return pessoa What am I doing wrong here? I really appreciate any help. I've seen a lot of similar questions like mine, but all solutions not worked for me.