Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Create a Model from parsing a different model's field
I have a model A with several fields. One of the fields ("results") is a a dict-like string in my database (which is hardly readable for a human being). Can I create a separate Model that would basically parse that "results" field into its own fields, so I can have a separate table with fields corresponding to the keys and values from my "results" field from model A? Final goal is to make a Results table that shows all the information in a pretty and easy-to-read manner. class ModelA(models.Model): language = models.CharField(max_length=30) date = models.DateTimeField() results = models.CharField(max_length=255) This is how "results" field looks in my database (I cannot change this format): OrderedDict([('Name', 'Bob'), ('Phone', '1234567890'), ('born', '01.01.1990')]) I want to create something like this: class Results(models.Model): name = model.Charfield(max_length=100) phone= model.IntegerField() born = model.DateTimeField() What is the best way to do this? How do I take the info from the "results" field from ModelA and "put" it into the Results model? -
WSGIRequest is not callable 'blockchain project'
I'm working on a blockchain project, but I had a problem that I could not solve myself, and here I share all the details of the project. Mining a new block def mine_block(request): if request.method == 'GET': previous_block = blockchain.get_last_block() previous_nonce = previous_block['nonce'] nonce = blockchain.proof_of_work(previous_nonce) previous_hash = blockchain.hash(previous_block) blockchain.add_transaction(sender = root_node, receiver = node_address, amount = 1.15, time=str(datetime.datetime.now())) block = blockchain.create_block(nonce, previous_hash) response = render(request({'message': 'Congratulations, you just mined a block!', 'index': block['index'], 'timestamp': block['timestamp'], 'nonce': block['nonce'], 'previous_hash': block['previous_hash'], 'transactions': block['transactions']})) return render(JsonResponse(response)) ``` # Getting the full Blockchain ``` def get_chain(request): if request.method == 'GET': response = render(request({'chain': blockchain.chain, 'length': len(blockchain.chain)})) return render(request,JsonResponse(response)) Checking if the Blockchain is valid def is_valid(request): if request.method == 'GET': is_valid = blockchain.is_chain_valid(blockchain.chain) if is_valid: response = render(request({'message': 'All good. The Blockchain is valid.'})) else: response = render(request({'message': 'Houston, we have a problem. The Blockchain is not valid.'})) return render(request,JsonResponse(response)) Adding a new transaction to the Blockchain @csrf_exempt def add_transaction(request): #New if request.method == 'POST': received_json = json.loads(request.body) transaction_keys = ['sender', 'receiver', 'amount','time'] if not all(key in received_json for key in transaction_keys): return 'Some elements of the transaction are missing', HttpResponse(request(status=400)) index = blockchain.add_transaction(received_json['sender'], received_json['receiver'], received_json['amount'],received_json['time']) response = render(request({'message': f'This transaction will be … -
Fetch datetime from one model and post it as a day in another model AP
Need to fetch the Date entered in the below timesheet class api model and export it under another class model api as a day #Model for Date time picking class Timesheet(models.Model): project=models.ManyToManyField(Project) Submitted_by=models.ForeignKey(default=None,related_name="SubmittedBy",to='User',on_delete=models.CASCADE) status=models.CharField(max_length=200) ApprovedBy=models.ForeignKey(default=None,related_name="ApprovedBy",to='User',on_delete=models.CASCADE) Date=models.DateField() Hours=models.TimeField(null=True) def str(self): return self.id #model for import date time as day class Days(models.Model): day_of_date= models.ForeignKey(Timesheet, related_name='date', on_delete=CASCADE) def str(self): return self.date #view for the model class DaywiseViewSet(viewsets.ModelViewSet): queryset=models.Days.objects.extra(where=["EXTRACT(day FROM day_of_date) <= %s"], params=[day_name]) serializer_class = serializers.Daysserializers throwing an error as "django.db.utils.ProgrammingError: can't adapt type '_localized_day'". Need help on creating a day wise report table using inputed date in a model. -
django settings.ABSOLUTE_URL_OVERRIDES requires the whole url to work
I'm maintaining a mezzanine/django application that has a couple of calls of get_absolute_url(). The always fail unless I put the following into my settings.py: ABSOLUTE_URL_OVERRIDES = { 'page_types.basicpage': lambda o: "http://<myHostName>:<myPort>/%s" % o.slug, 'page_types.registerdescpage': lambda o: "http://<myHostName>:<myPort>/%s" % o.slug, 'page_types.uutinen': lambda o: "http://<myHostName>:<myPort>/uutinen/%s" % o.slug, } According to django documentation this should also work ABSOLUTE_URL_OVERRIDES = { 'page_types.basicpage': lambda o: "/%s" % o.slug, 'page_types.registerdescpage': lambda o: "/%s" % o.slug, 'page_types.uutinen': lambda o: "/uutinen/%s" % o.slug, } But it doesn't. How can I get rid of myHostName and myPort in the settings file ? I'm currently working with django 2.2, python 3.7 and Mezzanine 5.0.0, but I've met this same issue with django 1.8, Mezzanine 4.x and python 2.7 -
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