Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using get_model in a custom slug generator raises django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I created a custom slug generator function to use in multiple models across multiple apps. To achieve this I pass the relevant django app name and django model as string parameters to the function, so the function can check if the slug is unique for that model: def slug_generator(django_app, django_model, field_name, slug_len, prefix=""): unique_pk = False model = apps.get_model(django_app, django_model) while not unique_pk: random_pks = random.sample( string.ascii_uppercase + string.digits + string.ascii_lowercase, slug_len) new_pk = ''.join(random_pks) search_query = {field_name: new_pk} try: if not model.objects.filter(**search_query).exists(): unique_pk = True except: if not model.objects.all().exists(): unique_pk = True return prefix + new_pk called in models.py like so: class Form(models.Model): form_id = models.CharField( max_length=25, default=slug_generator('forms', 'Form', 'form_id', 25)) The function was working fine when I only was using it for a single model (so i wasn't using get_model, I just hard coded the model it was for). Since adding get_model, this error is thrown on startup django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I tried putting the following before my function: import django django.setup() It only led me to a new error RuntimeError: populate() isn't reentrant, so it makes me think that there is a better way to write the function. Is what I am trying to achieve … -
htmx and django Class Based Views
I was traying to convert the countdown tutorial from here[1] to Class Based Views but I do not know what is missing. [1]https://htmx-django.com/blog/how-to-implement-countdown-timer-in-django-via-htm views.py class TimeDifferenceView(TemplateView): delta = datetime(2022, 12, 1, tzinfo=timezone.utc) - timezone.now() template_name = 'base.html' days = delta.days seconds = delta.seconds % 60 minutes = (delta.seconds //60) % 60 hours = delta.seconds // 3600 def get_context_data(self,*args, **kwargs): # Call the base implementation first to get the context context = super(TimeDifferenceView, self).get_context_data(*args, **kwargs) # Create any data and add it to the context. context['days'] = self.days context['seconds'] = self.seconds context['minutes'] = self.minutes context['hours'] = self.hours return context base.html <div id= "time" class="d-flex justify-content-between" hx-get="{% url 'time_difference' %}" hx-trigger="every 1s" hx-select="#time" hx-swap="outerHTML" > <div> <h5>Days</h5> <p> {{days}} </p> </div> <div> <h5>Hours</h5> <p> {{hours}} </p> </div> <div> <h5>Minutes</h5> <p> {{minutes}} </p> </div> <div> <h5>Seconds</h5> <p> {{seconds}} </p> </div> </div> -
How do I resolve "Invalid service account certificate. Certificate must contain a "type" field set to "service_account"" error to run a Django server?
I'm trying to run a Django server. I have installed python 3.8.2 and the rest of the requirements are installed through a requirements.txt file in the project folder. After installing the requirements, I've tried to run the server but it generates the following error: ValueError('Invalid service account certificate. Certificate must contain a ' ValueError: Invalid service account certificate. Certificate must contain a "type" field set to "service_account". I have tried re-installing python, re-installing the requirements, running it in a virtual environment but nothing has worked so far. It would be really great if someone guides me how to resolve this error and run the server. Error with complete traceback: https://drive.google.com/file/d/1nZdOXKjDgOnd96yJBfhZbWSZ_jdDjTuK/view?usp=sharing Manage.py: https://drive.google.com/file/d/1eXXvy8Jm2GmqmYD0pmG9CJUF-QEYchS-/view?usp=sharing Requirements.txt: https://drive.google.com/file/d/1hOsZrYactHs4nTmfbshPvIV2xAvzuaq4/view?usp=sharing -
Django model override save function raise error if an object is already active
in my Django Model I would like to validate an investment before saving, if this investment has active field value set to true and another investment belonging to the same company is already active then I should raise an error, si business rule is an only one active investment/company : Here is my code : def save(self, *args, **kwargs): if self.active: qs = type(self).objects.filter(active=True).filter(startup=self.startup) # TODO a bug here when unchecking then checking a unique active investment ==> error raised if qs: raise ValidationError(message="An active investment already exists for this startup") super(Investment, self).save(*args, **kwargs) My code seems to work, however i have found a bug in Django admin, in fact if an investment is active and is the only one to be active for that startup, when I uncheck then check again the active box the error is raised although I am not adding an active object neither updating here I am simply clicking on a checkbox twice!! -
How to sent data from contact form to my private gmail in django?
I have contact form on my Django website. I want, when someone fill the form to be sent to my private email. I have tried to do it like this, but it just refresh the page, I don't know what I made wrong. When I google the solution, I get many solutions with email services, but I don't need that, when form is filled, data to be sent to my private mail. What I need to change in my views function? This is contact form! views.py def contact(request): page_title = 'Contact' form = ColorfulContactForm() if request.method == 'GET': form = ColorfulContactForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] email = form.cleaned_data["email"] message = form.cleaned_data["message"] send_mail = EmailMessage("my.mail@gmail.com", message, to=[email]) return response else: form = ColorfulContactForm() return render(request, 'contact.html', {'page_title':page_title, 'form': form}) forms.py class ColorfulContactForm(forms.Form): name = forms.CharField( max_length=30, widget=forms.TextInput( attrs={ 'style': 'border-color: blue;', 'placeholder': 'Write your name here' } ) ) email = forms.EmailField( max_length=254, widget=forms.TextInput(attrs={'style': 'border-color: green;'}) ) message = forms.CharField( max_length=2000, widget=forms.Textarea(attrs={'style': 'border-color: orange;'}), help_text='Write here your message!' ) -
Can not create db table in django migration
I have 2 apps "app1", "app2" in my django project. When I ran python3 manage.pymakemigrations, I can see ... Migrations for 'app1': ... Migrations for 'app2': ... But when I ran python3 manage.py migrate, I got error saying django.db.utils.ProgrammingError: relation "auth_user" does not exist "auth_user" is db table for app1.User model. I tried to run migrate separately. It is fine for app2. But when I run python3 manage.py migrate app1, I got No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. I cannot find a solution for my case, anyone can help? -
Gmail API with heroku and django project
I am stuck with identyfing issue on application being deployed to Heroku. It is a python django project that using a Gmail API should send out emails to defined subscribers. Code is as below views.py (where function is called) def MailJournals(new_acts): mailAdresses = models.EmailSubscriber.objects.all().values_list('email') mail_list = [x[0] for x in mailAdresses] journal_date = datetime.strftime(datetime.now(), '%d/%m/%Y') message = MIMEText(render_to_string('newsScrapper/mail.html',{ 'journal_date': journal_date, 'new_acts': new_acts, }), 'html') message['to'] = ",".join(mail_list) message['from'] = EMAIL_HOST_USER message['subject'] = 'Official Journal as of ' + journal_date with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp: smtp.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) smtp.send_message(message) settings.py: EMAIL_HOST_USER = env('EMAIL_USERNAME') EMAIL_HOST_PASSWORD = env('EMAIL_PASSWORD') The thing is it perfectly works on localhost so I do not believe this is a code issue. Here are some heroku logs I have extracted for the call of that function: 2021-11-30T21:09:30.657994+00:00 heroku[router]: at=info method=GET path="/home/load/" host=legisync.herokuapp.com request_id=6c5c138d-05a4-488e-8bcd-c0bdc03da7fa fwd="83.23.240.85" dyno=web.1 connect=0ms service=464ms status=302 bytes=259 protocol=https Unfortunately I have no idea how to correctly identify underlying root cause why it does not work from heroku... Any ideas, or if sth else is needed from my side to share pls let me know. -
How to speed up the query transactions for large records in Django, if we are visiting multiple classes to achieve this?
I'm trying to show user profiles suggestion for a loggedIn user based on the tags he/she follows, In my case i have to travel to User_Interests_Tag class to get all the tags, next visit Post_Tag class to get all the posts for each of the tag(loop), once i have the all the postId's, visit the Post class to get each unique user and append it to a profile(List) and used paginator to limit the profiles sent to the client. How can i achieve this without using for loops to increase the overall efficiency and response time from the server? here is the snippet what i want to achieve : #looping through each tag for user_interests_tag in user_interests_tags: #user_post_tags = Post_Tag.objects.in_bulk(user_interests_tags) (used bulk but no luck) user_post_tags.extend(list(Post_Tag.objects.filter(tag_id = user_interests_tag).values_list('post_id', flat=True))) profiles = [] #looping through each tag id for user_post_tag in user_post_tags: #getting the user from post class user = Post.objects.get(id = user_post_tag) #checking if already follows and if already their in user profiles array if user not in profiles and not User_Follow.objects.filter( owner_id = user_id.id, user_id = user.user_id): profiles.append(user) #paginating 6 per request paginator = Paginator(profiles,6) limited_profiles = paginator.page(page) return limited_profiles Any leads very much appreciated, thanks in advance :) -
How to resolve the error: TypeError at /signup save() missing 1 required positional argument: 'self'
I'm trying to register users using AbstractUser but I'm getting an error. Although I'm getting error, users still get registered but I can't handle login with the registered users. The error goes thus: The error goes thus: The post request My views.py goes thus: def signup(request): if request.method == 'POST': first_name = request.POST['first-name'] last_name = request.POST['last-name'] username = request.POST['username'] email = request.POST['email'] phone_no = request.POST['phone-no'] password = request.POST['password'] password2 = request.POST['password2'] if password==password2: if CustomUser.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('signup') elif CustomUser.objects.filter(email=email).exists(): messages.info(request, 'Email Already Exist') return redirect('signup') else: CustomUser.objects.create_user(first_name=first_name, last_name=last_name, username=username, email=email, phone_no=phone_no, password=password) CustomUser.save(commit=False) return redirect('login') else: messages.info(request, 'Passwords Not Matching') return redirect('signup') else: return render(request, 'signup.html') And my models.py: class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=150) phone_no = models.CharField(max_length=20) is_end_user = models.BooleanField(default=True) is_smart_earner = models.BooleanField(default=False) is_top_user = models.BooleanField(default=False) -
Heroku : Server Error, Status=(500), bytes=403
Everything in the project is working but I only have problem with this request and I dont know what it is. heroku logs: 2021-11-30T19:23:21.705472+00:00 app[web.1]: 10.1.43.186 - - [30/Nov/2021:19:23:21 +0000] "GET /api/player=1/matches HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36" 2021-11-30T19:23:21.707787+00:00 heroku[router]: at=info method=GET path="/api/player=1/matches" host=football-players-stats-api.herokuapp.com request_id=e94d6c13-3fbd-4825-b696-282992be5bc9 fwd="186.58.74.102" dyno=web.1 connect=0ms service=27ms status=500 bytes=403 protocol=https views: class MatchesView(generics.ListAPIView): serializer_class = MatchesSerializer permissions = (IsAuthenticated) def get_queryset(self): player = self.kwargs['player'] return Matches.objects.filter(player=player).all() urls: app_name = 'api' urlpatterns = [ path('',include(router.urls)), path('player=<str:player>/matches',views.MatchesView) ] -
Why does my Django form not raise Validation Error?
I read through most SO cases regarding this issue but all are kind of specific, so I come here for help. I have impelemented a range filter in my Django project that takes in two inputs set to a low bound and high bound value, and displays the range of data within those bounds. What I'm trying to do, is make it so when a user inputs a higher number in the low bound than the high bound value, a ValidationError is raised for the user to see on the front end, and results are not displayed. I am a bit new to working with Django forms, but I can supply my code, and maybe someone could provide a solution forms.py class PlayerForm(forms.Form): # player forms points_high = forms.IntegerField(validators = [MinValueValidator(0)], min_value=0, label = 'Reviews', required = False, widget = forms.NumberInput( attrs={'id': 'pointsHigh', 'name': 'pointsHigh', 'href': '#', 'value': '', 'class': "form-control"})) points_low = forms.IntegerField(validators = [MinValueValidator(0)], min_value=0, required = False, widget = forms.NumberInput( attrs={'id': 'pointsLow', 'name': 'pointsLow', 'href': '#', 'value': '', 'class': "form-control"})) def check_bounds(self): """custom validation to check if low bound value is higher than high bound value""" data = self.cleaned_data player_low = data['player_low'] player_high = data['player_high'] if player_low … -
AttributeError: 'float' object has no attribute 'quantize' using django-firebird
I'm using: Django 2.2.24 django-firebird 2.2a1 fdb 2.02 my model: class MyModel(models.Model): ... total = models.DecimalField(max_digits=10, decimal_places=2, null=True) ... When i run a simple query: ml = MyModel.objects.values('id', 'total').last() I got this error: AttributeError: 'float' object has no attribute 'quantize' could someone help me please ? -
Can we loop through django channel layers?
I'm using django channels. I have encountered a problem. I'm trying to loop through different room names to send messages. but I'm getting type error. I don't know if this is possible with django-channels or is it fine to use loop for sending messages in sockets my code. consummers.ProjectConsumer Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) sender = text_data_json['sender'] receiver = text_data_json['receiver'] message = text_data_json['message'] # Send message to room group username = ["admin","main"] for user in username: object = { 'sender':sender, 'receiver': user, 'message':message, } username = user self.room_name = username print("here", self.room_name) self.channel_layer.group_send( self.room_name, { 'type': 'sent', #function name as an event type 'object': object #function parameters as an event object } ) async def sent(self, event): sender = event['object']["sender"] receiver = event['object']["receiver"] message = event['object']["message"] # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender':sender, 'receiver':receiver, 'message':message, })) error: File "/home/aa/gitCodes/clone-beru/4-multiuser_handler/backend/notifications/sockets/consumers.py", line 117, in receive await self.channel_layer.group_send(... TypeError: can not serialize 'type' object -
Failed in connecting to remote sql database using domain name instead of hardcoded remote ip adress
ALLOWED_HOSTS = ['http://xxx.xxxx.com/'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxxxDB', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'root', } tried replacing the remote ip to domain name which is in working state,django stops connecting doesnt show any error.please help. -
owl Carousel is not working after ajax success in python Django
I want to get the parent category list on the slider by clicking the main category's slider list. the second category's sider is not working when I click the main category. $('.maincategory').owlCarousel({ }); $(".box").on("click", function(){ var value= this.id.toString(); var csr =$("input[name=csrfmiddlewaretoken]").val(); debugger $.ajax({ url: 'getParentCategory', type: 'POST', data: { id: value, csrfmiddlewaretoken: csr }, success: function (response) { data = response.results AppendData(data); } }); }); function AppendData(data){ $(".secondCategory").empty(); debugger; var htmls = ''; if(data.length != 0){ for (var i = 0; i < data.length; i++) { htmls += '<div class="item eight-card-single text-center">' htmls += '<a id="{{value.id}}" class="second-category category">' htmls +='<img src="/media/uploads/products/logo.jpg">' htmls +='<h5 id="'+ data[i].name +'" class="card-title">'+ data[i].name +'</h5>' htmls +='</a>' htmls +='</div>' } $(".secondCategory").append(htmls); $('.secondCategory').owlCarousel({ }); } else { $(".secondCategory").append("No data"); } }; -
how to assign a value to new user in django
i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and right now, i don't know what to do neither do i know how to implement maybe becuase i don't have much experince with django. views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') # error is showing "instance" is not access using visual studio code instance = UserMembership.objects.create(user=obj, membership=get_membership) messages.success(request, f'Account Successfully created for {username}! You can Login In Now') return redirect('userauths:login') elif request.user.is_authenticated: return redirect('elements:home') else: form = UserRegisterForm() context = { 'reviews': reviews, 'form': form, 'info': info, 'categories': categories } return render(request, 'userauths/register.html', context) traceback Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File … -
"return self.title</pre>" returns a syntax error django
Please bear with my ineptitude. I'm trying upgrade my skillset from simple python scripts to something closer to resembling a full stack developer. RN I am creating a simple Django todo app and am going through a basic tutorial here. https://www.geeksforgeeks.org/python-todo-webapp-using-django/ Env is setup with the following... Python==3.8.9 Django==3.2.9 django-crispy-forms==1.13.0 my models.py looks like this: from django.db import models from django.utils import timezone class Todo(models.Model): title = models.CharField(max_length=100) details = models.TextField() date = models.DateTimeField(default=timezone.now) , if I am correct in assuming this is related to CSS. I am not sure where to go from here. Can anyone help me? def __str__(self): return self.title</pre> and my forms.py looks like this from django import forms from .models import Todo class TodoForm(forms.ModelForm): class Meta: model = Todo fields = "__all__"</pre> When I execute python3 manage.py makemigrations or runserver I get the following error and am clearly unable to figure out why. File "/home/ezurel/Coding/AppleTree/AppleTree/urls.py", line 19, in <module> from todone import views File "/home/ezurel/Coding/AppleTree/todone/views.py", line 7, in <module> from .forms import TodoForm File "/home/ezurel/Coding/AppleTree/todone/forms.py", line 8 fields = "__all__"</pre> ^ SyntaxError: invalid syntax I'm stumped as to the need for the </pre> tag and to why it needs to be there and not as … -
AttributeError at / type object 'Form' has no attribute 'objects', how to fix?
AttributeError at / type object 'Form' has no attribute 'objects', I'm new to django, I'd appreciate a brief explanation views.py from django.shortcuts import render,redirect from django.contrib import messages from .forms import * def main(request): if request.method == "POST": form = Form(request.POST) if form.is_valid(): Form.objects.get_or_create( name=form.cleaned_data['name'], email=form.cleaned_data['email'], phone=form.cleaned_data['phone'] ) messages.success(request, 'Form has been submitted') return redirect('/') else: return HttpResponse("Invalid data") else: form = Form() return render(request, 'app/main.html', {'form': form}) models.py class ModelsForm(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=30) phone = models.CharField(max_length=30) objects = models.Manager() forms.py from .models import ModelsForm class Form(ModelForm): class Meta: model = ModelsForm fields = '__all__'``` -
how to make multiple select checkbox with ajax and no button submit
Python 3.9 Django 3.2 I have categories and product , and through a simple form in the template I choose 1 or 2-3 checkboxes and I get the result. How to do it now via ajax and without button 'submit'. I select several product categories and each click on the checkbox is ajax and the next click on the checkbox adds the parameter to the request. it is similar to how you select several parameters in online stores. You have selected 2 parameters and received a filtered list of products I suppose that you need to intercept the sending, store one request in the cache and add a new one to this request <form method="post" id="category-box"> {% csrf_token %} <div class="form-check"> <input class="form-check-input" type="checkbox" name='category' value="{{c.name}}" > <label class="form-check-label" for="{{c.name}}"><a href="{{ c.get_absolute_url }}">{{ c.name }}</a></label> </div> {% endfor %} <button type="submit">Submit</button> </form> -
Will Django always consider an Emoji as 1 character long?
I'm making a Post Reaction model that uses emojis as reactions, and at this point I'm not mapping them to Choices, but instead inserting the utf-8 value (e.g. 😀) directly to the Database (Postgres) as a CharField instance. This made me think which value should I use to the max_length of this field. I know Rust will take emojis as 1 char long, but I'm not sure about how python or Postgres will react. -
Django Forms: How do I use a selected object from dropdown menu?
I have a functioning dropdown menu filled with some objects from a database. When a user selects one, they should be directed to the objects appropriate page. Each object is a "Workout" and each workout has "Exercises". It is working, however, I am struggling to get the appropriate 'id' from the object that has been selected by the user. Below I will provide the view, template, url, and form. view.py @login_required def routines(request): """This view will provide a dropdown list of all of the workouts of a specific user. Once one is selected, the user will hit a submit button. After submitted, a new page will show all the exercises for that workout""" if request.method == "GET": #if we have a GET response, provide a form with filled data form = RoutineForm(request.GET, user=request.user) #data needs to equal the object that was selected from the GET form data = 1 if form.is_valid(): data=form.cleaned_data("workout") form.instance.owner = request.user #make sure we have the right user form.save() return HttpResponseRedirect('routine_workouts_app:routines') context = {'form':form, 'data':data} return render(request, 'routine_workouts_app/routines.html', context) @login_required def routine(request, data): """I think this is the view that will display the information of a workout as of now. Should be similar to the workout … -
how do I create a javascript function that changes the html when a form submit button is pushed in django
I can easily update the html when it's not part of the form's submit or button. Or even when it's just a pure button element (rather than an input from a form). However, when I try to append a string to the class "chatGoesHere", nothing happens. The consolealso quickly reloads since the form is going to \send. I'm happy to post my views.py and urls.py, however, I'm pretty sure the issue is inside of my html document below: <p class="chatGoesHere" id="chatGoesHere"> 1st Item! </p> <form action="\send\" method="post"> <input type="text" name="userMessage" /> <input type="submit" value="Send to smallest_steps bot" class="sendButt" id="sendButt" /> </form> <script> var btn = document.getElementById("sendButt"); btn.addEventListener("click", updateChat); function createMenuItem(name) { let li = document.createElement('p'); li.textContent = name; return li; } const td = document.getElementById('chatGoesHere'); td.appendChild(createMenuItem("TEST2")) function updateChat(){ const td = document.getElementById('chatGoesHere'); td.appendChild(createMenuItem("TEST3")) } </script> I'd like it so that every time a user pushes the submit button of the form something gets added to the page without the page reloading. Thank you -
Django window.location not replacing string
I have a javascript function in a django view that is supposed to redirect the user to a different URL that contains a query parameter. When I print out the url before assigning it to window.location, it matches the url pattern as expected. However once I assign the URL to window.location, it seems to append the url to the already existing one instead of replacing it, and thus cannot find the matching url pattern. Javascript function: function downloadEvidence() { var product_review_ids = getProductReviewIDs(); if (product_review_ids === '') { window.alert("Please select at least one deployment.") return; } var url = window.location.href + "download_evidence?productReviewIDs=" + product_review_ids console.log(url); //prints: http://127.0.0.1:8000/access-review-owner/configure/new%20test%20product/download_evidence?productReviewIDs=14 window.location = url; } The url pattern it is supposed to match: urlpatterns = [ path('access-review-owner/configure/<str:product_name>/download_evidence/',views.download_evidence_view, name='download_evidence_view'), ] The view it's supposed to navigate to: @require_http_methods(['GET']) def download_evidence_view(request, product_name): product_id = request.GET.get('productReviewIDs', None) print(product_id) ''' NOTE: Package up evidence here ''' return HttpResponseRedirect(os.environ['BASE_URL']+f'access-review-owner/configure/{product_name}/download_evidence/') The url it's attempting to find when I assign the correct one to window.location: GET http://127.0.0.1:8000/access-review-owner/configure/new%20test%20product/download_evidence/access-review-owner/configure/new%20test%20product/download_evidence/ -
Proper way to construct classes - Django dartCounter project
I was recently starting to do some programming. I figured out how to use Django a couple of days ago. And now I'm trying to integrate some old Python code with it. I created a simple dartCounter. Which is quite easy in a while-loop. However for the new version I want some graphical interface, so I figured I should make some proper classes to interact with without the usage of while loops for the count mechanism. Those classes should be used in the views.py section in Django. The thing is, I think I already made it overcomplex using this method. First I created a class dart_player() class dart_player(): def __init__(self, name): self.name = name self.score = None self.leg = 0 self.thrown_scores = [] def set_start_score(self, start_score): self.score = start_score self.thrown_scores = [] def update_score(self, score): if self.score != None: self.score = self.score - score self.thrown_scores.append(score) else: print("Error score equals 'None' \n") def reverse_score(self, score): if self.score != None: self.score = self.score + score self.thrown_scores = self.thrown_scores[:-1] else: print("Error score equals 'None' \n") def update_leg(self, leg): self.leg = self.leg + leg Next I ended up creating a class dart_match() and within it, the class leg() since the leg is part of … -
Can you access variable attributes in the django template language with other variables?
Let's say I have two variables - User and Fruitlist. User is a model instance, while fruitlist is a list. {% for user in users %} <tr> <td>{{ user.title }} </td> <td>{{ user.text }} </td> {% for fruit in fruitlist %} <td>{{ user.fruit }} </td> {% endfor %} {% endfor %} I'm trying to create a table with the code above where a column is created for each fruit in fruitlist, and that column is filled with the value of an attribute user.fruit (the user model has a field for every fruit which contains a value). Why doesn't the above code work?