Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSRF verification failed on admin login when put on server
I've got a Django application running locally. Can login without any issues. When I've put this on a server, using AWS ElasticBeanstalk, I'm getting a CSRF verification failed. I don't know if this is relevant but this is the 2nd instance of this application, using the same database as the first instance. I'm getting the CSRF validation issue on all forms. I have cleared my cookies to ensure that isn't causing the problem. Can anyone advise how to troubleshoot this Thanks -
DRF change default viewset's lookup_field for custom action
How can I change a default lookup parameter for my custom action in DRF Viewset? Here is my Viewset (simplified) class InvitationViewSet(MultiSerializerViewSet): queryset = Invitation.objects.all() @action( detail=False, #url_path='accept-invitation/<str:key>/', #lookup_field='key' ) def accept_invitation(self, request, key=None): invitation = self.get_object() with legal_invitation(invitation): serializer = self.get_serializer(invitation) invitation.accepted = True invitation.save() return Response(serializer.data) I want when user enters url like /invitations/accept_invitation/abccba, where abccba is a random token string. key - is a unique field in Invitation model. I know I can set per-Viewset lookup_field='key', but I want all other actions still use default lookup_field='pk'. How can I achieve what I want? -
Forloop in django template
How could I get a next object in django for loop? I mean is it possible to do like this {{ route.0.segments.all.ind }}? {% for segment in route.segments.all %} {% if segment.departure == departure %} {% with forloop.counter as ind %} <span style="margin-top: -5px; font-size: smaller"> $ {{ route.0.segments.all.ind }} {{ segment.distance }}km {{ segment.duration }}hour</span> {%endwith %} {% endif %} {% endfor %} -
How to fix: Django forms: {{ form }} doesn't show up any result in html page
I've created a django form: #forms.py from django import forms class NameForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) sender = forms.EmailField() cc_myself = forms.BooleanField(required=False) and in view file: #views.py def get_form(request): print(request.POST) form = NameForm(request.POST or None) if form.is_valid(): print(form.cleaned_data) return render(request, "name.html", {"title": "Contact us"}) I've imported to a html file inside templates folder: #templates/name.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </body> </html> However, it doesn't show up any thing just a submit button. I have no idea what is the issue. I'll be so grateful for a solution around this issue. Update: If I create a new html file, the form is shown there. However, if I use it in my main html including boostarp, it is not showing up. Here is the full code of my html: {% extends 'base.html' %} {% block content %} <!-- Team --> {% for card in cards %} <!-- Team member --> <div class="col-xs-12 col-sm-6 col-md-4"> <div class="image-flip" ontouchstart="this.classList.toggle('hover');"> <div class="mainflip"> <div class="frontside"> <div class="card"> <div class="card-body text-center"> <p><img class=" img-fluid" src="https://sunlimetech.com/portfolio/boot4menu/assets/imgs/team/img_01.png" alt="card image"></p> <h4 class="card-title">{{ card.name }}</h4> <p class="card-text">{{ card.description }}</p> <a href="#" … -
How to extend default user model in django2.12
I am working on a project and i am not using the default django user model instead i am using my own custom user model. but i am experiencing a problem. For my user model i have also made my own authb.py file which i have provided below and if i am using the default django authentication then it is authenticating only my superuser and not the user that i am entering through the sign up form and i am totally stuck. first here is my authb.py from .models import User class AuthB: def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) return user except: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except: return None but right now i am not using this authb instead i am using default authentication. here is my models.py for user model class User(models.Model): is_authenticated = True username = models.CharField(max_length= 25) email = models.CharField(max_length= 150) password = models.CharField(max_length= 100) last_login = models.DateTimeField(auto_now= True) profilepic = models.CharField(max_length= 255, default= "") def __str__(self): return self.username here is my views.py file def signup(request): # context = {} # return render(request, 'sign-up.html', context) if request.method == 'POST': # print(request.POST) # Get form values username = request.POST['username'] email = request.POST['email'] … -
Override the default Verify class in django-graphql-jwt
I actually want to override the default Verify class in django-graphql-jwt https://github.com/flavors/django-graphql-jwt/blob/9879f29a2a9de421b11e6bf04f9c55b2f2d97dd7/graphql_jwt/mutations.py#L43 I tried this code but it doesn't work class Verify(graphql_jwt.Verify): @classmethod def mutate(cls, root, info, token, **kwargs): # my code here return super(Verify, cls).mutate() -
I am working a product based project in Django . I want to use ElasticSearch 6 or ElasticSearch 7 for searching .So how to implement with my code?
I am working a product based project . I want use elasticsearch 7 or elasticsearch 6 for product searching. so I have some doubt - 1- Can I used with Haystack ? could Haystack Support ElasticSearch 6 or 7 ? 2- can I used Elasticsearch DSL ? 3- or any other way to implement ElasticSearch6 or 7 with project? Also plz tell proper detail how to implement Elasticsearch? -
Django send_mail "to_email" field
I am having trouble getting the to_email field for the recipient. Using Django 2.1 and sending an automatic email after a user signs up to a certain page. Right now the email sends to reciever@gmail.com which is obviously incorrect. It needs to send to whatever email was entered into the form. I've tried changing to to_email= request.POST['email'] and to_email = form.cleaned_data['email'] but those don't work. Can someone help me? views.py def list_view(request): if request.method == 'POST': form = ListForm(request.POST) if form.is_valid(): form.save() messages.success(request, f"signed up!") subject = "Yay." html_message = render_to_string('mail/mail_template.html', {'context': 'values'}) plain_message = strip_tags(html_message) from_email = settings.EMAIL_HOST_USER to_email = ['receiver@gmail.com',] html_message.content_subtype = "html" send_mail( subject, plain_message, from_email, to_email, html_message=html_message ) return redirect('landing') forms.py class ListForm(forms.ModelForm): email = forms.EmailField(required=True) class Meta: model = List fields = ['email'] -
importing models into functions.py works one way but not the better way
I have an django app called my_app. I created a functions.py in it in the same location as models.py. When I do from .models import my_model I get error that it cannot import my_model. This happens even when i use my_app.models But when I do from . import models it works and I am able to do models.my_model. I don't want to import all models. I want to import only my_model from the models.py. Can anyone please help getting that better(?) way to work? Thank you -
Problem with testing logout function in Django project
When I test this function response status is 403. def test_logout(self): request = self.factory.post('http/api/logout/') request.user = self.user1 response = logout(request) self.assertEqual(response.status_code, status.HTTP_200_OK) My Authentification view: def login(request): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) def logout(request): request.auth.delete() return Response(status=status.HTTP_204_NO_CONTENT) How can I test the logout function view? -
Get related ID through formset
I have an inline formset which is working fine. There are a number of select boxes in the formset that lets you pick from various options in related tables. QuantityFormSet = inlineformset_factory(Option, Quantity, fields=('item', 'number','area'),extra=1) Item and Area are related tables. I want to set up a button inline with the form that let's the user click through to edit these two objects. So, for example, I want to achieve something like. {% for form in quantityForm %} {{ form.item }} <a href="{% url 'editItem' form.item.id %}"><i class="fas fa-edit"></i></a> {{ form.number }} {{ form.area }} {{ form.DELETE }} {% endfor %} However form.item.id isn't valid. How do I get the ID for form.item (which is a select box)? -
Django Make login/logout button defined in base.html appear in all pages that extend it
I am trying to implement login/logour unctionality using the default auth system in Django 2.2. I have the following included in my base.html <div class="nav-right-content"> <ul> <li class="nav-btn"> {% if user.is_authenticated %} <!-- Hi {{ user.username }}! --> <a href="{% url 'loggedout' %}" class="boxed-btn blank">logout</a> {% else %} <a href="{% url 'login' %}" class="boxed-btn blank">login</a> {% endif %} </li> <li class="nav-btn"> <a href="#" class="boxed-btn blank">Download</a> </li> </ul> </div> However, Even though I extend my index.html with base.html, it doesn't show the login/logout button correctly. Even when the user is logged-in it always shows the login button instead of logout button. Whereas, if I include the above snippet within my index.html it works correctly. What am i missing? Kindly guide. I don't want to have redundant code in all my htmls. -
How to add a record to a table that is implemented by default with PermissionsMixin
I am writing a backend for user authorization. I added my own user model and extended permissions and groups using PermissionsMixin. It prepared me a table in the database. How can I get there and use the shell to add records? The only thing I managed to do is add a group. I prepared a method for this. from django.contrib.auth.models import Group class UserManager(BaseUserManager): @staticmethod def create_auth_group(name): group = Group() group.name = name group.save() More specifically, how to add a record to the profiles_user_groups table? -
FileField: How to upload to with a whitespace in the name and path
I have a model that allow me to upload a file, but for some reason the whitespace defined in the custom upload_to function get replaced by underscore in the file system(or in s3) for both the filename and the folder path. Is there a way to enforce the use of whitespace? eg: The file "hello world.png" become "hello_world.png" ps: I know this is a bad practice to use whitespace, but it's not my choice . Here is the code: models.py one_file = models.FileField( _('My label'), null=True, blank=True, upload_to=one_file_name, max_length=500, #part for s3, using the local media doens't change anything storage=PrivateMediaStorage(), ) my upload_to function def one_file_name(instance, filename): extension = filename.split(".")[-1] return f'folder name/subfolder name/{filename}.{extension}' -
How to calculate Frechet Distance in Django?
This is basically a question about running custom PostGIS functions inside Django code. There is a number of related answers on this site, most close to my case is this one. It is suggested to use Func() or even GeoFunc() classes but there is no example for geospatial functions there. The latter ('GeoFunc') didn't even work for for me throwing st_geofunc does not exist exception (Django 2.1.5). The task that I have to complete is to filter linestrings based on their Frechet Distance to the given geometry. Frechet Distance is supposed to be calculated using ST_FrechetDistance function provided by PostGIS. In another project based on SQLAlchemy I completed exact same task with the following function (it is working): from geoalchemy2 import Geography, Geometry from sqlalchemy import func, cast def get_matched_segments(wkt: str, freche_threshold: float = 0.002): matched_segments = db_session.query(RoadElement).filter( func.ST_Dwithin( RoadElement.geom, cast(wkt, Geography), 10 ) ).filter( (func.ST_FrechetDistance( cast(RoadElement.geom, Geometry), cast(wkt, Geometry), 0.1 ) < freche_threshold) | # Frechet Distance is sensitive to geometry direction (func.ST_FrechetDistance( cast(RoadElement.geom, Geometry), func.ST_Reverse(cast(wkt, Geometry)), 0.1 ) < freche_threshold) ) return matched_segments As I said, the function above is working and I wanted to re-implement it in Django. I had to add additional SRS transformation of geometries … -
Correctly proxy nginx to django app with a subpath
I've been unable to fix this for almost a week now and would really appreciate some help. I feel like theres something I dont really understand and Im becoming increasingly frustrated because I cant seem to find a clear answer on this problem anywhere. Lets say I want to run a django app with uwsgi or gunicorn and have it be accessible via a subpath like for example : "www.mysite.com/app1" I create a nginx proxy_pass like this: location /app1/ { proxy_pass http://localhost:8000/; } Now. This far it works fine and I get redirected to the Django "/" page. If however I try to access "www.mysite.com/app1/admin" for example, I will be redirected to "www.mysite.com/admin", which is wrong. If I look at the nginx logs, I can see that there is a 301 Redirect for "www.mysite.com/app1/admin" and then obviously a 404 Not Found for "www.mysite.com/admin". I understand the problem is obviously that somehow Django or Uwsgi/Gunicorn need to know about the subpath I defined in Nginx. But I really cant find to seem a conlcusive answer of what the correct way of doing this is. Thank you very much -
How to remove an instance of a many to many relationship without deleting other instances
I am trying to disassociate a many to many relationship in django, but when i try to delete or remove or clear it, the instance of the object gets deleted. class Owner(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name class Items(models.Model): items_owner = models.ManyToManyField( Owner, related_name='owners_item', blank=True) item = models.CharField(max_length=150, unique=True) create some relationships sara = Owner(name='sara') pete = Owner(name='pete') cheese = Items(items='cheese') bacon = Items(item-'bacon') sara.owners_item.add(cheese) sara.owners_item.add(bacon) pete.owners_item.add(cheese) Try to delete the relationship between JUST sara and cheese sara.owners_item.remove(cheese) or sara.owners_item.clear(cheese) This deletes the Items instance of cheese, so pete no longer has a realationship to it... How do I keep all the object instances, yet be able to remove relationships? -
Bad display of the widget. Html, JS. Django - app
I create my application in Django. I am trying to add a simple widget from one of the web portals. <div id="distirbutor_comparision1_0_target"></div> <script id="distributorComparisionWidget_script" src="https://direct.money.pl/j/widgets/distributor_comparision_widget.js"></script> <script>var idDistributor = 241645; distributor_comparision_widget("distirbutor_comparision1_0_target", idDistributor, 1).render();</script> But it displays in a very unfavorable way. Correction should be displayed in this way. Can I change the size of the widget display on my website (not in the company that provides the widget)?? If so how to do it? The page that provides the code also has a widget preview option. Everything is properly displayed in it, and in the "Insepct" function only the code I have added on my website is visible. On my site I do not have any other elements except the added widget (so other elements do not change its size). -
Submitting a JS array via AJAX to Django view returns TypeError
I have an array of objects that needs to be submitted to Django view. I stringify it and checked result in console log. Up to this point it works. However, when I try to retrieve it in my view I get some errors. I tried to edit my code similarly to what I've found on the topic, unfortunately nothing helped. I tried ast.literal_eval instead of json.loads, passing 'items[]' and collecting data via request.POST.getlist as well as solution with request.body and request.is_ajax(). Yet, neither allowed me to retrieve the data. var items = []; var formInput = $('#inputbox').val(); items.push({'item': formInput , 'metrics': metrics.toString()}); $('#id_search').click(function( event ) { searchForm.submit(function () { $.ajax({ type: 'POST', dataType: 'json', contentType: 'application/json; charset=utf-8', url: '{% url "list_of_items" %}', data: JSON.stringify({'items': items,}), success: function (response) { console.log(data); } }); }); event.preventDefault(); }); and in views.py: def list_of_items(request): data = request.POST.get('items') data_received = json.loads(data) #(...) the JSON object must be str, not 'NoneType'``` I looks like an empty object is passed. This view receives another POST request from the JS form within same template (list_of_items.html) and I wonder if it's interfering with my ajax POST. -
Run a C++ algorithm that takes a file as input from django
I want to send a file from the UI (Django) to my C++ code that should be called when i submit the file.I also need to set some parameters in the C++ code that will be given by the user(need to get them from UI).How can we do this using subprocess module in python? -
Serialize the foreign keys
I am trying to serialize some data Here is my code : tennis = Tennis.objects.filter(name=name).values('competition__name', 'competition__rank') tennis_json = serializers.serialize('json', tennis) But I get the following error : {AttributeError}'dict' object has no attribute '_meta' So I looked for on stackoverflow and I modify my code like this : tennis = Tennis.objects.filter(name=name) tennis_json = serializers.serialize('json', tennis, field=('competition__name', 'competition__rank')) But unfortunately, I get nothing Could you help me please ? Thank you ! -
Deploying Django admin and Site as different applications
Is there a way to deploy Django Admin and your main application separately, though both of them sharing the same Models / Business logic services. I come from Grails background where you can create a plugin which can hold your Entities and common business logic and that plugin can be utilized by other application deployed and scaled separately though using the same Database. You don't have to repackage your plugin again for every change rather its just sibling folder to your other projects. Can I achieve something similar with Django? -
How to force a Django model to reload fields after saving without using refresh_from_db?
I have the following Django models: Device had a foreign key to Deployment I have the adopt method in Device that set the deployment for a device and perform some additional logic. notice that I pass an id and not a Deployment instance to the adopt method class Device(Model): id = models.UUIDField(primary_key=True) deployment = models.ForeignKey( Deployment, on_delete=models.SET_NULL, blank=True, null=True, related_name='devices' ) def adopt(self, deployment_id): self.deployment_id = deployment_id self.full_clean() with transaction.atomic(): self.save() # self.refresh_from_db() if self.deployment.private: # additional logic pass class Deployment(TimeStampedModel, DeploymentResource): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=150) private = models.BooleanField(default=False) If I do not access to the deployment field of the Device instance, adopt() works as expected. example: device = Device.objects.get(pk=device_id) device.adopt(deployment_id) # this works if instead I load the deployment field before calling adopt I get an AttributeError: 'NoneType' object has no attribute 'private' this does not works: device = Device.objects.get(pk=device_id) print(device.deployment) # example of accessing the field device.adopt(deployment_id) The cause is pretty obvious. device.deployment was None and it's not automatically reloaded after the save() call. An obvious solution is to call refresh_from_db after saving (see comment inside adopt method) but this will generate an additional query that I would like to avoid. Is there a way to … -
How to configure Google SSO (saml) for python?
I'm trying to configure Google's SSO for my django app. Google is the Identity provider and my app is the Service provider. I'm using python3-saml for the SSO and I used the files like in the django demo. Whenever I click login, Google tries to login but it returns a 403 saying csrf verification has failed. Any idea where I should be looking? For the files, I used the exact same as described in the demo mentioned above. -
How to mock a function called in Django flow
I'm creating test cases to do some end to end testing. One of these tests involves a call to the API for user registration which in turn calls multiple modules, one of which is calling a function "save_data_in_s3" which is responsible for storing some details in AWS S3. Now I want to mock this function inside the tests.py without making any changes in their respective modules. I have tried using the Python libraries such as patch and mock but I do not know how to handle a function which is not in the scope of tests.py module. Also I have tried using the @mock_s3 library, but that involves making changes in the respective modules.