Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render table from from csv file into django templates?
I have a problem with rendering table in django templates with data form csv file. I'm reading data from file: with open('data/file.csv', encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) and rendering the template: return render(request, 'search/search.html', {'data': reader}) and in the template: <table> <thead> <tr> <th>...</th> </tr> </thead> <tbody> <tr> {% for row in data %} <td>{{row}}</td> {% endfor %} </tr> </tbody> and I have error operation on closed file Firstly I thought about using pandas but in Django it gave me circular import :/ Could anyone let me know how can I fix it? -
Running multiple threading process in background using django / python parallel or async to each other
I'm currently building a modbus data scrapper tool in which i want it to get data from device continuously and parallel to each other. Here's the example code that i'm working with def get_data(self): connection_port = len(connection_ports) connection_count = 0 while connection_count != connection_port: timestamp = datetime.datetime.now() print('Timestamp: ', timestamp) client = ModbusTcpClient(connection_ports[connection_count][0], port=connection_ports[connection_count][1]) # Specify the port. connection = client.connect() count = 0 data_info = [] data_object = [] limit = len(registers) loop = 0 if connection: while loop < limit: if count == limit - 1: break address = registers[count] response = client.read_holding_registers(address, count=10, unit=connection_ports[connection_count][2]) try: register_value = response.registers[0] bin8 = lambda x: ''.join(reversed([str((x >> i) & 1) for i in range(12)])) modbus_value = register_value / scaling[count] timestamp = datetime.datetime.now() if count == limit: count = 0 else: count = count + 1 data_object.append(registers[count]) data_info.append(round(modbus_value, 2)) csv_name = str(connection_ports[connection_count][0]) + "-Slave-" + str( connection_ports[connection_count][2]) + ".csv" with open(csv_name, 'a+', newline='') as f: driver_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) driver_writer.writerow([label[count], str(address), round(modbus_value, 2), timestamp]) except Exception: print("Unable to Get Data from Device, Please Check Device Connection") exit # self.writeGui(data_object, data_info) else: print('unable to connect to device') connection_count = connection_count + 1 client.close() What i'm currently doing in this code … -
Fetch and return one field from database using django_restframework
So I have been trying to make an API with Django rest_framework that will return only 1 field from a table. I have been trying to follow the example from Django Rest Framework: Dynamically return subset of fields, but have been unable to recreate it. whenever I write "http://localhost:8000/api/students/fields=id/", I get a 404 error with "details": "not found" I have also been experimenting with adding an extra method in the view class, like in this example: @action(methods=['get'], detail=False) def newest(self, request): newest = self.get_queryset().order_by('created_at').last() serializer = self.get_serializer_class()(newest) return Response(serializer.data) with something like "get_id_list" instead, but I haven't quite figured it out. Also, does anyone know if these methods will first retrieve all fields from the database, and then filter out what it needs, or will the query adjust to only ask for the specified fields? The tables can get quite large, so it might save a lot of time if it doesn't fetch unnecessary data. Here is the code in serializer.py from rest_framework.serializers import ModelSerializer from .models import Student, Coverage class DynamicFieldsModelSerializer(ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up … -
python django Mock SAML Response from onelogin.saml.auth library using python3-saml
I have implemented for our django back-end application (SP) possibility to login via SAML, as IDP im using Keycloak. It works fine, but I want to write tests to be sure that all logic is being executed correctly. For this I want to generate a post request with SAML as body and mock (unittest.mock.patch) the real request. But i stuck. Here is my django view, which accepts get and post requests when I try to login via SAML: class SamlLoginView(View): @staticmethod def prepare_django_request(request): if 'HTTP_X_FORWARDED_FOR' in request.META: server_port = 443 else: server_port = request.META.get('SERVER_PORT') result = { 'https': 'on' if request.is_secure() else 'off', 'http_host': request.META['HTTP_HOST'], 'script_name': request.META['PATH_INFO'], 'server_port': server_port, 'get_data': request.GET.copy(), 'post_data': request.POST.copy(), } return result @never_cache def get(self, *args, **kwargs): req = SamlLoginView.prepare_django_request(self.request) auth = OneLogin_Saml2_Auth(req, settings.SAML_IDP_SETTINGS) return_url = self.request.GET.get('next') or settings.LOGIN_REDIRECT_URL return HttpResponseRedirect(auth.login(return_to=return_url)) @never_cache def post(self, *args, **kwargs): req = SamlLoginView.prepare_django_request(self.request) print(req['post_data']['SAMLResponse']) auth = OneLogin_Saml2_Auth(req, settings.SAML_IDP_SETTINGS) auth.process_response() errors = auth.get_errors() if not errors: if auth.is_authenticated(): logger.info("Login", extra={'action': 'login', 'userid': auth.get_nameid()}) user = authenticate(request=self.request, saml_authentication=auth) login(self.request, user) return HttpResponseRedirect("/") else: raise PermissionDenied() else: return HttpResponseBadRequest("Error when processing SAML Response: %s" % (', '.join(errors))) In my tests, I wanted to directly call the post method, in which there will be … -
IntegrityError at /new_food/(?P6\d+)/ : NOT NULL constraint failed: food_entry.refer_id
views.py : def new_entry(request, food_id): food=Food.objects.get(id=food_id) if request.method != 'POST': form=EntryForm() else: form=EntryForm(data=request.POST) if form.is_valid(): new_entry=form.save(commit=False) new_entry.food=food new_entry.save() return HttpResponseRedirect(reverse('food',args=[food_id])) context={'food':food,'form':form} return render(request,'new_entry.html',context) forms.py : from django import forms from .models import Food , Entry class FoodForm(forms.ModelForm): class Meta: model= Food fields= ['name'] labels= {'text':''} class EntryForm(forms.ModelForm): class Meta: model=Entry fields=['item'] labels={'text':''} models.py from django.db import models # Create your models here. class Food(models.Model): name=models.CharField(max_length=200) type=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Entry(models.Model): refer=models.ForeignKey(Food,on_delete=models.CASCADE) item=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural='entries' def __str__(self): return self.item[:50] Even after going through a lot of similar posts , I'm not being able to figure to out where is it going wrong , may be something is wrong in views.py but even after spending hours I'm not able to figure it out. Any help would be much appreciated . -
while deploying project getting error : cannot stat '/tmp/build_d2196d1a_/requirements.txt': No such file or directory?
I'm using python django with pipenv environment project hierarchy structure I have created a project, i pushed it to github successfully. When i deploy it to heroku the build completed successfully but while building it shows ----> Requirements file has been changed, clearing cached dependencies cp: cannot stat '/tmp/build_d2196d1a_/requirements.txt': No such file or directory heroku build log because of which i think packages are also not installed listed in requrements.txt and i'm getting application error while viewing application how can i solve this? -
Django cookie banner / consent
regarding cookies in django, is there any solution for the banner/consent, is there someone who can help me with the code or report me a secure package? thanks in advance thanks in advance -
Social network models architecture
I want to create the social network that should work as Reddit, but idk how to implement one thing. I did Communities model(subreddits) and also did Posts model. And it works fine, but i want to add the feature that will let you to create posts not only for one of the communities, but also for your profile, I mean that Here is my models models.py class Community(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, null=True, blank=True) description = models.TextField(max_length=500) cover = models.ImageField(upload_to='c_covers/', blank=True, null=True) admins = models.ManyToManyField(User, related_name='inspected_c') subscribers = models.ManyToManyField(User, related_name='subscribed_c') banned_users = models.ManyToManyField(User, related_name='forbidden_c') created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, null=True, blank=True) body = models.TextField(max_length=5000, blank=True, null=True) photo = models.ImageField(upload_to='post_photos/', verbose_name=u"Add image (optional)", blank=True, null=True) author = models.ForeignKey(User, related_name='posted_p', on_delete=models.CASCADE) community = models.ForeignKey(Community, related_name='submitted_p', on_delete=models.CASCADE) points = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='liked_p', blank=True) mentioned = models.ManyToManyField(User, related_name='m_in_posts', blank=True) rank_score = models.FloatField(default=0.0) active = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) -
Reverse for 'vote' with arguments '('', '')' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
I've been working with Django doc and ther is this code which works: <body> <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> <--------- {% for choice in question.choice_set.all %} <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"><br> {% endfor %} <input type="submit" value="Vote"> </form> </body> Django code: class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) Now, i am trying to make this code working in DRF, but it gives me an error. Here i found the code Here is code of drf: class DetailViewDRF(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'polls/detail.html' def get(self,request, pk): queryset = get_detail_queryset() return Response({'question': queryset}) Am i missing something vital in documentation? P.S. Why it suggests me to make get method static? -
Django Rest Framework Testing - OrderedDict instead of a number Error
So, I'm building an API with Django and rest-framework and when I try to send a post test request it keep getting this error where it's expecting a number but got a OrderedDict, if someone could help me it would be great. test_api.py def setUp(self): self.client = APIClient() self.sensor = Sensor(54545) self.sensor.save() self.company = Company(name='MOCK') self.company.save() def test_create_valid_user_success(self): """Test creating a user with valid payload is successful""" payload = { 'email': 'test@gmail.com', 'password': 'pass123', 'name': 'Test', 'registration': 144545, 'sensor': { 'id': 455465, 'battery': 100 }, 'company': self.company.id } res = self.client.post(CREATE_USER_URL, payload, format='json') self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload['password'])) self.assertNotIn('password', res.data) self.assertNotIn('id', res.data) *already tried json.dumps(payload), content_type='application/json' for the post serializers.py class SensorSerializer(serializers.ModelSerializer): class Meta: model = Sensor fields = ('id', 'battery',) class UserSerializer(serializers.ModelSerializer): """Serializer for the user object""" sensor = SensorSerializer() class Meta: model = get_user_model() fields = ( 'email', 'password', 'name', 'registration', 'sensor', 'company', ) extra_kwargs = { 'password': {'write_only': True, 'min_length': 5}, 'id': {'write_only': True} } def create(self, validated_data): """Create a new user with encrypt password and return it""" sensor_data = validated_data.pop('sensor') sensor = SensorSerializer.create(SensorSerializer(), validated_data=sensor_data) return get_user_model().objects.create_user(sensor=sensor, **validated_data) views.py class CreateUserView(generics.CreateAPIView): """Create a new user in the system view""" serializer_class = UserSerializer Error: TypeError: Field 'id' … -
Slow Serializion process Django rest framework
Im using django_rest_framework for my project and i have a problem. models.py: from django.db import models class RelatedField3_2(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class RelatedField3(models.Model): name = models.CharField(max_length=100) relfield3_2 = models.ForeignKey(RelatedField3_2, on_delete=models.CASCADE) def __str__(self): return self.name class RelatedField2(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class RelatedField1(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class MainTable(models.Model): owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) field1 = models.IntegerField() field2 = models.IntegerField() field3 = models.IntegerField() field4 = models.DecimalField(max_digits=10, decimal_places=1) field5 = models.IntegerField(null=True) field6 = models.IntegerField() relfield1 = models.ForeignKey(RelatedField1, on_delete=models.CASCADE) relfield2 = models.ForeignKey(RelatedField2, on_delete=models.CASCADE) relfield3 = models.ForeignKey(RelatedField3, on_delete=models.CASCADE) serializers.py: from rest_framework import serializers from main.models import MainTable, RelatedField1, RelatedField2, RelatedField3 class MainTableRelatedFields(serializers.RelatedField): def display_value(self, instance): return instance def to_representation(self, value): return str(value) def to_internal_value(self, data): return self.queryset.model.objects.get(name=data) class MainTableSerializerList(serializers.ListSerializer): def create(self, validated_data): records = [MainTable(**item) for item in validated_data] return self.child.Meta.model.objects.bulk_create(records) class MainTableSerializer(serializers.ModelSerializer): class Meta: model = MainTable list_serializer_class = MainTableSerializerList id = serializers.IntegerField(write_only=False, required=False) owner = serializers.ReadOnlyField(source='owner.username') relfield3 = PartnerPropRelatedFields(queryset=RelatedField3.objects.all()) relfield2 = PartnerPropRelatedFields(queryset=RelatedField2.objects.all()) relfield1 = PartnerPropRelatedFields(queryset=RelatedField1.objects.all()) def create(self, validated_data): return self.Meta.model.objects.create(**validated_data) views.py: from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from .serializers import MainTableSerializer class MainTableUploadView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) @action(['post'], detail=False) def upload_records(self, request, *args, **kwargs): … -
Django + Apache + Windows Server 2016, mod_wsgi unable to run wsgi.py file
I am trying to deploy a django project on a windows machine using Apache 24. Apache works. But the log file shows that mod_Wsgi is stuck while reading the wsgi.py file without throwing any error: Here is the last entry in my log file: [Thu Sep 03 14:13:33.708094 2020] [wsgi:info] [pid 17684:tid 908] [client ::1:53338] mod_wsgi (pid=17684, process='', application='l'): Loading Python script file 'C:/.../wsgi.py'. And the webpage keeps loading till infinity. Following is what I am using in my httpd.conf file: LoadFile "c:/python37/python37.dll" LoadModule wsgi_module "c:/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/python37" WSGIScriptAlias / "C:/...../wsgi.py" <Directory "C:/...../"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/.../static/" <Directory "C:/..../static/"> Require all granted </Directory> No changes in the httpd-vhost.conf file. I am frustrated with the issue and have tried a lot of tweaks, but the webpage just wont load. Also, my Apache Debug level is 'debug'. What am I missing? -
Django - Use foreign keys as choices for choice-field
Suppose I have the following models (Does not really matter, any model whatsoever will do) class Model0(models.Model): pass class Model1(models.Model): pass How can I pass them as choices to another Model, something like this: class Model3(models.Model): CHOICES = [ (models.ForeignKey(Model0,related_name='model_0',on_delete=models.CASCADE),'model0'), (models.ForeignKey(comment,related_name='model_1',on_delete=models.CASCADE),'model1'), ] choice_collumn = models.ForeignKey(choices=REPORT_TYPES) #it actually has a choices keyword argument The idea is that it will either have a Foreign key relationship to Model 0 or to Model 1. The way I am dealing with this is by setting one of them to null model_0_relationship = models.ForeignKey(Model0,null=True) model_1_relationship = models.ForeignKey(Model1,null=True) But what if I have way more than 2? is there a better solution? -
Use 2 pk instead of 1 in Django rest framework DELETE method
I want to delete an object that is related to a different model. Basically i need to send DELETE request to a url with 2 pks i guess, since it's impossible to send a DELETE request with additional data as body. Basically models look something like this: class Product(models.Model): name = models.CharField() class Person(models.Model): name= models.CharField() class ProductOrder(models.Model): product = models.ForeignKey(Product) person = models.ForeignKey(Person) I want to configure the DELETE method on ProductOrder, that I when i send my request to : http://127.0.0.1:8000/productorders/2/67/ It will find a Person with ID=2 , and delete a ProductOrder that is related to this person and it's related to a Product with ID=67. How can i combat this problem ? -
How to run Django docker image with server? [closed]
I have a Django docker image which is to be run on gpu and on Django's server. When I go inside the image and try to run the '''python3 manage.py runserver''' commmand it can't access the web. Please anyone could could help running the django server from docker and using GPU. -
How to Print data in django view file?
i am Selecting data using djano query.i am using following query def myfunction(request): mydata=MyModel.objects.all() #this is query return HttpResponse (mydata) # i am using this for printing data its showing me result in below formet, MyModel object(28) MyModel object(29) MyModel object(30) i want to print the data which is inside the object.How to do that? -
Django next url to HTTPS (Nginx)
I have added a SSL certificate to my nginx application, everything works fine, but when django paginates for the next url it uses: http:// not https:// How can I change this? -
Error : subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method... in Django date filtering
I'm using Django 2.2.12. In models.py, I have a model of name Webregister having field created_on = models.DateTimeField(null=True, blank=True) that returns data in the format 2020-09-04 22:17:00+00:00 Inorder to filter the date, I wrote this query Webregister.objects.filter(created_on__date=date.today()) and it returns the following error, NotImplementedError: subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method However, it's working fine If I use __year and hit the following query, Webregister.objects.filter(created_on__year="2020") PLease let me know what's the issue ? -
coming across with Cors issue after logged in
here is my axios get request async getIpAddress ({commit}) { const { data: { ip } } = await axios.get("https://www.cloudflare.com/cdn-cgi/trace", {responseType: "text", transformResponse: data => Object.fromEntries(data.trim().split("\n").map(line => line.split("="))) }); console.log(ip); commit('setIp', ip) if request.user.is_anonymous: working fine smoothly console.log is [HMR] Waiting for update signal from WDS... client-entry.js?d267:36 [Quasar] Running SPA. auth.js?e140:216 84.54.84.225 client?db9c:48 [WDS] Hot Module Replacement enabled. client?db9c:52 [WDS] Live Reloading enabled. backend.js:2237 vue-devtools Detected Vue v2.6.11 but after logged in I start struggling with cors Access to XMLHttpRequest at 'https://www.cloudflare.com/cdn-cgi/trace' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. xhr.js?e38e:160 GET https://www.cloudflare.com/cdn-cgi/trace net::ERR_FAILED please help me out -
Django user model - is it possible to build different profile?
I'm beginning with Django. I'm using a classical user system of Django (django user model). I did not use AbstractUser. I probably made a mistake. So each user of my website has a profile: class Functionfeedcool(models.TextChoices): COOKER = 'Cooker' SUPERCOOKER = 'Super cooker' DEV = 'Dev' CEO = 'CEO' class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) ... functionfc = models.CharField(max_length=20,choices=Functionfeedcool.choices,default=Functionfeedcool.COOKER,) ... Is it possible to use one other Profile only dedicated to Supercooker user? I'm using the same dashboard for each user. What kind of code I can use to complete this profile form for supercooker? Assume I don't want Cooker, Dev and Ceo have access to this form. if it's not possible, which I hope not. what is the quickest way to replace Django User Model to AbstractUser? -
Raw Query representation In Django ORM
I have two table state , vote class State(models.Model): state_name = models.CharField(max_length=255,blank=True) value = models.IntegerField() code = models.CharField(max_length=255,blank=True) class Votes(models.Model): user = models.ForeignKey(Registeruser, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) I want to convert my raw sql into Django ORM form '''' SELECT SUM(account_state.value) FROM account_votes INNER JOIN account_state ON account_state.id = account_votes.state_id where user_id ="%s" and candidate_id="%s";', [user_id,candidate]) ''' into a Django ORM form like Votes.object.select_related(state) kind of like that.. Please help me with that.. Im stuck.. Thanks in advance -
Django search lookup score
How can I get the score when using search lookup? Suppose you have the search shown in the documentation: >>>Entry.objects.filter(body_text__search='Cheese') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>] It results in two documents that must be sorted by some kind of numerical score. How to know the resulted score? -
How to import a model to a file in Django
I have the following structure of the project: manuals_project - bedienungsanleitung - migrations - admin.py - apps.py - models.py - urls.py - views.py - modules - save_to.py I have folder modules. And I have file save_to.py I need to import a model from bedienungsanleitung app. But when I try to do it, it gives an error No module named 'manuals_project.bedienungsanleitung' I try to do it the following way: from manuals_project.bedienungsanleitung.models import Link What is the mistake? Can someone help me? -
Django app running on 8000 cant be reached from windows
I am running a django app on 0.0.0.0:8000 on ec2. I can access this app using wget, but the same url does not work form windows. In my Security group i have added a rule t allow port range 8000 from source 0.0.0.0/0. Here is the wget response. Most certainly a config issue. Any AWS EC2 experts there? Thanks in advance ubuntu@ip-172-31-15-59:~$ wget 13.232.233.180:8000/events --2020-09-03 11:05:24-- http://13.232.233.180:8000/events Connecting to 13.232.233.180:8000... ^C ubuntu@ip-172-31-15-59:~$ wget http://ubuntu@ec2-13-232-233-180.ap-south-1.compute.amazonaws.com:8000/events --2020-09-03 11:07:03-- http://ubuntu@ec2-13-232-233-180.ap-south-1.compute.amazonaws.com:8000/events Resolving ec2-13-232-233-180.ap-south-1.compute.amazonaws.com (ec2-13-232-233-180.ap-south-1.compute.amazonaws.com)... 172.31.15.59 Connecting to ec2-13-232-233-180.ap-south-1.compute.amazonaws.com (ec2-13-232-233-180.ap-south-1.compute.amazonaws.com)|172.31.15.59|:8000... connected. HTTP request sent, awaiting response... 301 Moved Permanently Location: /events/ [following] --2020-09-03 11:07:03-- http://ubuntu@ec2-13-232-233-180.ap-south-1.compute.amazonaws.com:8000/events/ Reusing existing connection to ec2-13-232-233-180.ap-south-1.compute.amazonaws.com:8000. HTTP request sent, awaiting response... 200 OK Length: 2319 (2.3K) [text/html] Saving to: ‘events’ events 100%[==========================================================================>] 2.26K --.-KB/s in 0s 2020-09-03 11:07:03 (47.1 MB/s) - ‘events’ saved [2319/2319] -
How do I get an access token with a credential_id/token_id?
I have made a Django website using Google APIs. I was testing it and I logged in using Google, after that, a table called : "gfgauth_credentialsmodel" was created in my DB, it has a column called : "credentials", which is a large number. How do I get an access token using this credential_id?