Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I search my entire Users model for users that already have the requested email/phone?
I am new to rest framework, so forgive me if this is an obvious answer. I am using serializers with querysets in my views. The whole thing is locked down with JWT auth from Firebase What is the best way to search my database for a user that has a certain email or phone and return a JSON response of True or False depending on if that email / phone already exists in the database? What I have tried so far... class getuserid(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = GetUserIdSerializer lookup_field = 'phone' class GetUserIdSerializer(serializers.ModelSerializer): class Meta: model=UserProfile fields=['user'] The problem with this method is if I use a JWT that is not associated with the user who has that phone number in their database model, I get a invalid token error/forbidden. Obviously this is not a very secure way to do it, anyways, even if rest framework allowed me to. Here is the serializer where I create my user's profile in my database... class UserProfileSerializer(serializers.ModelSerializer): class Meta: model=UserProfile fields=['company','email','name','phone','image','account_type','password','sub_user_of','sub_pending','products_read','products_write','restock_read','restock_write','expenses_read','expenses_write','banking_read','banking_write','admins'] class UserSerializer(serializers.ModelSerializer): userprofile = UserProfileSerializer() def update(self, instance,validated_data): if(not instance.username == self.context['request'].user.username): raise exceptions.PermissionDenied('You do not have permission to update') profile_data = validated_data.pop('userprofile') if(not hasattr(instance,'userprofile')): instance.userprofile = UserProfile.objects.create(user=instance,**profile_data) else: instance.userprofile.company = … -
How to use axios to consume API Rest en Django specifically the list method in Model ViewSet?
Cheers, I'm trying do a request from Vue.js through axios to Django but the console show a error in the acccess to XMLHttpRequest. This is the error: enter image description here My code in Vue.js is the following: <template> <div class="main_container_cita"> <div class="panelIzquierdoCita"> <div class="panelVerticalCita"> <img src="../img/cita.png" alt=""> <h1>Mis citas</h1> </div> </div> <div class="panelDerechoCita" id="panelDerechoCita"> <table> <tr> <td>Fecha</td> <td>Hora</td> <td>Lugar</td> <td>Cliente</td> <td>Servicio</td> </tr> <tr v-for="(cita, index) in citas" :key="index"> <td v-text="cita.fecha"></td> <td v-text="cita.hora"></td> <td v-text="cita.lugar"></td> <td v-text="cita.cliente"></td> <td v-text="cita.servicio"></td> </tr> </table> </div> </div> </template> <script> import axios from "../utils/axios"; export default { name: "Cita", data: function () { return { citas: [] } }, methods: { getCita: async function(){ await this.verifyToken(); let token = localStorage.getItem("token_access"); axios.get(`cita`, {headers: {"Authorization": `Bearer ${token}`}}) .then(result => { this.citas = result.data }).cath((error)=>{ alert('Erorr en el get',error) }) }, verifyToken: function(){ let refresh = localStorage.getItem("token_refresh");//recuperar datos del LocalStorage return axios.post("refresh/", {refresh}) .then(result => { localStorage.setItem("token_access", result.data.access) }).catch(()=>{ this.$emit("logout"); }) } }, mounted(){ this.getCita(); } }; </script> Finally my code in Django is the following: class CitaView(viewsets.ModelViewSet): serializer_class = CitaSerializer queryset = Cita.objects.all() permission_classes = (IsAuthenticated,) def list(self, request): serializer = CitaSerializer(self.queryset.order_by("fecha").filter(cliente=1), many=True) return Response({'data': serializer.data}) I'll hope answers, I need to complete a project. -
Block Dates in Django Datepicker
I am using fengyuanchen's datepicker and am trying to create an array of dates from my Django model and filter (or block) the dates from the array out of the datepicker widget. I have a solid python background, but my JS knowledge is minimal, so I am hoping I can get some guidance on how to pass this data correctly. <head> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <!-- Fengyuan Chen's Datepicker --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.css" integrity="sha256-b88RdwbRJEzRx95nCuuva+hO5ExvXXnpX+78h8DjyOE=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.js" integrity="sha256-/7FLTdzP6CfC1VBAj/rsp3Rinuuu9leMRGd354hvk0k=" crossorigin="anonymous"></script> </head> <script> var array = [ {% for x in listing_reservations %} {{ x.start_date }} {% endfor %} ] $(function () { $("#id_start_date").datepicker({ filter: function(date) { if (array) { return false; } } }); }); </script> -
Redirection in PyTest Django doesn't work
I am trying to create tests for my login and signup process in my Django App with Pytest. When you signup ("/signup", home/register.html) you should be redirected to login page ("/login", home/login.html). After successfull login you shoul be redirected do welcome page ("", home/welcome.html). I created 2 tests for signup and it works. Unfortunetly I have problem with login and checking redirection to welcome page. Here is my test: @pytest.mark.django_db def test_login_redirect_to_welcome_for_authenticated_user(client): user = User.objects.create_user('Test', 'test@test.pl', 'password') client.login(username=user.username, password='password') response = client.get(path='/login', follow = True) assert response.status_code == 200 assert 'home/welcome.html' in response.template_name I logged the user on login page, set follow to true. And now I want to check if I am redirected to Welcome Page. Unfortunetly I have got this error: client = <django.test.client.Client object at 0x1030db460> @pytest.mark.django_db def test_login_redirect_to_welcome_for_authenticated_user(client): user = User.objects.create_user('Test', 'test@test.pl', 'password') client.login(username=user.username, password='password') response = client.get(path='/login', follow = True) assert response.status_code == 200 > assert 'home/welcome.html' in response.template_name E assert 'home/welcome.html' in ['home/login.html'] E + where ['home/login.html'] = <TemplateResponse status_code=200, "text/html; charset=utf-8">.template_name home/tests/test_login.py:18: AssertionError FAILED home/tests/test_login.py::test_login_redirect_to_welcome_for_authenticated_user - assert 'home/welcome.html' in ['home/login.html'] Do you know how I can fix this? -
Django, Mock keeps only last call args to itself
Using Django==3.2.15, mock==3.0.5, Python ~3.7 I have been noticing that the mock does not keep all the call_args from the different calls made to it, and they are all with the signature of the last call made to it. My code: This is a snippet that resembles where the service mock will be called, downstream. object_ids is a list of integer object IDs, I am sending to the service to handle. max_allotted_size is an integer, stands for the "chunks" I want to divide the service interaction. message_body is defined before the loop and contains other information the service requires from location.of.service import MyService my_service = MyService() num_iterations, leftover = divmod(len(object_ids), max_allotted_size) log_ids = [] for i in range(num_iterations): message_body['object_ids'] = object_ids[prev:curr] print( "iteration: {}, IDS count: {}, IDS: {}".format( i, len(object_ids[prev:curr]), object_ids[prev:curr], ) ) _, error = my_service.send_payload_to_some_other_service(message_body) if not error: log_ids += object_ids[prev:curr] prev = curr curr += max_allotted_size There is also code that picks up the leftover: if leftover: message_body['object_ids'] = object_ids[prev:] print( "leftover IDS count: {}, IDS: {}".format( len(object_ids[prev:]), object_ids[prev:], ) ) _, error = my_service.send_payload_to_some_other_service(message_body) if not error: log_ids += object_ids[prev:] There is also a print at the end to show the log_ids gathered with each … -
django ORM left join unrelated QuerySet
Here below is very simplified example of what I want to do with django ORM. Please do not concentrate on how to make models better (I try to make it simple and illustrative) but how to get data from presented situation. So, lets assume two models. First class Car(models.Model): brand = models.TextField() model = models.TextField() segment = models.TextField() stores all cars from dealer parking (different brand and segment). From time to time dealer make some special offer for car from given segment which are store in second table class Discount: car_segment = models.TextField() price_cut = models.IntegerField() Now we want to show all cars from brand selected by the user sorted by discount. Note that most of the cars have regular price (no price_cut, no "corresponding" entry in Discount table. In plane SQL this what I want to achieve is sth like: select * from (select * from Car where brand = "Toyota") left join Discount on segment=car_segment order by price_cut, segment; How to do this using django ORM? For example we have Car: brand model segment toyota aygo A toyota yaris B toyota corolla C toyota raw4 4x4 kia picanto A kia rio C and discounts car_segment price_cut A 1000 … -
Login in django failing after adding css to login page
I have a basic django website running on a postgres database. The login page code was structured as follows, {% extends "_base.html" %} {% load crispy_forms_tags %} {% block title %}Log In{% endblock title %} {% block content %} <h2>Log In</h2> <div class="container text-center"> <div class="row justify-content-center"> <div class="col-4"> <form method="post"> {% csrf_token %} {{ form | crispy }} <button class="btn btn-primary " type="submit">Log In</button> </form> </div> </div> </div> {% endblock content %} and _base.html as <!-- additional css content for navbar --> <div class="container-fluid full-height p-0"> {% block content %} {% endblock content %} <!-- similar footer content --> And then I decided to add some css from the bootstrap in the form of a just so my login page would look cleaner. Therefore I added some css in this form. {% extends "_base.html" %} {% load crispy_forms_tags %} {% block title %}Log In{% endblock title %} {% block content %} <div class="bg-dark vh-100 d-flex align-items-center justify-content-center"> <div class="col-3 p-5 border bg-light rounded-2"> <h2>Log In</h2> <form method=" post"> {% csrf_token %} {{ form | crispy }} <button class="btn btn-primary " type="submit">Log In</button> </form> </div> </div> {% endblock content %} with _base.html as follows <div class="container-fluid p-0"> {% block content … -
http://127.0.0.1:8000/admin/ not connected
I defined a function and when I use schedule, I don't have access to the admin page and other pages through http://127.0.0.1:8000/admin/. I have a blank page.But my program works properly and i try on localhost my code: def search(): . . . schedule.every(1).minutes.do(search) while True: schedule.run_pending() time.sleep(1) -
Django Raw SQL Query using multiple databases
I am trying to pull information from 2 different databases in the same query. Below is an example of the code I'm trying to use with identifying information changed to generic names. I have my data bases set up in settings like this: DATABASES = { 'default': {}, 'primary': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'oracle.test.com:5432/erp', 'USER':'test1', 'PASSWORD':'', }, 'secondary': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'oracle2.test.com:5432/wms', 'USER':'test2', 'PASSWORD':'', }, } Then in my views I have this: def index(request): sql_query = ('select \n' ' primary.table1.organization_id "Org", \n' ' primary.table2.LOCATION "Loc", \n' ' primary.table3.inventory "Inv", \n' ' primary.table4.reorder_date "Reorder", \n' ' secondary.table3.COMMENTS "Comments", \n' 'from \n' ' primary.table2, primary.table1\n' ' LEFT OUTER JOIN primary.table3 On\n' ' (primary.table1.SCHEDULE_NUMBER = primary.table3.SCHEDULE_NUMBER) \n' ' LEFT OUTER JOIN primary.table4 On \n' ' (primary.table1.SCHEDULE_NUMBER = primary.table4.PARENT_SCHEDULE_NUMBER) \n' ' LEFT OUTER JOIN secondary.table1 On \n' ' (primary.table1.SCHEDULE_NUMBER = primary.table1.SCHEDULE_NUMBER) \n' 'where 'primary.table1.item_id = primary.table2.inventory_item and \n' 'primary.table1.organization_id = primary.table2.organization_id \n') with connections['primary', 'secondary'].cursor() as cursor: cursor.execute(sql_query) field_names = [tuple(x[0] for x in cursor.description)] row = cursor.fetchall() result = field_names + row df = pd.DataFrame(result) df.rename(columns=df.iloc[0], inplace=True) df.drop([0], inplace=True) table = df.to_html(index=False, classes='mystyle', justify='left') return render(request, 'template.html', {'table': table}) I thought this would work because the syntax I found online for … -
Django raise ValueError( ValueError: Cannot assign "1": "Order.variation" must be a "ProductVariation" instance
Im trying to create a Orderobject but I get this error, and I dont know how to fix variation_obj = ProductVariation.objects.get(id=int(variation_id_list[index])) quantity = variation_quantity_list[index] total = variation_total_list[index] total = float(total) order_object = Order(user=request.user, variation=variation_obj.id, quantity=quantity, total=total) error: Django raise ValueError( ValueError: Cannot assign "1": "Order.variation" must be a "ProductVariation" instance. models.py class Order(models.Model): variation = models.ForeignKey(ProductVariation, on_delete=models.DO_NOTHING) created_at = models.DateField(auto_now_add=True) uploaded_at = models.DateField(auto_now=True) quantity = models.IntegerField() total = models.FloatField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
Django + Python Reference related data from Q Object
I have two models and a Q object. How can I retrieve the related data (the field called GROUP) and add it into my serialized result set shown below? Thank you in advance! Model A class WaiverAdult(models.Model): first_name = models.CharField(max_length=50) middle_initial = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) Model B class CheckIns(models.Model): adult = models.ForeignKey( WaiverAdult, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin') checkin = models.DateTimeField(blank=True, null=True) checkout = models.DateTimeField(blank=True, null=True) group = models.IntegerField(blank=True, null=True) Query group_adults = serializers.serialize('jsonl', WaiverAdult.objects.filter( Q(adult_checkin__checkin__gte=today()) & Q(adult_checkin__group__exact=group)), fields=('first_name', 'last_name')) -
Filter with order for two fields
I have Model Klass with fields like this: date_start = models.DateField(null=True, blank=True, default=date.today) date_finish = models.DateField(null=True, blank=True) As you see, date_start will be usually filled but date_finish may not. If neither one is filled we should not consider this record in further filtering. I would like to see objects (first N results) ordered by latest date regardless if that's date_start or date_finish. To be exact: considered date shall be date_finish if exists, date_start otherwise. Please note, that I don't want N/2 finished items and N/2 only started items concatenated but recent N "touched" ones. My first idea is to provide this extra field of considered_date that would be filled as I proposed but I don't know how to implement this. Shall it be done: on Model level, so new DateField to be added and have it's content always filled with sth selected for 2 seperate conditions (N elements each), then provided with temporary extra field (but without saving into db), then 2 sets joined and ordered by again for this new condition Fun fact: I also have BooleanField that indicates if period is closed or not. I needed it for simplicity and filtering but we could use this here as … -
Django model FilterSet - choose database and update filter fields from view
I have a Django application working with multiple databases of the same structure. Database name is a part of the url so it comes as an argument into the view (self.kwargs['db']). I use django-tables2 along with django-filter to show table data (SingleTableMixin, FilterView). I need to set which database has to be used to populate the filter's fields. The filter uses the default one at the moment. filters.py class FooFilter(django_filters.FilterSet): class Meta: model = Foo fields = ['project', 'fooclass'] views.py class FilteredFooView(SingleTableMixin, FilterView): template_name = "metadata/metadata-filtered-table.html" table_pagination = False table_class = FooTable model = Foo filterset_class = FooFilter def get_queryset(self): return Foo.objects.using(self.kwargs['db']).all() # sets db for the table def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) template_input = {'item': 'FooItem', 'name': getName(self.kwargs['db'])} context = {**template_input, **context, **self.kwargs} return context -
How can i filter objects for multiple values in Python Django?
I am trying to filter Objects in django for a query set instead of a single value. Please see my code below @api_view(['GET']) def getOffersReceived(request, name): owner = Profile.objects.get(name=name) dogs = Dog.objects.filter(owner=owner) print(dogs) sittings = Sitting.objects.filter(dog=dogs) return Response() The print(dogs) line is showing a query set of 4 values. The next step I am trying to get all the sittings that have value dog matching either one of the items in the query set. I am getting the following error: ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. any help would be greatly appreciated. Thank you -
Django forloop inside forloop in Template
hello iam trying to make Dropdown Menu in Navbar with querysets. I was trying to make it with two querysets send to html template ( "stages","questions") that are related to each other by key (id , stage_id), but i cant figured out why forloops cant work together. My second try was with passing data in json to javascript and make it with js QuerySelector, but django querysets are not JSON serializable. Any suggestions how to make it please ? views.py def edit_pages(request, gameid): stages = Stage.objects.filter(game_id=gameid) print(stages) questions = [] for st in stages: questions = chain(questions,Question.objects.filter(stage_id=st.id)) print(questions) return render(request, "homeSuperuser/edit_pages.html",{'stages': stages, 'questions': questions}) html <body> <div class="topnav"> {% for st in stages %} <div class="dropdown"> <button class="dropbtn">{{st.stage_name}}</button> <div class="dropdown-content"> {% for qs in questions %} {% if qs.stage_id == st.id %} <a href="#">{{qs.question_name}}</a> {% endif %} {% endfor %} </div> </div> {% endfor %} </div> </body> -
Alternative to using `regroup` in Django template on `ListView` using a lot of memory
I have tried using the following to regroup a ListView queryset in my template so that objects are grouped by a related field's value: {% regroup object_list by related_field.sort_value as grouped_list %} {% for group in grouped_list %} <span>{{group.grouper}}</span> {% for item in group.list %} <p>{{item.related_field.name}}</p> <p>{{item.description}}</p> {% endfor %} {% endfor %} The model has about a dozen fields, two of them relational (first related model has a couple dozen fields, the other has just a few) and there's several hundred total objects in the ListView queryset results. View: class BigListView(ListView): model = MyModel template_name = 'my_model/big_list_view.html' def get_queryset(self): return MyModel.objects.order_by('related_model_b.sort_value') Models: class MyModel(models.Model): code = models.CharField(max_length=30, unique=True) price = models.DecimalField(max_digits=8, decimal_places=2) sale_price = models.DecimalField(max_digits=8, decimal_places=2) sale_price_quantity_3_5 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) sale_price_quantity_6 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) description = models.CharField(max_length=40) location = models.CharField(max_length=20) quantity_on_hand = models.IntegerField() size = models.CharField(max_length=20) tag_description = models.CharField(max_length=100) color = ColorField(help_text='Theme Color') image = models.ImageField(upload_to=assign_product_sku, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) related_model_a = models.ForeignKey(RelatedModelA, related_name='mymodels', on_delete=models.CASCADE) related_model_b = models.ForeignKey('RelatedModelB', related_name='mymodels', on_delete=models.CASCADE, blank=True, null=True) class RelatedModelA(index.Indexed, models.Model): sku = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=100) alt_name = models.CharField(max_length=100, blank=True) description = models.TextField(blank=True) age = models.CharField(max_length=3, blank=True) size = models.CharField(max_length=100, blank=True) weight = models.CharField(max_length=100, blank=True) … -
Django: How to restrict access to views based on more than one condition
I'm already using UserPassesTestMixin with 1 test_func (as seen in the snippet from comments/views.py below). I'd like to incorporate another condition which is based on a boolean field in the user model: is_creator (snippet below from accounts/models.py). # comments/views.py class CommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): # new model = Comment fields = ( "body", ) template_name = "comments/comment_update.html" def test_func(self): return self.request.user == self.object.owner # accounts/models.py class CustomUser(AbstractUser): is_creator = models.BooleanField(default=False) I know I can create a custom decorator (function view)/mixins (class views) and slap it on/into the view I'd like to add the restriction to, but I was wondering if I have other options. Thanks in advance! -
In a new project, Graphene or Strawberry? Why?
which lib is better to integrate with a new django project? i red the docs and still doesnt know how performatic or easier to integrate each one can be in prod environment. i used graphene before to integrate with some pipefy code that i did at work but im pretty new in graphql and dont know at this point what way i should go. Strawberry docs - https://strawberry.rocks/docs Graphene - https://docs.graphene-python.org/en/latest/ -
Django constraints - only users with specific role can have specific field set (not null)
Trying to figure out if and how can I set conditional constraints like this: Only users with role=='client' can have User.broker field not null. Is it possible to do that using Meta.contstraints or a different mechanism that will take care of that? User model: class User...: role = CharField(...) broker = ForeignKey('User'...) -
Test with mock pass when run individually but not when together
I want test if a function is called in a view. My view is something like that: @api_view(["POST"]) def my_view(request): data = request.data my_function(data) return Response("ok") And my test: @pytest.fixture def mock_my_function(mocker): return mocker.patch("path.for.my.function") def test_my_test( mock_my_function, db, client ): data = {"some": "thing"} resp = client.post( "/my/url/", data=data, format="json", ) assert resp.data == "ok" mock_my_function.assert_called() Running this test individually, it's ok. Works! But, when I run all tests, this test fails. Pytest show me this error: E AssertionError: Expected 'mock_my_function' to have been called. -
Django queryset foreign key 3 tables
I have the following models: class Productos(models.Model): nombre = models.CharField(max_length=200, null=True) precio_publico = models.FloatField(null=True, blank=True) costo = models.FloatField(null=False, blank=False) inventario = models.IntegerField(null=False, blank=False, default=0) fecha_compra = models.DateField(blank=True, null=True) tipo_movimiento = models.CharField(max_length=1, choices=TIPO_MOVIMIENTO) slug = models.SlugField(blank=True, null=True) descripcion_corta = models.TextField(blank=True, null=True) descripcion = models.TextField(blank=True, null=True) imagen = models.ImageField(upload_to='images/',blank=True, null=True) marca = models.CharField(max_length=20) categoria = models.ForeignKey(Categorias, null= True, on_delete=SET_NULL) descuento = models.ForeignKey(Promos, blank=True, null=True, on_delete=CASCADE) inventariar = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class ProductosOrden(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) producto = models.ForeignKey(Productos, on_delete=models.CASCADE) cantidad = models.IntegerField(default=1) ordenado = models.BooleanField(default=False) class Orden(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) producto = models.ManyToManyField( ProductosOrden) medio_de_venta = models.ForeignKey(MediosVenta, null=True, blank=False, on_delete=models.SET_NULL) fecha_venta = models.DateField(blank=False, null=False) ordenado = models.BooleanField(default=False) ref_code = models.CharField(max_length=20, blank=True, null=True) promo = models.ForeignKey(Promos,null=True, blank=True, on_delete=CASCADE ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) vendido_por = models.CharField(max_length=20, null=False, blank=False) I need to query from Orden all the way to Productos and get the 'name' attribute I have tried the following: categoria = Orden.objects.filter(user=self.request.user, ref_code = '225v3cwhvqi0ymp2yw2n').values('producto__producto') and I get Id's instead of 'nombre': <QuerySet [{'producto__producto': 5}, {'producto__producto': 19}, {'producto__producto': 3}]> how can I access the attribute 'nombre' from the 'Productos' Model? -
Nginx reverse proxy with DRF API
I have a problem with NGINX Reverse proxy for Django Rest Framework API. My architecture is in Docker and the nginx container calls an other python container thanks to proxy_pass property with his hostnames. To target the DRF API, I use an '/api/' location. This location and proxy_pass is a success and when I call the URL, the swagger of the API open. However, when I test to open the administration, with this URL '/api/admin', a redirection open the URL '/admin' and a 404 appears. This is the same issue for the others pages. Do you have an idea about the mistake to target for example '/api/admin' ? My nginx template is : location /api/ { proxy_pass http://api.drf.fr:8000/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; client_max_body_size 0; } My URL in DRF API seems like this : from django.contrib import admin from django.urls import path, include, re_path from api.views import * schema_view = get_swagger_view(title='API') urlpatterns = [ re_path(r'^auth/', include(('drf_social_oauth2.urls', 'drf'), namespace='drf')), path('admin/', admin.site.urls), path('', schema_view) ] I don't know if it's useful, but I run the API in a python container thanks to this command : gunicorn apidrf.wsgi --bind 0.0.0.0:8000 --workers 4 --threads 4. -
How to handle ManyToMany fields while testing django-models?
I am trying to write tests for my django models. However, I've got a problem with testing ManyToManyFields and haven't resolved it yet. class TestVolunteeringModels(TestCase): def setUp(self) -> None: self.test_need = sample_need(title="Need", description="Description") self.test_opportunity = sample_opportunity(title="Opportunity", description="Description") for i in range(10): self.test_category = sample_category(name="Category") self.test_need.category = self.test_category self.test_opportunity.category = self.test_category def tearDown(self) -> None: self.test_need.delete() self.test_opportunity.delete() Which brings me this error: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead. The problem is when I use .set() as written in traceback instructions, like this: self.test_need.category.set(self.test_category) self.test_opportunity.category.set(self.test_category) It gives me another error, which says "TypeError: 'Category' object is not iterable" So my question is how can I access ManyToMany field in this case, so I can test it freely? -
Django Admin: column incidentreport_incidentperson.id does not exist; relation does not exist
I created many database in Incident Report but only db IncidentPerson got an error. When I open django admin it kept on sayng "ProgrammingError at /admin/incidentreport/incidentperson/ column incidentreport_incidentperson.id does not exist LINE 1: SELECT "incidentreport_incidentperson"."id", "incidentreport...". Appreciate the help. Thank you class IncidentPerson(models.Model): GENDER = ( (1, 'Female'), (2, 'Male'), ) INVOLVEMENT = ( (1, 'Pedestrian'), (2, 'Witness'), (3, 'Passenger'), (4, 'Driver'), ) ID_PRESENTED = ( (1, "Driver's License"), (2, 'Government'), (3, 'Passport'), (4, 'School Id'), (5, 'Others'), ) INJURY = ( (1, "Fatal"), (2, 'Minor'), (3, 'Not Injured'), (4, 'Serious'), ) DRIVER_ERROR = ( (1, "Bad Overtaking"), (2, 'Bad Turning'), (3, 'Fatigued / Asleep'), (4, 'Inattentive'), (5, 'No Signal'), (6, 'Too Close'), (7, 'Too Fast'), (8, 'Using Cellphone'), ) ALCOHOL_DRUGS = ( (1, "Alcohol Suspected"), (2, 'Drugs suspected'), ) SEATBELT_HELMET = ( (1, "Seat belt/Helmet Worn"), (2, 'Not worn'), (3, 'Not worn correctly'), ) incident_general = models.ManyToManyField(IncidentGeneral, blank=True, null=True) incident_first_name = models.CharField(max_length=250, blank=True) incident_middle_name = models.CharField(max_length=250, blank=True) incident_last_name = models.CharField(max_length=250, blank=True) incident_age = models.CharField(max_length=250, blank=True) incident_gender = models.PositiveSmallIntegerField(choices=GENDER, blank=True, null=True) incident_address = models.CharField(max_length=250, blank=True) incident_involvement = models.PositiveSmallIntegerField(choices=INVOLVEMENT, blank=True, null=True) incident_id_presented = models.PositiveSmallIntegerField(choices=ID_PRESENTED, blank=True, null=True) incident_id_number = models.CharField(max_length=250, blank=True) incident_injury = models.PositiveSmallIntegerField(choices=INJURY, blank=True, null=True) incident_driver_error = models.PositiveSmallIntegerField(choices=DRIVER_ERROR, blank=True, null=True) incident_alcohol_drugs … -
Implement Push notifications in Django REST + ReactJS with FIREBASE
I am trying to implement web push notification feature using React + django with Firebase. Can anyone help me with this?