Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-admin: show multi select field for JSONField
I have a model with a field channel (JSONField). I'm strong an array of string in db with channel. By default, a JSONField is shown as a textarea in django-admin. My goal is to somehow make channel a multi-select field that later converts to like this ["APP", "WEB"]. models.py @dataclass class ChannelTypes: WEB: str = 'WEB' APP: str = 'APP' class DiscountRule(models.Model): ... channel = models.JSONField(null=False, blank=False, default=list(astuple(ChannelTypes()))) My Approach: In forms.py, add custom fields (boolean) that only show up in admin form and are not stored in db. Something like this: class RuleAdminForm(forms.ModelForm): WEB = forms.BooleanField(required=False) APP = forms.BooleanField(required=False) Similarly, admin.py will populate the custom fields like this: def get_form(self, request, obj=None, *args, **kwargs): form = super(BaseDiscountRuleAdmin, self).get_form(request, *args, **kwargs) for i in obj.channel: form.base_fields[i].initial = True return form But this causes a problem that the custom field value persists after updating 1-2 times due to using base_fields[field_name].initial. Ideas for goal: Multi select option 1 -
How to save image inside a specific folder(folder name should be id)-DRF
I want to save image inside folder name same as id. Id is a automatic primary key.I tried that when i give post request i got none as a id. how can i achieve this???? models.py def upload_to(instance, filename): return 'organization/{instance}/logo/{filename}'.format(filename=filename, instance=instance.pk) class Organization(models.Model): code = models.CharField(max_length=25, null=False, unique=True) name = models.CharField(max_length=100, null=False) location = models.ForeignKey(Location, on_delete=models.RESTRICT) logo_filename = models.ImageField(_("Image"), upload_to=upload_to, null=True) I know i cant take id before saving into db. there is any possible to do rename when i gave post request?? I got confused over this. Any help appreciable,... -
Select Objects related in third table
Say I have the models class A(models.Model): class B(models.Model): class C(models.model): b = models.ForeignKey(B) class D(models.Model): c = models.ForeignKey(C) a = models.ForeignKey(A) What would a ORM query look like to select all Bs that are related to C's that are related to a specific A through table D? -
I keep getting this error when deleting posts and comments on my django project TypeError: __str__ returned non-string (type User)
I keep getting this error when deleting posts and comments on my django project TypeError at /admin/blog/comment/ __str__ returned non-string (type User) Request Method: POST Request URL: http://127.0.0.1:8000/admin/blog/comment/ Django Version: 2.2.1 Exception Type: TypeError Exception Value: __str__ returned non-string (type User) Exception Location: /home/martin/.local/lib/python3.8/site-packages/django/contrib/admin/utils.py in format_callback, line 126 Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/home/martin/django-blog', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/martin/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] This is error from konsole no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), obj) TypeError: __str__ returned non-string (type User) [28/Jan/2022 09:46:12] "POST /admin/blog/comment/ HTTP/1.1" 500 135782 -
How to environment variables in Heroku?
I've been stuck on this for ages and I can't find a solution. I've set up environment variables in the ~/.zshrc file and exported them correctly. Now when I try these commands for heroku setup it works for the email address but when I enter it for the password it removes the '!' at the end of my password. input: heroku config:set EMAIL_HOST_USER="myemail@gmail.com" heroku config:set EMAIL_HOST_PASSWORD="mypassword!" output: Setting EMAIL_HOST_PASSWORD and restarting ⬢ <app-name>... done, v45 EMAIL_HOST_PASSWORD: mypassword Can anyone explain why this may be happening? I have also tried, heroku connfig:add .... but the exclamation mark is also removed.. -
Method not allowed in django when i clicked the register form?
Method Not Allowed (GET): /customerregister/register Method Not Allowed: /customerregister/register [28/Jan/2022 09:29:50] "GET /customerregister/register HTTP/1.1" 405 -
How to write unit test for url shortener app using pytest?
<https://github.com/coderaki17/url_shortener_app/tree/master > I have attached my git repo above kindly help me out to write pytest for my code . -
Customize Django FilterSet: Create custom filter
I have a document table (django-tables2) and a FilterSet (django-filter) to filter it. That works fine in general. I want to create a custom ModelChoiceFilter (or ChoiceFilter) to display the elements in a two level hierarchy (a tree with parent nodes and one level of children): + Category 1 + Subcategory 1.1 + Subcategory 1.2 + Category 2 + Subcategory 2.1 + Subcategory 2.2 There is no need to expand and collapse the tree, i just want to show them ordered by category and rendered a little differently if they are first or second level. There are never more than two levels present and each top level component has at least one child. My current FilterSet looks like this: class DocumentFilter(FilterSet): title_name = CharFilter(lookup_expr='icontains') place_name = CharFilter(lookup_expr='icontains') source_type = ModelChoiceFilter(queryset=SourceType.objects.all().order_by('type_name')) doc_start_date = DateFromToRangeFilter() class Meta: model = Document fields = ['title_name', 'source_type', 'place_name', 'doc_start_date'] My model for the SourceType is as follows: class SourceType(models.Model): type_name = models.CharField(verbose_name="archivalienart", max_length=50,) parent_type = models.ForeignKey('self', verbose_name="übergeordnete Archivalienart", on_delete=models.CASCADE, null=True, blank=True, related_name="child_type",) The filter form template is as follows: {% load bootstrap4 %} <form action="{{ request.path }}" method="get" class="form form-inline"> <i class="fas fa-filter"></i>&nbsp; {% bootstrap_form filter.form layout='inline' form_group_class='my-small-form' %} &nbsp; {% bootstrap_button '<i class="fas fa-filter"></i>' … -
Django Page error takes no argument when click on link to it
I have been struggling with one of my pages in django. Basically I a making a graph (nodes and edges) where you can add remove nodes through forms. I have a graph model (GraphDetail) which requires nodes, and I am building the node form (GraphCreateNode) that adds nodes to the graph. However the link does not work. It says that GraphCreateNode does not take any arguments. Now CreateGraphNode needs the id of the graph it is going to be added to, whether that is sent via the url or stored and accessed in session I do not have a preference. Right now I am trying via the url. And as said I get an error, and I cannot see where I need to fix it, which is why I am asking all of you. Error Message: TypeError at /graphs/graph/74921f18-ed5f-4759-9f0c-699a51af4307/graph_add_node/ GraphCreateNode() takes no arguments So I looked around here to see what I could find: What is a NoReverseMatch error, and how do I fix it? was quite informative but not quite enough. Then I found TypeError: CraiglistScraper() takes no arguments, whilst it was about Selinum it mentioned something about a constructor. My class does not have a constructur, but does … -
Custom button in Class based UpdateView django
Problem: My UpdateView looks the same as my CreateView. I would like to change the submit button from "Check" to "Update". Here are my views in the views.py file: class CapsUnifCreateView(CreateView): template_name = 'capsules/uniformity_form.html' model = models.Uniformity fields = ( 'caps_name', 'mass_1_caps_empty', 'mass_20_caps_full', 'mass_max1', 'mass_min1', ) class CapsUnifUpdateView(UpdateView): fields = ( 'caps_name', 'mass_1_caps_empty', 'mass_20_caps_full', 'mass_max1', 'mass_min1', ) model = models.Uniformity Note, that I do not use a separate template for the UpdateView. Something like {% if CreateView %} Check {% else %} Update {% endif %} in the html file would be nice, but I don't know how to implement it. Thanks in advance! -
CSRF verification failed. Request aborted. only for login page
I am creating a To-Do application as my first project in django. Everything works fine when I run on local server but when I deploy it to heroku, CSRF token is not working on login page only. The app is deployed here. Issue: If we try any random or existing user on the login page, it shows CSRF verification failed BUT if we open /register endpoint i.e. Register a user on the app, it creates user and logs in to that user correctly at them time. Whole app features like adding a new task, editing a task, deleting a task works fine until I logout that user. When I come back to the login page again, I am not able to login with any user account. I've tried a lot of different methods like services in Procfile, environment variables for SECRET_KEY, providing meta tag in the main.html for csrf token using content={{ csrf_token }} but no luck. Codes: settings.py # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv('DEBUG', False) ALLOWED_HOSTS = [ '.herokuapp.com', '127.0.0.1:8000' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Facebook Webhook - The URL couldn't be validated. Response does not match challenge (Python)
When I try to set up the webhook, this is the error I receive. (I used Python and Django) It's my views.py: def getInstagramWebhook(request): if request.method == "GET": mode = request.GET.get("hub.mode") challenge = request.GET.get("hub.challenge") verify_token = request.GET.get("hub.verify_token") if verify_token == '123456': return HttpResponse(challenge) Facebook Get my callback URL: "GET /eroupa/webhook?hub.mode=subscribe&hub.challenge=331408336&hub.verify_token=123456 HTTP/1.1" 200 10 But I receive the below error: The URL couldn't be validated. Response does not match challenge, expected value="1049288922", received="\u003C!DOCTYPE html>\n\u003Chtm..." I think, I should change my return, I tried return(challenge) and JsonResponse but it's not work -
DRF nested serializer issue on create
I have a User model and a phone model the phone model has a foreign key relation with the user model i read the docs on NestedSerializers and tried it to no avail. this is my serializers.py file class PhoneSerializer(serializers.ModelSerializer): # opt = serializers.IntegerField(read_only=True) class Meta: model = Phone fields = ['phone'] class RegisterSerializerBase(serializers.ModelSerializer): phone = PhoneSerializer(many=False, allow_null=True) # otp = PhoneSerializer(many=True, read_only=True) email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('email', 'firstname', 'lastname', 'password', 'password2', 'phone',) extra_kwargs = {'password': {'write_only': True}, 'password2': {'write_only': True}, 'firstname': {'required': True}, 'lastname': {'required': True}, } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): phones = validated_data.pop('phone') instance = User.objects.create( email=validated_data['email'], firstname=validated_data['firstname'], lastname=validated_data['lastname'], is_active='True', type=User.TYPES.OWNER, ) instance.set_password(validated_data['password']) for phone in phones: Phone.objects.create(instance=instance, **phone) return instance when I go the the Browsable API and create a user with the credentials an error comes up saying django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str -
Django Postgres PostGISSpatialRefSys matching query does not exist
I am implementing location feature in my Django project with Postgresql as my database, so for that I install Postgres and then install PostGis extension I have the following filter query executed in my views.py from django.contrib.gis.measure import D from django.contrib.gis.db.models.functions import Distance Lesson.objects.filter(venue_coord__distance_gte=(request.user.location_coord, D(km=int(km))) Executing the above filter results in error: PostGISSpatialRefSys matching query does not exist In models.py I have venue_coord & location_coord that stores PointField as follows venue_coord = models.PointField(verbose_name=_(" Venue Co-ord"), blank=True, null=True) location_coord = models.PointField(verbose_name=_(" User Co-ord"), blank=True, null=True) Can anyone suggest why postgis is giving error all of a sudden. -
How to print the correct time from the datetime input in the form
I am getting date and time input from form through datetimepicker in Django. Because the current template outputs {{ form }} , you need to set the format of the time to be output to the template in models.py. I entered 3 PM, but 06:00 is stored in the db, and the time obtained by the get_time function is also 06:00. What should I set to display 15:00 in the template? def get_time(self): return self.date.strftime('%H:%M') @property def get_html_url(self): url = reverse('dataroom:training_edit', args=(self.id,)) return f'<div class="training-title" data-toggle="modal" data-target="#training_{self.id}">{self.get_time()}: {self.topic}' \ f'<a href="{url}" style="color:black;">&nbsp;&nbsp;<span style="color:red;">Edit</span></a></div>' -
Image is not loading from django rest framework in react
i am beginner in drf. i want to load image from django rest framework to react but I does not show image in react. views.py def PostView(request): parser_classes = (MultiPartParser, FormParser,JSONParser) if request.method=="GET": post = Post.objects.all() post_serializer = PostSerializer(post, many=True) return Response(post_serializer.data) Seriliazer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Axios call async function getPost() { await axios .get( "http://127.0.0.1:8000/api/post/" ) .then((res) => { console.log(res.data); setPost(res.data); }); } and react code is <div className="card mb-3" key={res.id}> <img className="card-img-top" src={`http://127.0.0.1:8000${res.image}`} alt="post image" /> <div className="card-body"> <h4>{res.title}</h4> <p className="card-text">{res.image}</p> </div> following is my API response following is my API response and browser error error -
django.core.exceptions.validationerror value true or false during migration
I am running into this error while trying to migrate a table. Once the error came, I has been persistent. KINDLY ASSIST. -
Django index unique on where
I have a class, which represents photos attached to a person. class PersonPhoto(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) photo = models.FileField(upload_to='photos/', blank=True, null=True) person = models.ForeignKey( Person, related_name="photos", on_delete=models.CASCADE ) main = models.BooleanField(default=False) I want to make sure that for every person there could be only one main photo. In pure SQL i would use something like create unique index on photo (person_id, main) where main = true; You can play with it here http://sqlfiddle.com/#!15/34dfe/4 How to express such constraint in django model? I am using django 4.0.1 -
Adding the member in django REST framework serializer
I am using serializer of Django REST framework I have this Serializer and class. This serializes data and passes as json. class SpotSerializer(serializers.Serializer): spot_id = serializers.IntegerField() another_id = serializers.IntegerField() class Spot: def __init__(self, spot_id,another_id) self.spot_id = spot_id self.another_id = another_id Now I want to add the another variable not the class member such as class SpotSerializer(serializers.Serializer): spot_id = serializers.IntegerField() another_id = serializers.IntegerField() another_name = Another.objects.get(id=another_id).name // adding This code doesn't show error but no another_name field is appeared in json. So is it possible? -
Django : How to redirect any post request on some views
I have a project setup on server(Cloud) which talks to another server(like chat system), at both sides we make API calls for servers(Cloud) to talk to each other we can call them Server#1 and Server#2.Now I want to setup this project on local(ngrok , localtunnel), so how do I redirect post requests by Server#1 on some views that I get on Server#2 to local web server or public domain of ngrok or localtunnel. I can use requests module to make API calls to public ngrok domain but I'll have to write this in many views.Is there any alternative or better way to handle this? -
Django JWT Token json response
I'm trying to do jwt token auth on django, when i try on postman im getting json response as ss 1 but on the frontend site im gettin html page. why is that, is there anyone to know fix this. thanks. postman-response -
Django AJAX call to refresh table data instead of using "append"
I want to refresh the data in my table every 10 seconds, without reloading the whole page again and again So I wrote some code in AJAX to append the new data But I want to refresh the data in the existing table and am not sure how to do that My current HTML code is just appending the whole table again and again, but I just want to refresh the data in a single table <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>temp1</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>Hello there</h1> <h1>{{info_data}}</h1> <table id="_appendHere" class="table table-striped table-condensed"> <tr> <th>Username</th> <th>Email</th> <th>Gender</th> </tr> {% for item in info_data %} <tr><td>{{item.username}} - {{item.email}} - {{item.gender}}</td></tr> {% endfor %} </table> </body> <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'App1:tempPage' %}, // URL to your view that serves new info data: {'append_increment': append_increment} }) .done(function(response) { $('#_appendHere').append(response); append_increment += 10; }); }, 10000) </script> </html> Any help would be highly appreciated!! Thanks!! -
How to implement authentication with Azure Directory when using React Frontend and Django REST API backend?
I'm just now learning Django REST Framework. However, I've been put on a project in charge of the DRF API. The project has a React frontend connected to a DRF API backend. I've made basic JWT Auth on the DRF API side before. However, we've been tasked with using Azure Directory for authentication. My question is how would this be setup? Would the Azure Directory auth be implemented on the frontend? What should be passed back and forth from the DRF API? I'm just a little confused reading the documentation and what needs to be stored for login and sessions on the API vs the frontend. Any information would be helpful, whether it would be specifics or the general apparatus. -
Django-error OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2
When I do manage.py makemigrations An error like this occurs PS C:\Users\User\PycharmProject\onlineshop-master> python .\manage.py makemigrations Traceback (most recent call last): File "C:\Users\User\PycharmProject\onlineshop-master\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\base.py", line 376, in check all_issues = self._run_checks( File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\User\PycharmProject\onlineshop-master\config\urls.py", line 24, in … -
Django how to sort and paginate nested ORM and non-ORM object
I need to make a query to get some properties and with its category FK get data for monthly cost in another table. With the result, need to calc value by day, installments, total price and due date. all works fine but there is a need to order data by some fields of the Property model, order by total price and paginate the result. i could make both, order and paginate work, but not together. Also, i'd like to ask if those calcs with installments is right to be placed on serializer.py, or should be moved to the viewset.py, or somewhere else? Here is my code so far: ViewSet.py with pagination: class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.Property.objects.filter(status)\ .prefetch_related('owner__user')\ .prefetch_related('host__user')\ .prefetch_related('category__user') serializer_class = MySerializer pagination_class = StandardResultsSetPagination filterset_class = MyFilterSet filter_backends = [filters.OrderingFilter, dj_filters.DjangoFilterBackend] def get_queryset(self): today = str(datetime.now()) start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') ''' validate start_date and end_date ''' return self.queryset ViewSet.py with sort: class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.Property.objects.filter(status)\ .prefetch_related('owner__user')\ .prefetch_related('host__user')\ .prefetch_related('category__user') serializer_class = MySerializer # pagination_class = StandardResultsSetPagination filterset_class = MyFilterSet filter_backends = [filters.OrderingFilter, dj_filters.DjangoFilterBackend] def get_queryset(self): today = str(datetime.now()) start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') ''' validate start_date and end_date ''' return self.queryset def list(self, request, *args, **kwargs): …