Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'phonenumbers'
I am deploying an app which works well locally to Heroku for the first time, and I have the following error: ModuleNotFoundError: No module named 'phonenumbers' 2021-08-01T05:05:10.359150+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-08-01T05:05:10.359151+00:00 app[web.1]: django.setup(set_prefix=False) 2021-08-01T05:05:10.359151+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup 2021-08-01T05:05:10.359152+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2021-08-01T05:05:10.359152+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate 2021-08-01T05:05:10.359152+00:00 app[web.1]: app_config = AppConfig.create(entry) 2021-08-01T05:05:10.359153+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create 2021-08-01T05:05:10.359153+00:00 app[web.1]: module = import_module(entry) 2021-08-01T05:05:10.359153+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2021-08-01T05:05:10.359154+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-08-01T05:05:10.359154+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2021-08-01T05:05:10.359155+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2021-08-01T05:05:10.359155+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked 2021-08-01T05:05:10.359221+00:00 app[web.1]: ModuleNotFoundError: No module named 'phonenumbers' 2021-08-01T05:05:10.360272+00:00 app[web.1]: [2021-08-01 05:05:10 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-08-01T05:05:10.416411+00:00 app[web.1]: [2021-08-01 05:05:10 +0000] [10] [ERROR] Exception in worker process 2021-08-01T05:05:10.416412+00:00 app[web.1]: Traceback (most recent call last): 2021-08-01T05:05:10.416413+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-08-01T05:05:10.416413+00:00 app[web.1]: worker.init_process() 2021-08-01T05:05:10.416414+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-08-01T05:05:10.416414+00:00 app[web.1]: self.load_wsgi() 2021-08-01T05:05:10.416415+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-08-01T05:05:10.416415+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-08-01T05:05:10.416419+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-08-01T05:05:10.416420+00:00 app[web.1]: self.callable = self.load() 2021-08-01T05:05:10.416420+00:00 … -
How to set mocked instance variable of class in python?
I'm writing a unit test for MyProducer class which produces the message on kafka topic. logic of testing is just mock the constructor of MyProducer class and set the manually created producer object to the instance of MyProducer class and then just verify if library methods of confluent-kafka are getting called correctly or not. I'm stuck in setting the manually created producer object to MyProducer. How can we set the manually created object to instance variable of MyClass by mocking init? # kafka_producer.py # actual code class MyProducer(object): def __init__(self, config: Dict[str, Any]={}): self.producer = Producer(config) def produce(self, *args, **kwargs): pass # test_kafka.py # testing def get_producer(*args, **kwargs): print(args,kwargs) conf = { "bootstrap.servers": 'localhost:9093' } producer = Producer(conf) def produce(*args, **kwargs): pass class KafkaTest(unittest.TestCase): def setUp(self): pass @mock.patch( "utils.kafka_producer.KafkaProducer.__init__", ) @mock.patch( "confluent_kafka.Producer.produce", ) def test_kafka_producer(self, produce, kafka_producer): produce.side_effect = produce kafka_producer.side_effect = get_producer kafkaProducer = MyProducer( {'bootstrap.servers': os.environ['KAFKA_BOOTSTRAP_SERVERS']} ) kafkaProducer.produce(fake_kafka_topic, value='test_data') It is giving error: AttributeError on 'MyProducer' has no attribute 'producer'. -
Google app engine disable request logging
I'm looking for a way to filter out request logging spam so I can more easily see warnings or errors. This seems to work locally: 'loggers': { 'django': { 'handlers': ['console'], 'level': 'WARNING', } } but fails on GAE According to this question this isn't possible and I need to use a log parser instead. However, that was 7 years ago, so I'm wondering if there's now a way to get this to work. Additionally, the answer links to a log parser which results in a 404, so if this isn't possible, I would like a link to a working log parser -
Adding new data to class in a Django model
I have a form which requires adding a standard name and if there is an option to add additional names to be added I want to create another input for it. I am not sure how to do that in regard to the Models, and migrating and creating the html related to the new name to take in the input. I have created the form with the following models: ownerName1= models.CharField(max_length=100,null=True, blank=True, verbose_name='Owner Name 1') ownerRole1= models.CharField(max_length=100,null=True, blank=True, verbose_name='Owner Role 1') ownershipPercentage1= models.IntegerField(null=True, blank=True, verbose_name='Business Phone 1') I added in the HTML template a button to add a new shareholder if available so I want if the button is created to create the following in the models.py ownerName2= models.CharField(max_length=100,null=True, blank=True, verbose_name='Owner Name 2') ownerRole2= models.CharField(max_length=100,null=True, blank=True, verbose_name='Owner Role 2') ownershipPercentage2= models.IntegerField(null=True, blank=True, verbose_name='Business Phone 2') and if pressed one more time the number changes to 3 and so on. Subsequently in needs to be updates in the form: class infoForm(ModelForm): class Meta: model = Info fields = ['ownerName1','ownerRole1','ownershipPercentage1'] Here is an example of the form: <div class="tab-pane fade" id="ownershipStructure" role="tabpanel" aria-labelledby="pills-3-tab"> <h2>Ownership Structure</h2> <div class="form-outline mb-4"> <input type="text" name="ownerName1" id="ownerName1" class="form-control" {% if form.is_bound %}value="{{ form.ownerName1.value }}"{% endif %}/> <label … -
Request from unknown party, Sogou
I am hosting a simple prototype on Amazon Lightsail and I saw some strange requests on my Django server. Is it anything to be concerned about? Invalid HTTP_HOST header: 'fuwu.sogou.com'. You may need to add 'fuwu.sogou.com' to ALLOWED_HOSTS. Invalid HTTP_HOST header: 'fuwu.sogou.com'. You may need to add 'fuwu.sogou.com' to ALLOWED_HOSTS. Bad Request: /http:/fuwu.sogou.com/404/index.html Bad Request: /http:/fuwu.sogou.com/404/index.html [01/Aug/2021 02:50:44] "GET http://fuwu.sogou.com/404/index.html HTTP/1.1" 400 63056 [01/Aug/2021 02:50:44] "GET http://fuwu.sogou.com/404/index.html HTTP/1.1" 400 63066 [01/Aug/2021 02:50:51] code 400, message Bad request syntax ('\x05\x01\x00') [01/Aug/2021 02:50:51] "" 400 - -
Connection refused when try convert html to pdf in AWS ubuntu, But works File in Local env
I am trying to convert HTML to pdf in a Django project it works fine on my local computer but when I uploaded it on my AWS ec2 instance it's giving me [Errno 111] Connection refused html_to_pdf function def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None Error in Django -
Django - Getting request instance in custom Template Backend
I've implemented a custom template backend (like django.template.backends.django.DjangoTemplates) where I need to determine a custom path for the template that needs to be used based on properties on the request object. That path is not/can't be added to TEMPLATES in settings.py in hard-coded manner, so it needs to be determined dynamically. Problem is that, I couldn't find a way to obtain the instance of request object within my class, it doesn't seem to be provided to the class at all. So I was wondering, whether this is even possible. I couldn't find anything in the docs. It's not possible or did I miss something? Thanks -
Nginx + uwsgi + Django + socket: web socket connection cannot be established
I am building a project that uses Nginx + uwsgi + Django. The project uses websocket. Everything works just fine when I run local tests, but things got out of hand when I am running it on a server. I am getting an error telling me that Websocket connection failed, and I am not receiving a status code. I suspect that the problem is not with my Django settings, but rather with the Nginx and uwsgi configuration. Nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { upstream django { server 127.0.0.1:8000; } server { listen 80; server_name 8.1**.1**.104; charset utf-8; location /static { alias /home/Pilot/main/static; } location / { uwsgi_pass 127.0.0.1:8000; include /etc/nginx/uwsgi_params; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } uwsgi.ini: [uwsgi] chdir =/home/Pilot module =Pilot.wsgi master =true processes =4 socket =127.0.0.1:8000 chmod-socket = 666 vacuum = true I thought I read something about Django that it uses asgi rather than … -
d3 voronoi from gejson
I've been trying to adapt a voronoi example code I found online,(originally works with an csv input) but I cant make it display on the map, and it doesn't report any error in the console, I'm generating a geojson with django, I'm not so versed in Javascript, so any help will be appreciated: this is what I have: showHide = function(selector) { d3.select(selector).select('.hide').on('click', function(){ d3.select(selector) .classed('visible', false) .classed('hidden', true); }); d3.select(selector).select('.show').on('click', function(){ d3.select(selector) .classed('visible', true) .classed('hidden', false); }); } voronoiMap = function(map, geoj) { var pointTypes = d3.map(), points = [], lastSelectedPoint; var voronoi = d3.geom.voronoi() .x(function(d) { return d.x; }) .y(function(d) { return d.y; }); var selectPoint = function() { d3.selectAll('.selected').classed('selected', false); var cell = d3.select(this), point = cell.datum(); lastSelectedPoint = point; cell.classed('selected', true); d3.select('#selected h1') .html('') .append('a') .text(point.properties.id) //.attr('href', point.properties) .attr('target', '_blank') } var drawPointTypeSelection = function() { showHide('#selections') labels = d3.select('#toggles').selectAll('input') .data(pointTypes.values()) .enter().append("label"); labels.append("input") .attr('type', 'checkbox') .property('checked', function(d) { return initialSelections === undefined }) .attr("value", function(d) { return d.type; }) .on("change", drawWithLoading); labels.append("span") .attr('class', 'key') .style('background-color', function(d) { return d.color; }); labels.append("span") .text(function(d) { return d.type; }); } var selectedTypes = function() { return d3.selectAll('#toggles input[type=checkbox]')[0].filter(function(elem) { return elem.checked; }).map(function(elem) { return elem.value; }) } var pointsFilteredToSelectedTypes … -
Kuberntes: Django + Gunicorn only / path working
I've been trying to deploy a Django project to EKS but I haven't been able to make it work. I installed ALB and I managed to get public access but now the only path working is / and everything else loads forever without giving an error. Here are my yamls: django-deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: django-app labels: app: django spec: replicas: 3 selector: matchLabels: app: django template: metadata: labels: app: django spec: containers: - name: django image: <image-uri> imagePullPolicy: Always ports: - containerPort: 8000 name: gunicorn django-service.yaml apiVersion: v1 kind: Service metadata: name: django-service annotations: service.beta.kubernetes.io/aws-load-balancer-type: external service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing spec: ports: - port: 80 targetPort: 8000 protocol: TCP type: LoadBalancer selector: app: django Things that I've tried: Using default load balancer vs Ingress with its own yaml Using Fargate nodes vs managed nodes Different Gunicorn configs (never got an error apart from timeouts) -
UTF-8 when running management commands from script
I am using this command to dump data py -Xutf8 manage.py dumpdata app.ModelName --indent 4 --format=json --output app/fixtures/data.json which works perfectly fine. However when I try to run the command in script management.call_command( "dumpdata", indent=4, format="json", output=os.path.join(path, "app//fixtures//data.json"), verbosity=1, ) It ends up with this error: django.core.management.base.CommandError: Unable to serialize database: 'charmap' codec can't encode characters in position 1-2: character maps to <undefined> I have tried something like this yet it still doesn't work. Any solutions to this? -
Getting mistake after creating success_url with CreateView class
Sorry for my bad English in advance. I'm trying to discover django, so I decided to write my own sign in/sign up views. So I just wrote something like that - class RegisterView(CreateView): template_name = 'auth/user_create_form.html' model = User fields = ['username', 'password', 'email'] So, it's basically working with GET requests. We can see the form on specified url. But after altering all fields and submitting form, I've got a mistake what suggested to specify get_absolute_url for model to redirect after submitting. So I decided to give success_url to RegisterView - class RegisterView(CreateView): template_name = 'auth/user_create_form.html' model = User fields = ['username', 'password', 'email'] success_url = reverse('words:main_page') And got a mistake Exception in thread django-main-thread: Traceback (most recent call last): File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/linuxbrew/.linuxbrew/opt/python@3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/home/linuxbrew/.linuxbrew/opt/python@3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/checks/urls.py", … -
Django/AWS EB: [app-deploy] - [RunAppDeployPreBuildHooks] error (no such file or directory), BUT the file does exist?
I have a Django application and I'm trying to deploy to my AWS EB Environment. It's a project that my friend and I are working on. I an trying to run the command eb deploy however though I get this: Alert: The platform version that your environment is using isn't recommended. There's a recommended version in the same platform branch. Creating application version archive "app-3d19-210731_133226". Uploading Prod Rest API/app-3d19-210731_133226.zip to S3. This may take a while. Upload Complete. 2021-07-31 17:32:29 INFO Environment update is starting. 2021-07-31 17:32:33 INFO Deploying new version to instance(s). 2021-07-31 17:32:36 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2021-07-31 17:32:39 ERROR [Instance: i-05761282d68083a51] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2021-07-31 17:32:39 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-07-31 17:32:39 ERROR Unsuccessful command execution on instance id(s) 'i-05761282d68083a51'. Aborting the operation. 2021-07-31 17:32:39 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. I checked the eb-engine.og and this is what I get: 2021/07/31 17:19:47.104584 [INFO] Executing instruction: StageApplication 2021/07/31 17:19:47.111204 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ 2021/07/31 17:19:47.111230 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/ 2021/07/31 … -
Django - setCustomValidity translation error
I need to translate error messages in setCustomValidity with Django i18n, but with code below it works only for the first input field. Something is messed with translation part. Could You take a look? enter code here <form action="" method="post" action=''> {% csrf_token %} <div class='message-area'> <div id='contact-form-name'> <input type='text' name='message-name' class='form-control' placeholder="{% trans 'Name' %}" required oninvalid='this.setCustomValidity("{% trans 'Fill in' %}")'> </div> <div id='contact-form-message'> <textarea type='text' name='message-message' id='form-control-message' placeholder="{% trans 'Message' %}" required oninvalid='this.setCustomValidity("{% trans "Fill in" %}")'></textarea> </div> <button id='search-button' type='submit'>{% trans 'Wyślij' %}</button> </div> </form> enter code here -
AttributeError: '_EnumDict' object has no attribute '_cls_name'
I have been receiving this error in several python based projects including my current one Shuup and i'm not sure how to resolve it. I have research other errors but none speak about this one. Any help to steer me in the right direction would be great. -
Django Http404 returns status=200
When my application raises Http404 the status-code returned is 200, which I find odd. It returns and renders my 404-template, so it should work, but the status-code is wrong. Please find the views and urls-file below: #views.py from django.http import Http404 def test_404_view(request): raise Http404 def error_404(request, exception): return render(request,"MyApp/404.html") #urls.py handler404 = 'myapp.views.error_404' . . -
How to resolve Server Error 500 on heroku
I am testing with django and created a simple app which would return some details about a given registration number. I compare those details with the lists of products i have in my shopify store and i would like to return filtered product which match the criteria. However Heroku serves with Server Error 500. I cant find anything wrong with the logs. 2021-07-31T20:43:09.115353+00:00 heroku[web.1]: Starting process with command `gunicorn APImat.wsgi --log-file -` 2021-07-31T20:43:11.691200+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-07-31T20:43:11.692898+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [4] [INFO] Listening at: http://0.0.0.0:51130 (4) 2021-07-31T20:43:11.693005+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [4] [INFO] Using worker: sync 2021-07-31T20:43:11.697003+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [7] [INFO] Booting worker with pid: 7 2021-07-31T20:43:11.759836+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [8] [INFO] Booting worker with pid: 8 2021-07-31T20:43:12.235949+00:00 heroku[web.1]: State changed from starting to up 2021-07-31T20:43:13.000000+00:00 app[api]: Build succeeded 2021-07-31T20:43:29.513759+00:00 app[web.1]: VOLKSWAGEN 2021-07-31T20:43:29.513867+00:00 app[web.1]: SHARAN SEL BLUE TECH TDI S-A 2021-07-31T20:43:29.513923+00:00 app[web.1]: 0 2021-07-31T20:43:29.911010+00:00 app[web.1]: 6682466025621 2021-07-31T20:43:30.272828+00:00 app[web.1]: 6714350698645 2021-07-31T20:43:30.613893+00:00 app[web.1]: 6720035750037 2021-07-31T20:43:30.987627+00:00 app[web.1]: 6734793212053 2021-07-31T20:43:31.383095+00:00 app[web.1]: 6793971859605 2021-07-31T20:43:31.671587+00:00 app[web.1]: 6973133750421 2021-07-31T20:43:31.917019+00:00 app[web.1]: 10.41.181.68 - - [31/Jul/2021:20:43:31 +0000] "GET /KM12AKK/ HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36" 2021-07-31T20:43:31.919827+00:00 heroku[router]: at=info method=GET … -
Django Bootstrap collapse list not working properly and expanding all items
I am using bootstrap collapse element in my template but the problem is when I click on any items its' expanding all items. When I am adding pk inside html elements then it's not expanding. here is my code: html: {% for i in contact%} <p> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse{{i.pk}}" aria-expanded="false" aria-controls="multiCollapseExample1{{i.pk}} multiCollapseExample2">Your Ticket Status</button> </p> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample1{{i.pk}}"> <div class="card card-body"> {{i.message}} my replay.{{i.id}} </div> </div> </div> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample2{{i.pk}}"> <div class="card card-body"> admin replay </div> <textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="write details about your project"></textarea><br> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </div> {%endfor%} models.py class Contact(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) parent =models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') #others fields -
HTML page loading a totally blank screen
<html lang="en"> <head> <title>Is it New Year's</title> </head> <body> {% if newyear %} <h1>YES</h1> {% else % } <h1>NO</h1> {% endif %} </body> </html> When I try running this HTML code I don't get an error but do get just a blank page when I should be getting either a yes or a no. Running this server using Django. -
502 Bad Gateway nginx/1.4.6 (Ubuntu)
I had website which is running using Django and it is working using nginx. I had tried to install SSL on the website, but it didn't succeed. But now when I try to access the website , it is giving me this error: 502 Bad Gateway nginx/1.4.6 (Ubuntu) What should I do ? thank you -
Django Authentication Classes via simple JWT apply locally to view but not on Elastic Beanstalk Production Server
I'm having trouble with some JWT authentication from the rest_framework_simplejwt package in relations to my django rest framework being deployed on Amazon Elastic Beanstalk in the Linux 2 Enviornment. This is what I have for my code: Technology Python 3.8 running on 64bit Amazon Linux 2/3.3.2 Relevant Pip Packages djangorestframework==3.12.4 djangorestframework-simplejwt==4.7.2 gunicorn==20.1.0 Views.py from django.shortcuts import render from rest_framework import generics from .serializers import ThingSerializer # Create your views here. from .models import Thing from rest_framework.permissions import IsAuthenticated class ThingView(generics.ListCreateAPIView): permission_classes = (IsAuthenticated,) queryset = Thing.objects.all() serializer_class = ThingSerializer settings.py INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'thing', 'rest_framework_simplejwt', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } urls.py from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt import views as jwt_views from . import views from files.views import ThingView urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), path('jwt/test/', ThingView.as_view(), name='other-view'), ] When I run it locally, it works properly all the views work and the view that requires authentication (the ThingView) is working properly. However when I deploy my backend to my Amazon Elastic … -
Save reversal relationship item in database using one POST - Django
I have these models, serializers, and views: Models: class Connection(models.Model): from portfolio.models import Portfolio user = models.ForeignKey(User, related_name='exchange_connections', on_delete=models.CASCADE) class ConnectionSettings(models.Model): exchange_connection = models.OneToOneField(Connection, to_field='id', primary_key=True, related_name='settings', on_delete=models.CASCADE) import_past_transactions = models.BooleanField(default=False, blank=True) class ConnectionCredentials(models.Model): exchange_connection = models.OneToOneField(Connection, to_field='id', primary_key=True, related_name='credentials', on_delete=models.CASCADE) key = models.CharField(max_length=300, blank=False, null=False) secret = models.CharField(max_length=300, blank=False, null=False) passphrase = models.CharField(max_length=300, blank=True, null=True) Serializers: class ConnectionCredentialsSerializer(FlexFieldsModelSerializer): class Meta: model = models.Connection fields = '__all__' class ConnectionSettings(FlexFieldsModelSerializer): class Meta: models = models.ConnectionSettings fields = '__all__' class ConnectionSerializer(serializers.ModelSerializer): portfolios = PortfolioSerializer(many=True) credentials = ConnectionCredentialsSerializer(many=False) settings = ConnectionSettings(many=False) class Meta: model = models.Connection exclude = ('user',) read_only_fields = ('date_created', 'last_updated') Views: class ConnectionViewSet(viewsets.ModelViewSet): serializer_class = serializers.ConnectionSerializer queryset = models.Connection.objects.all() permission_classes = (IsAuthenticated, core_permissions.IsMineOnly) def get_object(self): return self.request.user.connections_set def perform_create(self, serializer): serializer.save(user=self.request.user) GET request works great and I get all values from the OneToOne relationships. However, when I create a connection, I want to be able to create all the rows associated using one request. For example, passing all the data needed for the different models in one POST request. -
django enumerate a model's integer field when another model gets created
from django.db import models class Game(models.Model): description = models.TextField(max_length=8192) class GamePreview(models.Model): game = models.OneToOneField(Game, on_delete=models.CASCADE) comments = models.IntegerField(default=0) # Want to + 1 this when a comment gets created class GameComment(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) comment = models.CharField(max_length=512) @classmethod # does not work def create(cls, game): comment = cls(game=game) preview = GamePreview.objects.get(game=comment.game) preview.comments += 1 return preview Basically, I have a GamePreview model that has a IntgerField that should show the amount of comments, but I cannot figure out how I can do preview.comments += 1 when a GameComment gets created... -
for loop doesn't work in Django template (inside of table tag)
i'm trying to create a table inside of my html template, but when i write <td>{{project.title}}</td> it doesn't work! actually when i use {{x}} i have no output! i don't really know what's wrong inside of my template... html template: {% extends 'main.html' %} {% block content %} <h1>Projects</h1> <table> <tr> <th>ID</th> <th>Project</th> <th>Votes</th> <th>Ratio</th> <th></th> </tr> {% for project in Projects %} <tr> <td>{{project.id}}</td> <td>{{project.title}}</td> <td>{{project.vote_total}}</td> <td>{{project.vote_ratio}}</td> <td>{{project.created}}</td> <td><a href="{% url 'project' project.id %}">View</a></td> </tr> {% endfor %} </table> {% endblock content %} models.py: from django.db import models import uuid from django.db.models.deletion import CASCADE # Create your models here. class Project(models.Model): title = models.CharField(max_length=200) descripeion = models.TextField(null=True, blank=True) demo_link = models.CharField(max_length=1000, null=True, blank=True) source_link = models.CharField(max_length=1000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self) -> str: return self.title class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote') ) # owner = project = models.ForeignKey(Project, on_delete=CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self) -> str: return self.value class Tag(models.Model): name = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) id = … -
Django AllAuth and dj-rest-auth custom user settings after Sign Up
I am using django-allauth and dj-rest-auth in my DRF project for social authentication. I have managed to set up the social authentication process, but I want to have a post-configuration for the user after the sign up. I want to set things up like full_name, is_verified etc. For now I only have this view that makes the authentication possible class AzureLoginView(SocialLoginView): adapter_class = AzureOAuth2Adapter client_class = OAuth2Client callback_url = 'http://localhost/login/azure/' I have a view that set this things up for a normal registrations, but I'm not sure how to integrate it with social registration. class AccountViewSet(mixins.CreateModelMixin, GenericViewSet): serializer_class = EmailUserSerializer permission_classes = [AllowAny, ] def perform_create(self, serializer): fullname = "something" # set other user parameters