Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: POST Pandas dataframe using API, and Pickle
This is a question building upon How to send a pandas dataframe using POST method and receive it in Hug/other REST API... I believe the answer is not complete and therefore I would like to ask: How do I send the pickled Pandas Dataframe using REST API to a Django Model Database? Below is my try after following the original post, but the object does not save. What do I need to do to make it work? import pandas as pd df = pd.DataFrame({'a': [0, 1, 2, 3]}) import pickle pickled = pickle.dumps(df) import base64 pickled_b64 = base64.b64encode(pickled) Want to send the pickled_b64 object, by POST via API to destination (www.foreignserver.com) import requests r = requests.post('http://www.foreignserver.com/api/DataFrame/', data = {'df_object':pickled_b64}) On Server www.foreignserver.com class DataFrame(models.Model): df_object = models.BinaryField() result: [09/Sep/2019 13:23:53] "POST /api/DataFrame/ HTTP/1.1" 201 64 In Django REST framework HTTP 200 OK Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "url": "http://www.foreignserver.com/api/DataFrame/17/", "df_object": "" } -
Select users from list and add to post request
I have a list of users that all have checkbox next to them. All the users that are selected should be added to the array and then sent to the database via the django post request. Here is a picture of that: The Button at the bottom is the submit button. models: class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) color = models.CharField(max_length=25, default="", blank=True) class Studyplan(models.Model): name = models.CharField(max_length=100, null=True) description = models.CharField(max_length=1000, null=True) parent_assignment = models.ForeignKey(Assignment, blank=True, on_delete=models.CASCADE,related_name="studyplan", null=True) deadline = models.DateField(default=date.today, null=True) students = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_students", null=True) teachers = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_teachers", null=True) canview = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_canview", null=True) notes = models.ManyToManyField(Note, blank=True, related_name="studyplan", null=True) tasks = models.ManyToManyField(Task, blank=True, related_name="studyplan", null=True) messages = models.ManyToManyField(Message, blank=True, related_name="studyplan", null=True) Views: @login_required def skapa_studieplan(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') parent_assignment = Assignment.objects.get(pk=request.POST.get('Studyplan-PAID')) users = UserProfile.objects.all() instance = Studyplan.objects.create(request.POST.get('Studyplan-Canview')) for user in users: instance.canview.add(user) studyplan = Studyplan(name=name, description=description, parent_assignment=parent_assignment, canview=instance) studyplan.save() return redirect('allaStudieplaner') My Problem is that I can't figure out to get the values from a ManyToManyField into a POST request. I get an error similar to this: Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead -
how to fix "Amazon S3 CORS configuration in django"
i am having a problem implementing amazon S3 in my Django web app.i uploaded the media files in the s3 bucket. but whenever I visit the web app, the images don't appear. and when I click open image in another location, then I get this message. "This XML file does not appear to have any style information associated with it. The document tree is shown below." thanks. CORS configurations in AWS3 <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> settings.py AWS_ACCESS_KEY_ID="AKIA3YNRVIBTIO6SMLIB" AWS_SECRET_ACCESS_KEY="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" AWS_STORAGE_BUCKET_NAME="izala" AWS_S3_FILE_OVERWRITE=False AWS_DEFAULT_ACL=None DEFAULT_FILE_STORAGE="storages.backends.s3boto3.S3Boto3Storage" INSTALLED_APPS = [ 'storages', ] -
How to get a username instead of an id?
I want to write a tweeter-like app but I have this wierd message when i'm trying to get the author username instead of the author id. I would like to know how to get that author username properly instead of having this error : NOT NULL constraint failed: tweets_tweet.author_id I first tried to use the get_field method in my seriliazer. Here is the model: class Tweet(models.Model): slug = models.CharField(max_length=100, unique=True, null=True, blank=True) content = models.TextField(max_length=150) datestamp = models.DateTimeField(auto_now_add=True) nb_likes = models.PositiveIntegerField(default=0) nb_comments = models.PositiveIntegerField(default=0) author = models.ForeignKey( User, on_delete = models.CASCADE, related_name = "tweets", related_query_name = "post", null=False ) def save(self, *args, **kwargs): self.slug = slugify(self.content[:10]) + '-' + randomString() super(Tweet, self).save(*args, **kwargs) Here is my Serializer : class TweetSerializer(serializers.ModelSerializer): author = serializers.SerializerMethodField() def get_author(self, obj): return obj.user.username class Meta: model = Tweet fields = ["content", "author", "nb_likes", "nb_comments", "slug"] def to_representation(self, obj): representation = super().to_representation(obj) if obj.nb_likes > 50: representation['super_popular'] = True return representation -
Cloning all objects in a table to different table django
I have a (Django/Postgresql) project that has lots of tables with foreignkeys and manytomany fields. I should create new tables derivatives of these tables. I have some restrictions for objects to clone and I should change foreignkeys and manytomany ids because my new tables have relations with each other. You can say that: TableA: Item(TableB) Item(TableC) TableB: Item(TableA) TableC: I should do like: TableA_1: Item(TableB_1) TableB_1: Item(TableA_1) TableC: None What happened is I have changed foreignkeys and remove some items that does not apply to my restrictions. Is there a fast way to do it? I am doing it using django pagination and serializer, then change all foreignkeys and manytomany keys. It is a very slow process. -
Error running inspectdb command for database in redshift
I am working to execute the inspectdb command in redshift. I have installed psycopg2 and django-redshift-backend and when doing the db inspect I get this error: # Unable to inspect table 'TABLE_REDSHIFT' # The error was: syntax error at or near "WITH" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... -
django app on apache error: sec_e_invalid_token
Hello guys I'm trying to deploy my django app on apache on windows server 2008 R2 but I'm getting an error curl: (35) schannel: next InitializeSecurityContext failed: SEC_E_INVALID_TOKEN (0x80090308) - The token supplied to the function is invalid. Been stuck with this prob for a while can anyone help me ? -
Django Background tasks vs Celery
I am trying to do some tasks in django that consume alot of time. For that, I will be running background tasks. After some R&D, i have found two solutions: Celery with RabbitMQ. Django Background tasks. Both options seem to fulfill the criteria but setting up Celery will require some work. Now as far as the second option is concerned, setup is fairly simple and in fairly quick amount of time, i can go on writing background tasks. Now my questions if i adopt the 2nd option is this: How well does Django Background tasks perform ? (Scalability wise in Production environment). Can i poll the tasks (after some time) in DB to check the task's status? Architecture of Django-Background-tasks? Couldn't find any clear explanation about it's architecture (Or have I missed some resource?) Again coming to the first point, how well does Django Background tasks perform in production. (Talking about prior experience of using this in prod.) -
Get data from python backend
I'm running web application and i need to call specific python function, that returns some data. I am trying some AJAX, but I am not sure, how to call specific function. Any advice? -
How write django views based on sparql results from an ontolgy?
I have built a Django web application that takes in a textual description of a system. I then used natural language processing to extract specific textual information. The extracted information is then populated (as individuals) into an ontology (.owl) using a Owlready2. Once the ontology is populated, I can run SPARQL queries. Now, I would like to display the query results in a template via class base view. Currently, I dont know where to start with a solution. I can only think of converting the query results to json and the put it in the class based view. Below is some code to get the SPARQL results. from owlready2 import * import owlready2 owlready2.JAVA_EXE = "mypath" world = World() world.get_ontology("file://C:\\mypath\\RDFContext_Test.owl").load() sync_reasoner(world) print(world) graph = world.as_rdflib_graph() r = graph.query(""" PREFIX UC: <http://www.semanticweb.org/name/ontologies/2018/8/untitled-ontology-2#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> prefix xsd: <http://www.w3.org/2001/XMLSchema#> select ?use_case ?flgroup where { ?use_case UC:hasGoal "V" . ?use_case UC:hasFlowGroup ?flgroup. ?flgroup a UC:SpecificAltFlowGroup .}""") However, I dont know where to go from here to display it in the template. Can some point me in the right direction? -
How To Secure Third Party API data using Django?
I'm using a third party API Key for my website. I have done some modification on that API and now I'm using it for my own site. I want to secure that API data by adding a restriction on any user (Authenticated or Anonymous ). I want to add a time limit on the data provided by the API. So, if anybody uses the same data after a certain period of time then it will show an error. As well as I want some restrictions on users IP. So, a user can access my website a fixed number of time. -
How to make true query in django_elasticsearch_dsl like icontains in django?
Need using django_elasticsearch_dsl search by given text. It should works as for full word and for only part of world. Like for "Example" and "xample". Using python 3.6, django_elasticsearch_dsl 7.0 Have found in documentation that django "icontains" query is similar to "match_phrase" in elasticsearch_dsl.query, but seems it does not work for me. titles = TitleDocument.search().query( Q("match", title=kwargs['text']) or Q("match", slug=kwargs['text']) or Q("match", page_title=kwargs['text']) or Q("match_phrase", menu_title=kwargs['text']) or Q("match_phrase", meta_description=kwargs['text']) ) Does not work for part of word (ex. "neve", full is "never") But Django query works good ti = Title.objects.filter(meta_description__icontains=kwargs['text']) Use only one field to filter by just for example I expect to find something looks like django icontains filter. Need to find not only for full word match. -
Error when handling multiple forms in the same View
I'm trying to create a view that handles two forms with models related by a ForeignKey. The purpose of this form is to add a Bedroom and the Lights related to that Bedroom on the same page. #views.py def add_bedroom(request, pk): get_property_id = pk data = {'property':get_property_id} property_reference = Property.objects.get(pk=get_property_id) if request.method == 'POST': bedroom_form = AddBedroomForm(request.POST, request.FILES, initial=data) lighting_form = LightingBedroomAddForm(request.POST) if bedroom_form.is_valid() and lighting_form.is_valid(): bedroom = bedroom_form.save() add_lighting = lighting_form.save(commit=False) add_lighting.bedroom = bedroom add_lighting.save() return HttpResponseRedirect(reverse('properties:property_detail', args=[pk])) else: print('Error') bedroom_form = AddBedroomForm(initial=data) lighting_form = LightingBedroomAddForm() context = { 'add_bedroom_form':bedroom_form, 'add_lighting_form':lighting_form, 'title':"Add Bedroom", 'reference':property_reference, } return render(request, 'properties/add-bedroom.html', context) For some reason it doesn't work and my guess is that when I assign this add_lighting.bedroom = bedroomit doesn't get the id value. I get the POST printed but it just reloads the page(I don't have validation errors). What am I doing wrong here? I've checked this Link1 and this Link2 #models.py class Bedroom(models.Model): type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50) bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30) image = models.ImageField(null=True, blank=True) ensuite = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE, related_name='bedroom') def __str__(self): return str(self.pk) class LightingBedroom(models.Model): type = models.CharField(db_column='Type', choices=LIGHTING_TYPE_CHOICES, max_length=30) bulb_type … -
how to check if a user is logged in when using third party login system?
I have a web app which is based on django (version 2.0+), the user can only login with third party authentication. My question is like, can I still use the technique like: "if request.user.is_authenticated():" (https://stackoverflow.com/questions/3644902/how-to-check-if-a-user-is-logged-in-how-to-properly-use-user-is-authenticated) to see if user is logged in? Some background: After third party login, user profile is available. At the moment the structure of the database is still at design phase. -
Calculating income and expenses per month
Hello developers How to calculate income with date .For example income of last month income of last year and income of this month. models.py class Add(models.Model): income = models.IntegerField(blank=True, null=True) expense = models.IntegerField(default=0) date = models.DateTimeField(default=timezone.now, null=True, blank=True) -
Django Query for two related models
I have an Order model that is related to Booking model as ForeignKey field. So, an Order can be related to multiple Booking objects. class Order(models.Model): shop=models.ForeignKey(Shop, on_delete=models.CASCADE, blank=True, null=True) user=models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, blank=True, null=True) order_id=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4) order_date=models.DateField(default=date.today) class Booking(models.Model): order=models.ForeignKey(Order, on_delete=models.CASCADE, blank=True, null=True) service=models.ForeignKey(Service, on_delete=models.CASCADE, blank=True, null = True) My goal is to show Order with the related Booking objects like this: <ul> {% for order in orders %} <li>{{ order.order_id }}</li> <ul> {% for booking in BOOKINGS WITH THIS ORDER ID %} <li>{{ booking.service }}</li> {% endfor %} </ul> {% endfor %} </ul> In the template, with in each order, I want to be able to loop through bookings with that order id. I am having trouble figuring out how to make the proper query to achieve that in the template. I thought about creating a dictionary object to store and pass the related booking object details, but this does not seem to be the proper way to do this. def shopDashboardPastBookings(request): orders = Order.objects.filter(shop_id = shopID ).exclude(order_date__gte = (datetime.now() - timedelta(days=1)) ) bookings = {} for order in orders: booking_query = Booking.filter(order = order ) bookings[order.order_id] = booking_query // should I be making separate queries for … -
How to receive user input from FilteredSelectMultiple widget?
I am trying to create form using FilteredSelectMultiple widget. I managed to get it showing on my page, but faced difficulties receiving user input from it. For now, after I click submit button page just refresh and shows same form again instead of going to designated page. What I am doing wrong? My code so far: forms.py class DrgSkaiciuokle(forms.Form): drg_pasirinkimas = forms.ModelMultipleChoiceField(queryset=DRGkodas.objects.all(), label="Pasirinkite atvejį sudarančius DRG", widget=FilteredSelectMultiple("DRG kodai", is_stacked=False), required=True) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) #I have no idea if this part is right: def clean_drg_pasirinkimas(self): drg_pasirinkimas = self.cleaned_data['drg_pasirinkimas'] return drg_pasirinkimas views.py def DRG_skaiciuokle(request): if request.method == 'POST': form = DrgSkaiciuokle(request.POST) pasirinkti_DRG = form.cleaned_data['drg_pasirinkimas'] context = { 'pasirinktiDRG': pasirinktiDRG, } #This page should be opened after submitting form instead of refresh return render(request, 'DRGskaiciuokle_valid.html', context) else: form = DrgSkaiciuokle() context = { 'form': form, } return render(request, 'DRGskaiciuokle.html', context) my html file: {% extends "base_generic.html" %} {% block content %} <div id='frame'> <div id='sk_head'> <h3>Kaštų konvertavimo skaičiuoklė</h3> <h4>Pagal DRG metodiką</h4> </div> <form> <div id='sk_body'> <fieldset> <legend>Įveskite duomenis</legend> <form action="" method="post"> {% csrf_token %} <table> {{ form.media }} {{ form.as_table }} <script type="text/javascript" src="{% url 'jsi18n' %}"></script> </table> <input type="submit" value="Skaičiuoti"> </form> </fieldset> </div> </form> … -
Invalidating cached AJAX response when session changes
Server-side, Django is caching a certain view we always load with AJAX, based on whether the user role changes, which is passed through headers. Using Vary headers for this: url(pattern, cache_page(CACHE_TIMEOUT)(vary_on_headers('USER_ROLE')(MyView.as_view())), name='myview') Here's how the header is sent: $.ajax({ url: url, cache: true, beforeSend: request => request.setRequestHeader('User-Role', document.USER_ROLE), success: response => loadView(response) }); Where document.USER_ROLE is set in a relevant place on page load and its values are different strings based on whether the user is logged in or not, and on their role. Then, as you can see, client-side we are also caching the response. This means if the user logs in or logs out they will get a non-pertinent cached version of the view. Therefore I need some way to invalidate the client cache, that is, to pass cache: false if the user role changes. I have thought of using a cookie: // get current user role on page load before making the ajax request // compare role to the last, stored in a cookie, and if changed, disable caching document.USER_ROLE = '{{ user.role_str }}'; document.SHOULD_CACHE_VIEW = true; const lastUserRole = Cookie.get('lastuserrole'); if (document.USER_ROLE !== lastUserRole) { Cookies.set('lastuserrole', document.USER_ROLE); document.SHOULD_CACHE_VIEW = false; } And then we can use … -
Django Form is not valid but not giving me an error
In the below form If I uncomment "Product" field my form is not working.I think there is something wrong with my html file. I am not including whole model code only the neccessary code. lead/models.py class Lead(models.Model): address_line = models.CharField(_("Address"), max_length=255, blank=True, null=True) street = models.CharField(_("Street"), max_length=55, blank=True, null=True) city = models.CharField(_("City"), max_length=255, blank=True, null=True) state = models.CharField(_("State"), max_length=255, blank=True, null=True) postcode = models.CharField(_("Post/Zip-code"), max_length=64, blank=True, null=True) country = models.CharField(max_length=3, choices=COUNTRIES, blank=True, null=True) website = models.CharField(_("Website"), max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) assigned_to = models.ManyToManyField(User, related_name='lead_assigned_users') account_name = models.CharField(max_length=255, null=True, blank=True) tags = models.ManyToManyField(Tags, blank=True) contacts = models.ManyToManyField(Contact, related_name="lead_contacts") ctype = models.CharField(default=None,max_length=20, choices=TYPE, blank=True, null=True) product = models.CharField(default=None,max_length=255, blank=False, null=True) common/models.py class Products(models.Model): name = models.CharField(max_length=50,null=False,blank=False) def __str__(self): return self.name lead/view.py @login_required def create_lead(request): template_name = "create_lead.html" users = [] if request.user.role == 'ADMIN' or request.user.is_superuser: users = User.objects.filter(is_active=True).order_by('email') elif request.user.google.all(): users = [] else: users = User.objects.filter(role='ADMIN').order_by('email') form = LeadForm(assigned_to=users) if request.POST: form = LeadForm(request.POST, request.FILES, assigned_to=users) if form.is_valid(): lead_obj = form.save(commit=False) lead_obj.created_by = request.user lead_obj.save() if request.POST.get('tags', ''): tags = request.POST.get("tags") splitted_tags = tags.split(",") for t in splitted_tags: tag = Tags.objects.filter(name=t) if tag: tag = tag[0] else: tag = Tags.objects.create(name=t) lead_obj.tags.add(tag) if request.POST.getlist('assigned_to', []): lead_obj.assigned_to.add(*request.POST.getlist('assigned_to')) assigned_to_list = … -
find and quickly solve the production problem
usually in code without putting in production each time verifies that it works well. but at the time of production in heroku we always have an error if we write heroku logs --tail we always have the same static files but usually it's a library not well installed but use. generally to find the error one checks requirements.txt and the documentation and the code there is not a faster method -
Custom registration form. Confirm password
I used custom form for register users. I want do validation for confirm password. forms.py: class RegistrationForm(UserCreationForm): '''Register for new users''' email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = get_user_model() fields = {'username', 'password1', 'password2', 'email', 'first_name', 'last_name'} def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user template: <div class="input-group register"> {{ form.password.errors }} <label for="id_password1">Password: </label> {{ form.password1 }} </div> <div class="input-group register"> {{ form.password.errors }} <label for="id_password2">Confirm password: </label> {{ form.password2 }} </div> views.py def registration_view(request): context = {} context.update(csrf(request)) context['form'] = RegistrationForm() if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() newuser = auth.authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password2'] ) auth.login(request, newuser) return redirect('home') else: context['form'] = form return render(request, '/registration.html', context) How can I add validation for password(also confirm password)? -
upload base64 video file using django
I have a user model that i want to add a video field to it, i used Base64ImageField to upload the image for the user and PDFBase64File for the files implementing Base64FileField, so i want VIDEOBASE64File validator for the video to accept video types like mp4, ...etc class PDFBase64File(Base64FileField): ALLOWED_TYPES = ['pdf'] def get_file_extension(self, filename, decoded_file): try: PyPDF2.PdfFileReader(io.BytesIO(decoded_file)) except PyPDF2.utils.PdfReadError as e: return 'non-valid' return 'pdf' I want a validator for the video to accept certain extension of videos. -
Django - how to redirect the first logged in user to a loading page
Definition of The first logged in user: the first one to authenticate, meaning no one else in that moment is logged in except him. This django webapp needs to rely on a third parties rest api (Microsoft powerbi), which get paid per minute, but it also provide the possibility to turn on and off the server programmatically with a rest api call to azure. The most obvious way to turn on and off the server, it seems to be to react at the first login and the last logout. The issue here, is that the server needs about 30 seconds to start. And I need to redirect the user to a "loading" page, and when server is up, i would redirect him again to the home page. currently, I detect the first login with a receiver, in my views.py I have: @receiver(user_logged_in) def sig_user_logged_in(sender, user, request, **kwargs): print("user logged in: %s at %s" % (user, request.META['REMOTE_ADDR'])) queryset = get_current_users() if queryset.count() == 0: headers_capacity = azure_auth_capacity() print("resuming capacity...") resume_pbi_capacity(headers_capacity) print("redirecting to loading page...") # Both following tries to redirect does not work #return '/loading/' #return render_to_response("loading.html") Here I would redirect the user to a loading page as you see, since … -
How can I have the fields for each language shown using Django Forms and django-modeltranslation?
I have a Model with fields available in English and another language e.g. title and title_langcode. I have a Django Form that allows users to edit the fields of a model, based upon the TranslationModelForm from django-modeltranslation. The user needs to be able to enter details for the field in both languages, so there is a Textbox for title and title_langcode. At the moment, only title is appearing as that is all that is present in Fields. How can I let the user edit both language fields in the same form? -
Function to copy fields from a model to another model in django
I want to merge 2 different models with different but overlapping fields. I try to write a function that copy the fields with its data from model A to model B. def create_field(): old = DetailItem.objects.all() new = CrawlItem.objects.all() for item in old: c = CrawlItem.objects.get(title=item.title, description=item.description, link=item.link, cpvcode=item.cpvcode, postalcode=item.postalcode ) c.save() and i don't know whereis the mistake. I want to have a model that contains the data from the old model and some new fields. Here is my code for the two models: class DetailItem(Base): title = models.CharField(max_length=500) description = models.CharField(max_length=20000) link = models.URLField() cpvcode = models.ManyToManyField('CPVCode',related_name='cpv') postalcode = models.ForeignKey('PostalCode',on_delete=models.SET_NULL,null=True,blank=True,related_name='postal') def __str__(self): return self.title class CrawlItem(Base): guid = models.CharField( primary_key=True, max_length=500) title = models.CharField(max_length=500) link = models.URLField() description = models.CharField(max_length=2000) pubdate = models.DateTimeField() detail = models.ForeignKey('DetailItem',on_delete=models.SET_NULL,null=True,blank=True,related_name='crawldetail') def __str__(self): return str(self.title) This is what I want to get: class CrawlItem(Base): guid = ... title = ... link = ... cpvcodes = ... postalcode = ... pubdate = ... vergabestelle = ... vergabeart = ... anmeldefrist = ... description = ... Any ideas how to get there are highly appreciated!