Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disable email management in django-allauth
I'm using django-allauth and wondering what The Right Way™️ to disable email management is. Some context: accounts are created on behalf of users, and they should stick to their (institutional) email address. Should I just override the templates and remove accounts/email from allauth.urls or is there a more elegant way? -
How to add search filters to find individual value inside of an array in Django
I have succesfuly implemented Elasticsearch with haystack inside of my Django project but now I'm stuck with this problem since last week.. Basically, the problem is that I need to be able to add filtering when someone click on a checkbox so that he can find a single desired value inside of an array / string which is the ptag field. I've tried many things like Haystack Facets but it never worked, so how can I possibly do this? My code look like this for now, I've just added a function (FilterView) but I still can't find a way to make it work effectively.. Views.py from django.views.generic import TemplateView from django.http import JsonResponse from django.shortcuts import render from .models import Product class HomeView(TemplateView): template_name = "home.html" def FilterView(request): ptag = request.GET.get('ptag', '') qs = Product.objects.all() if ptag != 'on' else Product.objects.filter(ptag='') context = { 'queryset': qs } return render(request, "partials/search_form.html", context) urls.py from django.conf.urls import url from django.contrib import admin from search.views import HomeView from .settings import MEDIA_ROOT, MEDIA_URL from django.conf.urls.static import static urlpatterns = [ url(r'^$', HomeView.as_view()), url(r'^admin/', admin.site.urls) ] + static(MEDIA_URL, document_root=MEDIA_ROOT) Models.py from django.db import models from django.contrib.postgres.fields import ArrayField from django.urls.base import reverse class Product(models.Model): destination … -
How a passed dictionary in setUp() method can cause changing the user's password here?
I am learning Django testing. I recently saw these codes, I searched a bit but still couldn't convince myself how they actually work together. Here are the codes: class PasswordChangeTestCase(TestCase): def setUp(self, data={}): self.user = User.objects.create_user(username='john', email='john@doe.com', password='old_password') self.url = reverse('password_change') self.client.login(username='john', password='old_password') self.response = self.client.post(self.url, data) class SuccessfulPasswordChangeTests(PasswordChangeTestCase): def setUp(self): super().setUp({ # where do this dictionary is passed in? 'old_password': 'old_password', 'new_password1': 'new_password', 'new_password2': 'new_password', }) def test_password_changed(self): self.user.refresh_from_db() self.assertTrue(self.user.check_password('new_password')) Can you please explain What does super().setUp({#keyValues}) does in here? I know what aresuper() and setUp(), but I don't know what does it means when they are next to each other specially when a dictionary is passed into setUp? testing_password_changed function confused me as well. Where in these parts of the code the old password is changed with new password that it refresh the db with self.user.refresh_from_db() function. Changing old password with new password is done in PasswordChangeForm I expected something like self.client.post(password_change_url, data), or maybe I didn't understand them properly. Please help me Thank you for reading and helping. -
How to test URL args of POST request?
I have a POST view, which also get GET argument ?company= from URL. How to test it using Django Rest Framework test tools? -
Setting up django registration for custom user (Validing user creation form for custom user causes no such table: app_appuser)
I am trying to register my custom user on django website. My register view (that was wrote for standard user) throws no such table: app_appuser model: class AppUser(AbstractUser): full_name = models.CharField(max_length=50, null=True) miniature = models.ImageField(upload_to='images/profile_photos', default="defaults/default.png", validators=[validate_miniature_file_extension]) def __str__(self): return self.name form: class RegisterForm(UserCreationForm): class Meta: model = models.AppUser fields = ("username", "full_name") post method that is responsible for registration: def post(self, request): form = forms.RegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('/') else: return render(request, 'register.html', { 'form': form }) I tried to run makemigrations, and syncdb and it didn't help me. I also have added AUTH_USER_MODEL = 'app.AppUser' to my settings.py file. And my question is: how to setup registration for it? -
return csv file in response with only headers in it
I need to create an rest api in django which would return a csv file which contains headers only inside it , and also file is created during run time. Here is my code, don't know why it is not sending file, ideally this function should return csv file which would have headers as filenames. def get_template(): fieldnames = ['id, rate_plan_name, test_cd, test_name, price, is_package, is_deleted'] with open('templates.csv', 'w') as csvfile: wtr = csv.writer(csvfile, delimiter=',') wtr.writerow(fieldnames) response = HttpResponse('templates.csv', content_type='application/x-download') filename = "template_%s.csv" % (datetime.utcnow()) content = "attachment; filename='%s'" % filename response['Content-Disposition'] = content return response -
How can I create a django API as a relay?
I'm new to Django but not new to Python. I need to create a restful (and websocket next) APIs to communicate with my underlying C++ backend program. So I need the following scenario to happen: The user makes a request The request comes through the API server (which is to be in Django) Django, through a model (or otherwise), forwards this request to me (or its parameters), with a callback or otherwise I use the thrift RPC client (which is already coded and ready to go) with the parameters from the request provided by Django, to call the C++ backend. Get the response from the backend, and create a response for the client and submit it to them through Django. I did some tutorials on Django and got the idea of how it works. It seems to me that what I'm planning to do is not possible, because I have to strictly communicate with a model in the database. I don't need that. How can I use Django as a relay for my backend software as described above for Restful API? Is it possible to do the same with websocket? An example would be highly appreciated. Additional information: Why I … -
VS Code - Is it possible to do "Go to definition" with module path as string?
I develop my Django application in VS Code editor and for example, I have a list of middlewares in my app's config, e.g. MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ... ] and now, I want to simply mark my corsheaders.middleware.CorsMiddleware, click right mouse button and just click "Go to definition", and then I should jump to the class definition (source code). Is it possible with any extension? -
How can I get rid of this generic class and stop the unnecessary inheritance chain?
At my job I am currently trying to rewrite the views we have for our website. Hopefully this will help me refractor the authentication system, but that is irrelevant. I am not very adept at python (this is a Django Project), and therefore, I'm having a hard time a.) just understanding the code, and b.) figuring out where everything goes. I've already tried pretty much copying and pasting the contents of the BaseGenericView class into the Dashboard class, but that doesn't work. I've tried being selective in what I take from it and it still doesn't work, I've gotten quite a few different errors that overall don't tell me what I did wrong. Below I have the BaseGenericView class and the Dashboard class (there are a lot more views that are based of the BaseGenericView class, but I thought the Dashboard would be a good example to work with). class BaseGenericView(View): """ Base view for all frontend views that extend base.html this view adds desk and worker and request to the context along with setting the desk to request.session and checking verification """ desk = None page_name = "" @method_decorator(login_required) def dispatch(self, *args, **kwargs): # Desk must be in session … -
Django allauth not hashing passwords
I'm using Django AllAuth for my social login. I don't have custom User signup form, but I do use custom User model. Here's my user model: class User(AbstractUser): is_candidate = models.BooleanField(default=True) is_employer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) username = models.CharField(max_length=40, unique=False, default='') first_name = models.CharField(_("Ime"), max_length=50, null=True) last_name = models.CharField(_("Prezime"), max_length=50, null=True) mobile = models.CharField(_("Telefon"), max_length=20,null=True, blank=True, unique=True) address = models.CharField(_("Adresa"), max_length=250, null=True, blank=True) def __str__(self): return self.email Now, after getting errors that user/password combo on login is not correct for any and all users I tried, I inspected database and noticed that passwords for users registered are not hashed at all. Note that passwords for superusers, the ones I create with python manage.py createsuperuser, are hashed properly. So, after Googling around, I found that I need to override AllAuth's save_user() method, so I've set ACCOUNT_ADAPTER = 'core.social_adapter.UserAccountAdapter' in my settings.file, and added following code to myproject/core/social_adapter.py: class UserAccountAdapter(DefaultAccountAdapter): print("using account adapter") def save_user(self, request, user, form, commit=True): user = super(UserAccountAdapter, self).save_user(request, user, form, commit=False) user.is_candidate = True user.password = makepassword( form.cleaned_data['password'] ) print('in custom adapter save_user method') print(user.password) user.save() return user This, however, didn't help at all. Moreover, said save_user method doesn't seem to be used at all, as … -
How to use select_related() when some rows return null values for that related-object?
I'm trying to execute the following query: member = Member.objects.get(id=12345) Group.objects.annotate(membership=FilteredRelation('members', condition=Q(members__member=member))) \ .annotate(request=FilteredRelation('requests', condition=(requests__member=member))) \ .filter(Q(membership__isnull=False) | Q(request__isnull=False)) \ .select_related('membership', 'request') with the models class GroupMembership(models.Model): group = models.ForeignKey('group.Group', related_name='members', on_delete=models.CASCADE) member = models.ForeignKey( 'group.Member', related_name='group_membership', on_delete=models.CASCADE, ) class GroupMembershipRequest(models.Model): group = models.ForeignKey('group.Group', related_name='requests', on_delete=models.CASCADE) member = models.ForeignKey( 'group.Member', related_name='group_membership_request', on_delete=models.CASCADE, ) But i'm getting the following error: AttributeError: 'NoneType' object has no attribute '_state' probably caused by the nature of the query (some membership or request can be null). Is there another way to achieve that? -
JS should mantain it work after page reload
I am basically complete zero in JS, so this question might be completely dumb, anyway… I have a script that shows filename in bootstrap4 file input https://getbootstrap.com/docs/4.0/components/input-group/#custom-file-input This script is in charge for showing the file name inside the input: Problem is when page gets reloaded (due to the form failed validation, for example), this field would turn itself empty, that is without file name in it. Is it possible to modify this script in a way to show filename after page gets reloaded? P.S. Files are there after reloading. They are cashed by backend. file input html code is bellow {% endif %} <script> $(document).on('change', '.custom-file-input', function (event) { $(this).next('.custom-file-label').html(event.target.files[0].name); }) </script> {% if widget.is_initial %} <a href="{{ widget.value.url }}"><img class="ml-0" src="{% thumbnail widget.value "small" %}"></a> {% if not widget.required %} {% endif %} <br> {% endif %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupFileAddon01">Upload</span> </div> <div class="custom-file"> <input type="{{ widget.type }}" name="{{ widget.name }}" class="custom-file-input" id="inputGroupFile02" id="inputGroupFile02" aria-describedby="inputGroupFileAddon01" {% include "django/forms/widgets/attrs.html" %}> <label class="custom-file-label " for="inputGroupFile02">{{ widget.value|default_if_none:"Choose the file" }} {{ widget.filename }}</label> </div> </div> -
creating post api for manytomany field assingning value to the fields in model
I am working on a project, it is "company data" for recording employees details. I have one "manytomany" field named "skill" and I want to assign value to it from postman by "post request". def create_employee(cls, email, password, first_name, last_name, mobile_number, dob, nationality, skill): user = User.objects.create(first_name=first_name, last_name=last_name, email=email, username=email) if not password: password = User.objects.make_random_password() user.set_password(password) user.save() dob_obj = datetime.datetime.strptime(dob, "%Y-%m-%d").date() emp = cls.objects.create(user=user, email=email, mobile_number=mobile_number, dob=dob_obj, nationality=nationality, skill=skill.set()) return emp views.py class RegistrationView(APIView): permission_classes = () authentication_classes = () def post(self, request): email = request.data.get('email', '') password = request.data.get('password', '') first_name = request.data.get('first_name', '') last_name = request.data.get('last_name', '') mobile_number = request.data.get('mobile_number', '') dob = request.data.get('dob', '') nationality = request.data.get('nationality', '') skill = request.data.get('skill', '') if not email: return Response({"success": False, "message": "An error occurred"},status=status.HTTP_400_BAD_REQUEST) try: if User.objects.filter(email=email).exists(): return Response({"success": False, "message": "Email ID already registered. Please login"}, status=status.HTTP_400_BAD_REQUEST) employee = Employee.create_employee(email, password, first_name, last_name,mobile_number, dob, nationality, skill) except: return Response({"success": False, "message": "An error occurred. Please try again"}, status=status.HTTP_400_BAD_REQUEST) return Response({"success": True, "profile": employee.get_profile(), "token": employee.get_token() }) expected: The skill value should be set while employee registration. actual: it is not getting added. -
Suggested model structure to achieve users selection of services/package - Django
I am building an application that offers different services, a user can select and purchase specific needed packages. I want to know the best way to create the model so that our users can select and once paid it sets the service to active. I have one model that holds information about each individual services which includes (Package Title / Description / Price ). I need another model to handle what services are associated to each user but I am unsure how to go about this. I have created two models as shown below but unsure how I can accomplish the above as I believe there is a better was to accomplish this. class ClubPackages(models.Model): club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE) PACKAGE_STATUS = ( ('0', 'Active'), ('1', 'Not Active') ) player_register_package = models.CharField(default='1', max_length=1, choices=PACKAGE_STATUS) player_register_price = models.DecimalField(default=100.00, max_digits=8, decimal_places=2) player_register_expiry = models.DateField(default=timezone.now) roster_package = models.CharField(default='1', max_length=1, choices=PACKAGE_STATUS) roster_price = models.DecimalField(default=50.00, max_digits=8, decimal_places=2) roster_expiry = models.DateField(default=timezone.now) rent_a_pitch_package = models.CharField(default='1', max_length=1, choices=PACKAGE_STATUS) rent_a_pitch_price = models.DecimalField(default=100.00, max_digits=8, decimal_places=2) rent_a_pitch_expiry = models.DateField(default=timezone.now) shop_package = models.CharField(default='1', max_length=1, choices=PACKAGE_STATUS) shop_price = models.DecimalField(default=50.00, max_digits=8, decimal_places=2) shop_expiry = models.DateField(default=timezone.now) class OurPackages(models.Model): title = models.CharField(max_length=50) description = models.TextField(max_length=200) price = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self): return self.title -
Mocking a RelatedManager in Django 2
This question is directly related to this question, but that one is now outdated it seems. I am trying to test a view without having to access the database. To do that I need to Mock a RelatedManager on the user. I am using pytest and pytest-mock. # models.py - truncated for brevity, taken from django-rest-knox class AuthToken(models.Model): user = models.ForeignKey( User, null=False, blank=False, related_name='auth_token_set', on_delete=models.CASCADE ) # views.py class ChangeEmail(APIView): permission_classes = [permissions.IsAdmin] serializer_class = serializers.ChangeEmail def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = request.user user.email = request.validated_data['email'] user.save() # Logout user from all devices user.auth_token_set.all().delete() # <--- How do I mock this? return Response(status=status.HTTP_200_OK) # test_views.py def test_valid(mocker, user_factory): user = user_factory.build() user.id = 1 data = { 'email': 'foo@example.com' } factory = APIRequestFactory() request = factory.post('/', data=data) force_authenticate(request, user) mocker.patch.object(user, "save") related_manager = mocker.patch( 'django.db.models.fields.related.ReverseManyToOneDescriptor.__set__', return_vaue=mocker.MagicMock() ) related_manager.all = mocker.MagicMock() related_manager.all.delete = mocker.MagicMock() response = ChangeEmail.as_view()(request) assert response.status_code == status.HTTP_200_OK Drawing from the answer in the linked question I tried to patch the ReverseManyToOneDescriptor. However, it does not appear to actually get mocked because the test is still trying to connect to the database when it tries to delete the user's auth_token_set. -
make a dialogflow webhook receiver in django
Hi I'm setting up a chatbot using dialogflow, what I want is to integrate dialogflow with django so that a search function in the django server is executed and the result of the research is passed to the chatbot, I made a webhook to the django server in dialogflow using the url "https://0e3c393b.ngrok.io/webhook" but I dont know how make a webhook receiver in django, Any recommendations ? -
Displaying scrapped data in Django Template
I am trying to display the data from a website by scrapping it and storing it and passing it to template but not able to show anything. When a user click on those red button it will scrap the data like ammonium, NO2 etc for that location. So far I am able to scrap and show the result in terminal but not able to show it on that table. views.py from django.shortcuts import render, Http404 from .models import Data,pol import urllib import time from bs4 import BeautifulSoup import re import urllib.request import os from django.conf import settings import csv from django.views.decorators.csrf import csrf_exempt @csrf_exempt def data(request): Am = " ",CO = " ",NO = " ",OZ = " ",SO2 = " ",AT = " " PM10 = " ",BE = " ",NO2 = " ", ON = " ", pxy = " " TO = " ",BP = " ", PM2_5 = " ",SR = " " if request.method == 'POST': if 'rowd' in request.POST: rowd = request.POST['rowd'] station_code = {"av":"QW5hbmRWaWhhcg==","mm":"TWFuZGlybWFyZw==", "pb":"UHVuamFiaUJhZ2g=","rkPuram":"UktQdXJhbQ==","airpo":"SUdJ", "civilLines":"Q2l2aWxsaW5lcw=="} result = None #while result: sc = {"av":1,"mm":2, "pb":3,"rkPuram":4,"airpo":5, "civilLines":6} while(result is None): print("station",rowd) url = "http://www.dpccairdata.com/dpccairdata/display/AallStationView5MinData.php?stName={}".format(station_code[rowd]) html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html) regex = re.compile('tdcolor.*') td1 … -
Django admin: change date and datetime format
The default date format in Django admin is YYYY-MM-DD, I would like to change it to DD-MM-YYYY. Based on an answer to a similar question I could update the validators to accept the new format, but if I opened an existing object, the date was still shown as YYYY-MM-DD and the JS date picker returned dates in this format, too. How to overcome these issues? -
Django-Tables2 Pagination Labels
Django-Tables2 is great because it has built in pagination. The pagination labels are numbers such as: 1,2,3...n I would like to change the labels so that I could provide a list or query set of information where each index in the list object is a pagination label. I am envisioning something like this: from .models import SomeModel from .tables import CustomTable def table_view(request): #get the model model = SomeModel #configure the table table = CustomTable(model.objects.all()) #dictionary for table configuration master_dict = {'per_page': per_page, 'labels': ['a', 'b', ... 'z'} #<-list of pagination labels #configure table according to master dict and return for display RequestConfig(request, paginate = master_dict)).configure(table) return render(request, 'some_html.html', {'table': table}) Is this possible? Is there a way to change the pagination label? -
How to clean a form with cleaned values from another form?
I have a Loan Model that contains a loan amount. And I have a Tranche Model that contains an amount. Here is the pseudo code for those 2 models: class Loan(models.Model): loan_amount = PositiveIntegerField() class Tranche(models.Model): tranche_amount = PositiveIntegerField() I create a standart ModelForm for each of them: class LoanForm(forms.ModelForm): class Meta: model = Loan fields=['loan_amount'] class TrancheForm(forms.ModelForm): class Meta: model = Tranche fields = ['tranche_amount'] I define the two forms like this: def someview(request): loan_form = LoanForm(request.POST or None) tranche_form = TrancheFrom(request.POST or None) if loan_form.is_valid() and tranche_form.is_valid(): loan_form.save() tranche_form.save() #then render somme success_url #else render the template and give it the forms I want to be abble to get the cleaned loan amount and give it to my TrancheForm clean function. I want to check that the 2 amount are the same. In my real exemple Tranche is an inline formset so I want to avoid to do it on the view level like: if loan_form.loan_amount == tranche_form.loan_amount: loan_form.save() tranche_form.save() else: #return some error message And I would prefer a way to access the loan amount directly inside the clean method. -
Django drf simple-jwt authentication"detail": "No active account found with the given credentials"
I am implementing user authentication with django-rest_framework_simple-jwt with custom user, My models.py: class UserManager(BaseUserManager): def create_user(self, email, username, password, alias=None): user = self.model( email = self.normalize_email(email), username = username,) user.set_password(password) user.save() return user def create_superuser(self, email, username, password): self.create_user(email, username, password) user.is_staff() user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(null=False, unique=True) username = models.CharField(max_length=25, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username",] So I am implementing restframework simple-jwt authentication,my settings .py is as follows as: REST_FRAMEWORK={ 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ]} my urls.py: urlpatterns = [ url(r'^api/token/$', TokenObtainPairView.as_view(), name='token_obtain_pair'), url(r'^api/token/refresh/$', TokenRefreshView.as_view(), name='token_refresh'),] on login process, it returns error that "detail": "No active account found with the given credentials" all my users were active. I have no clue to sort this out, I need help.Thanks in advance. -
What is the bulletproof way to restore a django database from a local machine to a server?
I've not found a huge amount of guidance out there on this issue - and when I do find guidance there's not much to explain away some of the problems I'm having. I'm self-learning Python and Django, which is going fine, but deploying to a server is...hell. It would be great if there was someone out there with a bullet proof workflow for backing up a Django DB, and restoring to a server. With reference to virtual environments, migrations, --fake and -initial. For my own sake - and for anyone reading - I'm going to go through exactly what I've done, and see if I can see where the mistakes are - because I'm at the brick wall stage. The Problem 'It works on my machine' pretty much sums up exactly where I am at. It works fine. ON MY MACHINE. I've managed to get to a point where the database (Postgresql) is restored to my server - Python Anywhere. And my server instance of Django is talking to the database, and some data is being served. However, there are then some migration issues which persist, and ultimately cause several fatal errors about certain tables not existing - like this: … -
Dockerized Django: how to manage sql scripts in migrations?
Fairly new to Docker, I am trying to add the execution of a custom sql script (triggers and functions) to Django's migration process and I am feeling to feel a bit lost. Overall, What I am trying to achieve follows this pretty clear tutorial. In this tutorial, migrations are achieved by the execution of an entry point script. In the Dockerfile: # run entrypoint.sh ENTRYPOINT ["/usr/src/my_app/entrypoint.sh"] Here is the entrypoint.sh: #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi # tried several with and without combinations python manage.py flush --no-input python manage.py makemigrations my_app python manage.py migrate exec "$@" So far so good. Turning to the question of integrating the execution of custom sql scripts in the migration process, most articles I read (this one for instance) recommend to create an empty migration to add the execution of sql statements. Here is what I have in my_app/migrations/0001_initial_data.py import os from django.db import migrations, connection def load_data_from_sql(filename): file_path = os.path.join(os.path.dirname(__file__), '../sql/', filename) sql_statement = open(file_path).read() with connection.cursor() as cursor: cursor.execute(sql_statement) class Migration(migrations.Migration): dependencies = [ ('my_app', '0001_initial'), ] operations = [ migrations.RunPython(load_data_from_sql('my_app_base.sql')) ] As … -
How to merge two Django queries but keeping the result?
I have two queries, both giving me on their own a correct result. I tried merging them but then, the results get wrong (the numbers get multiplied). qs2 = Customer.objects.filter( opportunity__turnover__date__range=[start, end] ).annotate( month=TruncMonth('opportunity__turnover__date') ).annotate( turnover=Sum( "opportunity__turnover__value", filter=( Q(opportunity__turnover__type='Project') ) ), ).order_by( 'name','month' ).values('name','month','turnover') qs = Customer.objects.filter( project__worklog__day__range=[start, end] ).annotate( month=TruncMonth('project__worklog__day') ).annotate( hours=Sum("project__worklog__effort")/60/60, hoursBilled=Sum( "project__worklog__effort", filter=( Q(project__worklog__account__category='Abrechenbar') | Q(project__worklog__account__category='Billable') ) )/60/60, ).order_by( 'name','month' ).values('name','hours','month','hoursBilled') For the time being I am transforming both results to Pandas Dataframes and merging them - which works but is not nice as I do not need it to be a dataframe. The relevant models look like this: class Opportunity(models.Model): id = models.IntegerField(primary_key=True) #CRMID customer = models.ForeignKey(Customer, on_delete=models.CASCADE) probability = models.FloatField(null=True, blank=True, default=None) closeDate = models.DateField(null=True, blank=True, default=None) duration = models.IntegerField() value = models.FloatField(null=True, blank=True, default=None) name = models.CharField(max_length=200, null=False, blank=False) type = models.CharField(max_length=100, null=True, blank=True) class Turnover(models.Model): opportunity = models.ForeignKey(Opportunity, on_delete=models.CASCADE) type = models.CharField(max_length=100) date = models.DateField(null=True, blank=True, default=None) value = models.FloatField(null=True, blank=True, default=None) class Worklog(models.Model): worker = models.ForeignKey(Person, on_delete=models.CASCADE) day = models.DateField(null=True, blank=True, default=None) effort = models.FloatField() #timeSpentSeconds account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True, blank=True) comment = models.TextField(null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) issue = models.CharField(max_length=200) class Project(models.Model): key = models.CharField(max_length=200, primary_key=True) name = models.CharField(max_length=200, null=False, … -
Django URLs linking
I have 2 buttons and when I click on one of them I want to be redirected to a new html page, using the id as a parameter. My URLs urlpatterns = [ path('', admin.site.urls, name ='home'), path('dpo/imprimir/aprovado/<int:id>/',Aprovado, name ='aprovado'), path('dpo/imprimir/reprovado/<int:id>/',Reprovado, name ='reprovado'), ] My Template {% load i18n admin_urls %} {% block object-tools-items %} <li> <a href="/dpo/imprimir/aprovado/{{instance.id}}">{% trans "Aprovado" %}</a> </li> <li> <a href="/dpo/imprimir/reprovado/{{instance.id}}">{% trans "Não aprovado" %} </li> {% endblock %} My views from django.http import HttpResponse from django.shortcuts import render from django.shortcuts import render_to_response from .models import Projeto def Aprovado(request, id): obj = Projeto.objects.get(id=id) context = { "object": obj } return render(request, "dpo/imprimir/aprovado.html", context) def Reprovado(request, id): obj = Projeto.objects.get(id=id) context = { "object": obj } return render(request, "dpo/imprimir/reprovado.html", context) I think I'm doing this the wrong way.