Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a link to my React app from a Django template
I am in the process of converting some Django apps to React but am having issues with something I thought was simple. I need to link directly to my react blog post app. Back when my blog app was a Django app I would link it like this: <a href="{% url 'posts:details' 'title_of_blog_post' %}" class="alert-link"> Click here</a> Now that my app is a react app, I need to link to the specific blog post without using the full external link. The only way I've been able to link to the app is to use href="{% url 'posts-list' %}", but this just takes me to the landing page of the post app and not the specific post I need to render. App.js class App extends Component { render() { return ( <BrowserRouter> <Switch> <Route exact path='/posts/create' component={PostCreate}/> <Route exact path='/posts/' component={Posts}/> <Route exact path='/posts/:slug' component={PostDetail}/> <Route component={Posts}/> </Switch> </BrowserRouter> ); } } posts.urls.py path('', views.PostListCreateAPIView.as_view(), name='list-create'), re_path(r'^(?P<slug>[\w-]+)/$', views.PostDetailAPIView.as_view(), name='detail'), MySite.urls.py re_path(r'^posts/', TemplateView.as_view(template_name='posts/react.html'), name='posts-list'), path('walking', TemplateView.as_view(template_name='posts/walking.html')), path('api/posts/', include('posts.urls')), Any help you could provide would be much appreciated! -
How to make dropdown list to be appeared in dropdown menu form?
I have made a dropdown menu in django so that a user could select one option and it is working but whenever I click on dropdown menu, all the contents hide itself except the one I hover a mouse on it. How to make all appear so that it shows me?? forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image','payment_method','detail'] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) payment_method = models.CharField(max_length=10, choices=Paymet_choices) profile.html {{p_form|crispy}} -
Is there DRYer to get Detail View information from ForiegnKey and ManyToManyRelationships
I am creating a website which will require lots of detail on the bottom of each instance. I am currently having to write custom implementations for each related instance. Is there a way to write a function which will help me reduce the amount of code i am using? I have tried using getattr on model instances but can't seem to get it to work, perhaps someone can help? This is what i am currently using to pass data into the template. Each time the data dict is reset a new detail section is passed into the template and these are the chunks i would like to modulirise into a method call. def get_detail_fields(self): field_values = list() data = dict() data['headings'] = ['name', 'address', 'number'] for parent in self.parents.all(): data[parent.name] = [parent.name, parent.address.get(), parent.number] field_values.append(('parents', data)) for course in self.courses.all(): if course.find_next_course_instance(): data = dict() data['headings'] = ['session', 'name', 'start_date'] data[course] = [course, course.name, course.start_date] field_values.append(('course', data)) if self.competency: data = dict() data['headings'] = ['name', 'stage level', 'description'] competencies = self.competency.all() for competency in competencies: data[competency.name] = [competency.name, competency.stage_level, competency.description] field_values.append(('Competencies', data)) return field_values And this is what my tempalte is looking like <table> <tr> {% for heading in value.headings … -
Limit amount of foreign keys, each one referring to a day of the week
Let's say I have two models in my app: Car and CarAvailability. class Car(Model): availability = ForeignKey(CarAvailability) class CarAvailability(Model): WEEKDAYS = ( ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday') # ... basically all the days of the week ) day = CharField(max_length=20, choices=WEEKDAYS) What are my options to limit the amount of foreign keys (availability attribute) to a maximum of 7 and make sure of only one per weekday. I don't know if I'm making myself clear enough here, let me know if anything. -
Django view doesn't save model instances but running the functions correctly?
I have a function that process images that are uploaded by users. I made a view that when entered apply the function on the uploaded images. models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.FileField(upload_to = user_directory_path , verbose_name = 'Image') class Processed(models.Model): uploaded_image = models.ForeignKey(UploadedImages,on_delete=models.CASCADE,related_name='processed') analysedimage = models.ImageField(upload_to=analyses_directory_path, verbose_name='analysed Image', blank=True) views.py def AnalysedDetails(request,pk=None): Uimage = get_object_or_404(models.UploadedImages,pk=pk) analysed = models.Processed(uploaded_image=Uimage,analysedimage=main(Uimage.pre_analysed.path)) analysed.save() return HttpResponse("OK") but when i check the admin page to see the model it only saves the uploaded image and doesn't save the processed one and when I check the directory i find that only the uploaded image field is saved. I tried analysed=models.Processed(uploaded_image=Uimage.pre_analysed,analysedimage=main(Uimage.pre_analysed.path)) but it returns Cannot assign "": "Processed.uploaded_image" must be a "UploadedImages" instance -
How to set cookies on Client Server in CORS request
I have a React Frontend Client at foo.com and a Django Backend server at bar.com.I am using Django's Session Authentication for logging in.When the client at foo.com makes a CORS login request to bar.com ,the Backend server successfully sends the Set-Cookie Headers(csrftoken and sessionid) in the response but these cookies are set for Domain bar.com i.e for Backend domain.I want these cookies to be set for my Frontend domain i.e foo.com.How can I achieve this? -
why the response so slowly when first request to drjango server
Now i make prediction using tensorflow inside django .And there is one issus when i test.When django server is started,and the response from django server is so slowly when first request,it is hunted by sessison.run.And it is fast when make second,third request,how to fix this issue about first request slowly. I tried to add some tf app function ,but it doesn't work genfun=get_batch_generator(data_list) fo = codecs.open("./result", "w","utf-8") for input_data,y_true in genfun: y_pred = sess.run(pred, feed_dict={'text_left:0': input_data['text_left'],'text_right:0': input_data['text_right']}) for y in y_pred: fo.write(str(y[1])+"\n") sess are defined the outer file when run python manage.py runserver command class NNmodel(object) : ins_ = None @classmethod def instance(cls) : cls.ins_ = cls.ins_ if cls.ins_ else NNmodel() return cls.ins_ def __init__(self): self.flag_ = False self.pred = None self.sess = None def load(self,nn_model_file) : if self.flag_ == True : return self.flag_ = True gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3) self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options,allow_soft_placement = True)) with tf.gfile.FastGFile(nn_model_file, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) self.sess.graph.as_default() tf.import_graph_def(graph_def, name='') # Get graph graph = tf.get_default_graph() self.pred = graph.get_tensor_by_name("dense_9/Softmax:0") the response is so slow when make first request -
Django transaction.commit_on_success rolling back even though exception is not raised
I have a scenario where a transaction.commit_on_success() is being rolled back after the code block finishes execution without raising error. The DataBaseError is being caught and retried explicitly within that transaction. If there are 10 requests coming in simultaneously, for the one's where the retry executes, rollback happens for those objects even though a voucher is served in the first retry. Assuming I have brand, amount and currency already, below is my code base def get_coupon_code(brand, currency, amount, retry=4) try: qs = VoucherCode.select_for_update().filter( brand=brand, currency=currency, amount=amount ).values('id', 'voucher_code').order_by('id')[:1] try: return qs[0] except IndexError: return None except DatabaseError as err: if retry and hasattr(err, 'args') and err.args[0] == 1213: retry -= 1 time.sleep(4) return self.get_coupon_code( brand=brand, currency=currency, amount=amount, retry=retry) else: raise err try: with transaction.commit_on_success(): object = Coupon.objects.create(brand=brand) voucher_code = get_coupon_code(brand, currency, amount) object.voucher_code = voucher_code return object except Exception as error: raise MyCustomException() -
How to allow rendering view only if accessed via iframe from specific domain in Django?
I have a Django view which I want to be accessible only from an iframe inside a webpage inside domain.com. I don't want it to be accessible directly nor from any other domain. Here are a list of use cases: If user tries to access view directly in my website, a Forbidden error is thrown. If user goes to www.domain.com and the webpage contains an iframe pointing to my view, the content of the view is displayed. If user tries to copy same iframe code and paste it on another webpage from a different server, even if the server is pretending to be www.domain.com, he gets a forbidden error. Any other hacky way rather than use case 2 gets forbidden error. Is it possible to do this? How can it be done? I know of the X-Frame-Options: allow-from https://example.com/ header, but first, this doesn't block direct access, second is it hacker safe? -
Send mass emails with multiple tasks or one task with time.sleep?
I want to write a Python Script in Django with Celery that is responsible for sending a lot of emails. Let's say about 300 emails. Once I trigger this function it should send this emails to specific customers. Since I have some rating limits (5 emails/second) on my email provider who is responsible for sending this emails I need to send the emails in chunks. Is it better do create a separate task for every email chunk like this: for chunk in chunks: send_five_emails.apply_async(countdown=1) @task def send_five_emails(...): pass Or is it better to create one task with a sleep function inside it: send_emails.delay() @task def send_emails(...): for chunk in chunks: time.sleep(1) send_five_emails() -
Django: best practice to define dependencies between your settings?
I'm using environment variables for my settings in Django. For example: EMAIL_BACKEND = os.environ['DJ_EMAIL_BACKEND'] EMAIL_HOST = os.environ.get('DJ_EMAIL_HOST') EMAIL_HOST_USER = os.environ.get('DJ_EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('DJ_EMAIL_HOST_PASSWORD') EMAIL_PORT = os.environ.get('DJ_EMAIL_PORT') As you can see here, EMAIL_BACKEND is required, not the 4 other variables. However, when EMAIL_BACKEND has a value like dummy (e.g to test in local), the 4 other variables are not required to be set. However, I'd like to find a clean way to conditionally force to set these 4 variables according to the value of the first one. A dummy version could be something like: EMAIL_BACKEND = os.environ['DJ_EMAIL_BACKEND'] if EMAIL_BACKEND == "django.core.mail.backends.smtp.EmailBackend": EMAIL_HOST = os.environ['DJ_EMAIL_HOST'] EMAIL_HOST_USER = os.environ['DJ_EMAIL_HOST_USER'] EMAIL_HOST_PASSWORD = os.environ['DJ_EMAIL_HOST_PASSWORD'] EMAIL_PORT = os.environ['DJ_EMAIL_PORT'] else: EMAIL_HOST = os.environ.get('DJ_EMAIL_HOST') EMAIL_HOST_USER = os.environ.get('DJ_EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('DJ_EMAIL_HOST_PASSWORD') EMAIL_PORT = os.environ.get('DJ_EMAIL_PORT') Can you think of a less verbose, more organised way to do this? Thanks. -
How can I see user information other than the logged-in user in Django?
I'm using Django 2.2 and PostgreSQL. After logging in, the user has a page where they can see other users' information. However, all users' login information appears on the page. I want to see information from other users except him. How can I do that? templates/neighbor.html {% csrf_token %} {% if neighbor_list %} {% for neighbor in neighbor_list %} <div class="card border-left-success py-2" style="background-color: rgb(240,240,240);"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-left"> <strong><p><a href="{% url 'store:neighbor_detail' neighbor.user.username %}">{{neighbor.user.first_name}} {{neighbor.user.last_name}}</a></p></strong> <p><strong><i class="fa fa-user"> : </i></strong>{{neighbor.user.username}}</p> <p><strong><i class="fa fa-envelope"> : </i></strong>{{neighbor.user.email}}</p> <p><strong><i class="fa fa-phone"> : </i></strong>{{neighbor.phone}}</p> <p><strong><i class="fa fa-fax"> : </i></strong>{{neighbor.fax}}</p> {% if neighbor %} <p><strong><i class="fa fa-map"> : </i></strong>{{neighbor.neighborhood}}, {{neighbor.avenue}}, {{neighbor.street}}, {{neighbor.block}}, No.{{neighbor.number}}, Kat.{{neighbor.storey}}, {{neighbor.district}}/{{neighbor.province}}</p> <p>{{neighbor.profile_image}}</p> {% endif %} </div> </div> </div> </div> </div> {% endfor %} {% endif %} store/views.py from store.models import StoreOtherInfo def neighbor(request): neighbor_list = StoreOtherInfo.objects.all() return render(request,'store/neighbor.html',{"neighbor_list":neighbor_list}) -
How can I rename a field in django using an input field
I have an app that allows people to renames files. Issue is I haven't got much idea on how to do this yet. I want a user to be able to hover over the file of choice, then type in a new file name and then click enter and then that name they enter would rename that file. HTML: {% for video in videos %} {% if video.active %} <div class="folder"> <div class="folder-settings-tool" onclick="folderSettings(this)"> <!-- CHANGE COLOUR OF THE SETTINGS COG TO WHITE --> <img src="{% static 'public/image/icons/settings-work-tool.svg' %}"> </div> <div class="folder-settings"> <div class="title-change"> <p class="title-rename">RENAME</p><input type="text" name="title"> </div> <div class="archive"> <p class="archive-text"> ARCHIVE </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> <div class="make-final"> <p class="archive-text"> MAKE FINAL </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> <div class="downloadable"> <p class="archive-text"> DOWNLOADABLE </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </div> </div> <a href="{% url 'public:file_detail' model='video' pk=video.pk %}"> <div class="folder-text"> <p>VIDEO</p> </div> <div class="image"> <img src="{% static 'public/image/icons/folders.svg' %}"> </div> <div class="folder-info"> <div class="folder-title"> {{ video.title }} </div> <div class="folder-date"> <p><span class="folder-created">Created</span> {{ video.created }}</p> </div> </div> </a> </div> {% endif %} {% endfor %} Models: class Folder(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='%(class)ss_created', verbose_name … -
how do i generate a chart from this data
im setting up a system that records users who visit different pages on my site, but i have failed to plot a graph that shows how many visit which pages i have managed to capture the different users in the database but now retrieving them and plot them on the graph depending on what page they have viewed is an issue '''reports.py''' get_client_ip(request, action="Analytics page", description="User accessed the analytics page.") return render(request, "search.html", {"view":"reports", "home_page":home_page, "specie_page":specie_page, "login_page":login_page, "advanced_page":advanced_page, "sign_up_page":sign_up_page, "activation_page":activation_page, "specie_download":specie_download, "analytics_page":analytics_page}) ''' i expect it to plot a graph from the results but i dont know how to do it -
Django Nested Views
I'm developing an internal application and I would like to be able to nest my views to keep everything nice and organized. I plan on doing this by keeping different parts of the page in their own HTML files with their own Views (separate sidebar and navbar, separate charts, etc). views.py from django.shortcuts import render from django.views.generic import TemplateView import Recall.data_logger.models as DLM class ReportHome(TemplateView): template_name = 'data_logger/index.html' class SelectorSidebar(TemplateView): template_name = 'data_logger/sidebar.html' def get(self, request, *args, **kwargs): companies = DLM.Company.objects.order_by('company_name').all() return render(request, self.template_name, {'companies':companies,}) index.html <html> <head></head> <body data-gr-c-s-loaded="true"> {% include 'data_logger/navbar.html' %} <div class="container-fluid"> <div class="row"> {% include 'data_logger/sidebar.html' %} <!-- This is the part I need help with--> </div> </div> </body> </html> sidebar.html <div class="col-sm-3 col-md-1 sidebar"> <ul class="nav nav-sidebar"> {% for company in companies %} <li><a href="#">{{ company.company_name }}</a></li> {% endfor %} </ul> </div> I understand that by just using {% include 'data_logger/sidebar.html' %} it's just loading the HTML and bypassing SelectorSidebar, how do I direct it through the View? -
Use S3 in Django to store media files (minio)
I currently try to integrate S3 as storage backend (django-minio-storage - https://github.com/py-pa/django-minio-storage) for media files and also for static files. With static files i have no problems at all but if i want to upload media files i get form validation errors and stuff like that. Thats the first thing with media files, the second is that for some reason if i place the file at the template django returns a local path instead of the path to the s3 service (minio) as it also does for static files, im not really sure where this behaviours comes from but it might be a problem of how i process the return of the saved file path. models.py def get_file_path_user_avatar(filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join('user_avatar', filename) class User(AbstractBaseUser): user = models.CharField(verbose_name='Username', max_length=15, unique=True) bio = models.TextField(verbose_name='Bio', blank=True, null=False, max_length=1000) avatar = models.ImageField( null=False, blank=True, upload_to=get_file_path_user_avatar, validators=[default_image_size, default_image_file_extension], ) ... the funny fact is that im able to upload the file at the django admin backend but not at my frontend, the form does not validate here (but the files gets saved anyways). this is how i display the avatar image: template.html: <img class="avatar" src="/media/{{ user.avatar }}"> … -
Django login auth always redirect me to accounts/profile?
I'm tried to separate authentication logic in different app, called users, code: project_base_app/urls.py: path('users/', include('users.urls')), users/urls.py: from django.urls import path, re_path, include from . import views urlpatterns = [ path('', include('django.contrib.auth.urls')), path('profile/', views.redirect_to_user_profile, name='redirect-user-profile'), re_path('profile/(?P<pk>\d+)/', views.UserProfileView.as_view(), name='user-profile'), ] users/views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.views import generic from django.contrib.auth.models import User # Create your views here. def redirect_to_user_profile(request): url = '/profile/' + request.user.id return HttpResponseRedirect(redirect_to=url) class UserProfileView(generic.DetailView): model = User template_name = 'user_profile.html' Then I hit host/users/login it load form, I'm login and it always redirects me to host/accounts/profile/ how can I change it ? -
Generate list of response messages in django-rest-framework
I'm creating an API using django-rest-framework. I intend to auto generate api clients for a couple of languages via openapi-generator from the openapi schema. django-rest-framework allows to generate an api schema through ./manage.py generateschema. Unfortunately the schema has (at least) two shortcomings: Responses don't have descriptions The schema shows response code 200 only Is there an obvious solution that I'm missing or do I have to adapt this this hack for django rest swagger from May 2017 somehow? This is the relevant code from a minimal application: #models.py from django.db import models class MyModel(models.Model): name = models.CharField(max_length=50) #serializers.py from rest_framework import serializers from . import models class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.MyModel fields = ['name',] #views.py from django.shortcuts import render from rest_framework import viewsets from . import models, serializers class MyModelViewSet(viewsets.ModelViewSet): queryset = models.MyModel.objects.all() serializer_class = serializers.MyModelSerializer #./manage.py generateschema > schema.yaml ; cat schema.yaml paths: /mymodel/{id}/: delete: operationId: destroyMyModel responses: '200': content: application/json: schema: required: - name properties: name: maxLength: 50 type: string parameters: - name: id required: true in: path schema: type: string description: A unique integer value identifying this my model. put: operationId: updateMyModel responses: '200': content: application/json: schema: required: - name properties: name: maxLength: 50 type: … -
Run second Django for git pull
I use in my project(not my decision): python==2.7, Django==1.11.5, django-background-tasks==1.1.11 I want to update the server with git pull. I want to use a copy of the server to handle requests while the server restarts. How can I do this? How can I check that the tasks of runserver and background_tasks have ended? I'm new in CI and I don't know how to start and do it right. -
Axis / Key issues merging three dataframes into one
I'm trying to merge three (but really $n number of) dataframes of amortization tables into one table where the month is the primary axis. For instance a 360 month loan1 could start on May 1 2019, a 360 month loan2 could start on Sep 2 2019, and a 360 month loan3 could start on Jan 1 2019. When merging the dataframes the first column should be the first month across any of the dataframes and the last column should be the last month of the last month. I would expect blank or NaN values for months where a loan isn't active. When merging, I can't seem to get Months to be the Dataframe key. I have a function that grabs loans, builds amortization tables as dataframes, and puts them into a list. def buildLoanTable(): loans = Loan.objects.all() df=[] for l in loans: df.append(amortization_table(float(l.amount),float(l.rate),l.total_term/12, start_date=l.start_date)) for idx,d in enumerate(df): df[idx] = d.drop(columns=['Period']).T df = pd.concat(df, axis=1, ignore_index=True, sort=False) return df I've tried all sorts of variations of: df = pd.concat(df, axis=1, ignore_index=True, sort=False) df = pd.concat(df, axis=1, keys=(['Month']), ignore_index=True, sort=False) [ 0 1 2 ... 358 359 360 Month 2019-05-01 00:00:00 2019-06-01 00:00:00 2019-07-01 00:00:00 ... 2049-03-01 00:00:00 2049-04-01 00:00:00 2049-05-01 … -
How add custom fields to django-serializer dynamically?
I am trying to write a simple CRUD application. I have several pretty similar model classes and one serializer: class TestModelSerializer(serializers.ModelSerializer): queryset = None @classmethod def initialize(cls, queryset, context_class, **kwargs): _srlz = cls() _srlz.Meta.model = context_class _srlz.Meta.fields = '__all__' _srlz.queryset = queryset _srlz = cls(_srlz.queryset, **kwargs) return _srlz class Meta: model = None fields = '' so I can serialize my classes, calling initialize function like this: _q = Foo.objects.all() _srlz = TestModelSerializer.initialize(_q, Foo, many = True) _q2 = Bar.objects.all() _srlz2 = TestModelSerializer.initialize(_q2, Bar, many = True) and so on. But I have faced to one problem. Sometimes my classes are in hard One-to-Many relation (composition): class Foo(models.Model): pass class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete = models.CASCADE) When I serialize Foo class I want to serialize a list of related Bar classes as well and nest result data to Foo's serializer data. I am not intended to write custom serializer for each of these classes but instead try to implement some generic approach. I decided to make some experiments and finally create an interface that provides me several methods for my collection items: class Foo(models.Model): bars = iCollection pass Now when instantiate a serializer I can get all fields of … -
How to call file object path in a django view?
I have a view where when users access it images they uploaded will be processed so I need to call the image.path to pass it to the processing function as it requires an image path. whenever I try to call the function it returns invalid file path error and when I try calling the Model.field.path returns an error stating Model field has no path attribute so here's my model.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.FileField(upload_to = user_directory_path , verbose_name = 'Image') class Processed(models.Model): uploaded_image = models.ForeignKey(UploadedImages,on_delete=models.CASCADE,related_name='processed') analysedimage = models.ImageField(upload_to=analyses_directory_path, verbose_name='analysed Image', blank=True) views.py def AnalysedDetails(request,pk=None): Uimage = get_object_or_404(models.UploadedImages,pk=pk) analysed = models.Processed(uploaded_image=Uimage,analysedimage=main(print(Uimage))) analysed.save() return HttpResponse("OK") I tried Uimage.path and print(Uimage.path) and both didn't work so how can i call it proberly ? -
how to send an email with image unattached
html_content=render_to_string('email_approval.html',{'result':result}) message = strip_tags(html_content) email = EmailMultiAlternatives('인증 메일', message, to=[request.POST['email']]) email.attach(logo_data()) email.attach_alternative(html_content, "text/html") email.send() def logo_data(): with open(finders.find('../static/logo.jpeg'), 'rb') as f: logo_data = f.read() logo = MIMEImage(logo_data,_subtype="jpeg") logo.add_header('Content-ID', '<logo>') return logo views.py I have succeeded in sending an email with image attachment but I want to send an image above my email_approval.html as not of the image attachment. I want my image to be part of my message.I also have tried putting it as image tag on the html file but it does not appear on the gmail... please help me.. -
Django generated time column
I am making a little Time Attendance Application in Django. I'm experimenting with models in my app. I can't figure out how I can do this: start_time datetime NOT NULL, finish_time datetime NULL, duration int(11) GENERATED AS (TIMESTAMPDIFF(MINUTE, start_time, end_time)) STORED NULL, In django. So far, I've made a table called employees with all the employees' details: class employees(models.Model): employee_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=15) last_name = models.CharField(max_lenth=20) user_pic_one = models.ImageField() user_pic_two = models.ImageField() user_pic_three = models.ImageField() age = models.IntegerField() national_id = models.CharField(max_length=15) join_date = models.DateField() pay_structure = models.CharField() What I want to do is, Make a new table that has the 5 columns. - employee_id (as a foreign key from the employees class we just made) - start_time = models.TimeField() - end_time = models.TimeField() - duration = models.IntegerField() - date = models.DateField(default=date.today) So the only two things that I want to know are: How to do the foreign key stuff to verify the employee id in the later table from the employees table. and calculate the time duration in minutes from the start_time to the end_time. Thanks :) -
Preserve test data even after completion of unit test (not just database)
I want to use my test database with data in it which was created when testcase ran, how can i do it? I tried running normal django test which inherits TestCase and put a break point after test data is been generated. Now if I login to the test_db (which django creates) in different terminal tab through postgres command and query it, no data is shown! can someone explain why this happens?