Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django giving "Reverse for 'view' not found" error when view is defined
While using django 4.0.4 I have encountered the error "Reverse for 'upload' not found. 'upload' is not a valid view function or pattern name". It was working earlier in the day, and I can't figure out the problem for the life of me. I'll include my views.py, urls.py, and the relevant section of my html file, all three of which are in the same folder of the project. If anyone has any advice I would greatly appreciate it. Views.py def welcome(request): return render(request, 'welcome.html') def contact(request): return render(request, 'contact-us.html') def how(request): return render(request, 'How-to-use.html') def upload(request): if request.method == 'POST': if 'scatter_plot' in request.POST: form = UploadFileForm(request.POST.get, request.FILES) file=request.FILES['document'] csv = CSV.objects.create(doc=file) os.system('python ../scatter_plot.py') if 'line_plot' in request.POST: form = UploadFileForm(request.POST.get, request.FILES) file=request.FILES['document'] csv = CSV.objects.create(doc=file) os.system('python ../line_plot.py') return render(request, 'uploaded.html') else: form = UploadFileForm Urls.py urlpatterns = [ path('', views.welcome), path('admin/', admin.site.urls), path('contact-us/', views.contact), path('upload.html', views.upload), path('upload/', views.upload), path('welcome/', views.welcome), path('How-to-use/', views.how), path('contact-us.html', views.contact), path('welcome.html', views.welcome), path('How-to-use.html', views.how) ] Welcome.html <form method="POST" enctype="multipart/form-data" action="{% url 'upload' %}"> {% csrf_token %} <input type='file' name='document' accept='.csv'> <button type='submit' name='line_plot'>Graph as a line Graph</button> <button type='submit' name='scatter_plot'>Graph as a Scatter Plot</button> </form> -
How to test correctly this func in Django?
I have a test which check user can create a news or not. But my test doesn't work. I suppose I do something wrong with 'category' and 'author', but I don't know how to change it correctly. When I create a news in site by myself, everything work right. Test: @classmethod def setUpTestData(cls): user = User.objects.create(username='test1') user.set_password('test1') user.save() Profile.objects.create(user=user) NewsCategory.objects.create(category='Sport') def test_if_user_can_create_news(self): user = self.client.login(username='test1', password='test1') self.client.post(reverse('create_news'), { 'title': 'News 1', 'description': 'Description news 1', 'category': NewsCategory.objects.get(category='Sport'), 'author': user }) self.assertTrue(News.objects.filter(title='News 1').exists()) Models: class News(models.Model): title = models.CharField(max_length=200, verbose_name='Title') description = models.TextField(verbose_name='Description') category = models.ForeignKey(NewsCategory, on_delete=models.CASCADE, verbose_name='Category') author = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name='Author') class NewsCategory(models.Model): category = models.CharField(max_length=100, verbose_name='Category') Form: class NewsForm(forms.ModelForm): class Meta: model = News fields = 'title', 'description', 'category' -
how to implement raw sql query in DRF with paramters
Hi Everyone i am trying to implement raw sql query to create api in django framework and input paramter is team_id, start_date and end_date. like team_id=1 and start=2022-04-25 and end_date=2022-05-01, and temp1 query date like 7 date from 2022-04-25 to 2022-05-01. how will do this,please help me out. SELECT temp1.car_number,temp1.trips,temp1.status, case when temp1.date= %s then temp1.trip else 0 end as day1_trips, case when temp1.date= %s then temp1.trip else 0 end as day2_trips, case when temp1.date= %s then temp1.trip else 0 end as day3_trips, case when temp1.date= %s then temp1.trip else 0 end as day4_trips, case when temp1.date= %s then temp1.trip else 0 end as day5_trips, case when temp1.date= %s then temp1.trip else 0 end as day6_trips, case when temp1.date= %s then temp1.trip else 0 end as day7_trips from (SELECT date, car_number,driver_id,trips,car_status,status, case when trips=0 THEN else trips end as trip FROM fleet_car_dash_daily /this is input paramter/ WHERE team_id= %s and (date BETWEEN %s and %s))as temp1 group by temp1.date -
RuntimeError: __class__ not set defining 'AbstractBaseUser'
Django app works fine local, but when pushed to heroku build works, but deploy fails: RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? reading older posts this has been attributed to Django version / python version incompatibilities. This is a recent version: Django 3.2.13 and Python 3.9.12. This is confirmed to work together. Tried downgrading / upgrading, but without succes. Any one has an idea how to resolve? -
Error Using Ajax when I load from a differente file with Django
Im using JaxaScript(Jquery with Ajax) and my HTML Page all in the same file, but when I tried to code my JS and HTML in different files, I get an error when trying to ajax with Django. JS: $(document).on('click', '#add-button', function (e) { e.preventDefault(); value = $(this).data("forloopcounter"); value = value - 1 let variation_id = document.getElementsByClassName("select-variations")[value].attributes[2].nodeValue console.log(variation_id) $.ajax({ type: "POST", url: '{% url "cart:add" %}', data: { variationid: variation_id, productquantity: 1, csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { document.getElementById("cart-quantity").innerHTML = json.quantity }, error: function (xhr, errmsg, err) { console.log(xhr) } }); }) Note: I have a guess it's because of this url: '{% url "cart:add" %}', but I don't know how to fix. Note: when I ajax with all in the same page it works. Note it's not an importation error, when i execute console.log it works Error I get in the web: jquery.min.js:4 POST http://127.0.0.1:8000/%7B%%20url%20%22cart:add%22%20%%7D 404 (Not Found) -
Can I use "-" in django project name
While I am trying to create a new project in Django I got this error command used : django-admin startproject test-service 'test-service' is not a valid project name. Please make sure the name is a valid identifier. Then I tried with django-admin startproject test_service and it is working. Can you please confirm whether i can use dash in project name. I am planning to do a uniq naming convention for upcoming projects also. -
Django : stop access to my web app from being accessed on port 8000 and access only using the IP
I have deployed my Django web app on a digital ocean droplet. The python server is running on port 8000. python manage.py runserver 0.0.0.0:8000 I have configured apache web server to serve the requests. /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /etc/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #Serving static files Alias /static/ /etc/myproject/static/ <Directory /etc/myproject/static> Require all granted </Directory> <Directory /etc/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/etc/myproject python-home=/etc/myprojectenv WSGIProcessGroup myproject WSGIScriptAlias / /etc/myproject/myproject/wsgi.py </VirtualHost> Now when I am accessing my web app using the IP address X.X.X.X, I am able to see my app, however the app is also accessible on port 8000, X.X.X.X:8000. I want to prevent my app from being accessed on any other port except being accessed ousing IP. How can I do that? -
How Can I Search One Model and get Related Fields from Another Model in Django
I am working on a project in Django where I have two Models; Profile and submitted_apps. How do I efficiently relate these Models such that I would be able to get applicant's profile details like username, nation, state, upon search of submited_app Model. Is it good to use a OneToOneFields where as I did here on all Models. Understand that the submitted_apps Model is recording those applicants who successfully submitted their application form. I also have a ModelForm form named Applicant_Search_Form. Profile Model Code below class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=30, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) nation = models.CharField(max_length=10, choices=NATION, blank=True, null=True) state = models.CharField(max_length=20, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', upload_to ='profile_images') Submitted Model Code below" class submited_apps(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) confirm = models.BooleanField() date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.application == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.applicant def __str__(self): return f'Application Number: {self.application}-{self.applicant}' Here is my code for the ModelForm class Applicant_Search_Form(forms.ModelForm): class Meta: model = submited_apps fields = ['applicant'] Here is my view for the search … -
How to set Password Protected Pages on WeasyPrint PDF Builder?
I want to set Password Protected Pages onWeasyPrint PDF Builder. I am generated PDF using Weasyprint in Django and I want password encrypted after download PDF File. ** Here is code for generate PDF file.** def build_pdf(request,html_content, header_html=None, footer_html=None): def get_page_body(boxes): for box in boxes: if box.element_tag == "body": return box return get_page_body(box.all_children()) def get_page_and_body(html, css): if html is None: return None html = weasyprint.HTML( string=html, base_url=getattr(settings, "WEASYPRINT_BASEURL", None), url_fetcher=django_url_fetcher, ) css += "@page { margin 0 !important; }" document = html.render(stylesheets=[weasyprint.CSS(string=css)]) document_page = document.pages[0] document_body = get_page_body(document_page._page_box.all_children()) return ( document_page, document_body.copy_with_children(document_body.all_children()), ) def preprocess_html(html, context): for key, value in context.items(): html = html.replace(f"{{{{ {key} }}}}", str(value)) return html document = weasyprint.HTML( string=html_content, base_url=request.build_absolute_uri(), # base_url=getattr(settings, "WEASYPRINT_BASEURL", None), url_fetcher=django_url_fetcher, ).render() return document.write_pdf() can anyone help me? -
Get user posts using Class-based views?
Creating a blog project, how do I get the specific user's posts using Class-based views? What I have so far works, but it's incomplete. I am able to sort any user posts, but if I try to get the current logged-in user's posts, this happens to my side navbar. Here's what I have so far views.py class UserIssueListView(ListView): model = Issue template_name = 'issues/user_issues.html' context_object_name = 'issues' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Issue.objects.filter(author=user).order_by('-date_posted') nav.html <div id="nav-menu"> <ul class="nav-menu-items"> <div id="navbar-toggle"> <a href="#" class="menu-bars" id="hide-menu"> <i class="fas fa-bars nav-icon"></i> </a> <a href="#"><h3 class="text-white">Bug Tracker</h3> </a> </div> <hr /> <div class="nav-section"> <li class="nav-text"><a href="{% url 'dashboard' %}"><i class="fas fa-home nav-icon"></i>Dashboard</a></li> <li class="nav-text"><a href="{% url 'issues-home' %}"><i class="fas fa-fire nav-icon"></i>Recent Issues</a></li> <li class="nav-text"><a href=""><i class="fab fa-youtube nav-icon"></i>My Projects</a></li> </div> <hr /> <div class="nav-section"> {% for issue in issues %} <li class="nav-text"><a href="{% url 'user-issues' issue.author.username %}"><i class="fas fa-play-circle nav-icon"></i>My Posts</a></li> {% endfor %} <li class="nav-text"><a href=""><i class="fas fa-history nav-icon"></i>User Profile</a></li> <!-- <li class="nav-text"><a href=""><i class="fas fa-clock nav-icon"></i>Subscriptions</a></li> --> </div> </ul> </div> I suspect it's because of the for loop, but I'm stuck on how to proceed. How do I get only the current logged-in user's posts? -
How to add field to Django queryset
I'm learning DRF and trying to make website, where users can leave reviews for some products and also rate (like or dislike) this reviews. So now I'm stuck in like system. For example I have these models: class Review(models.Model): author = models.ForeignKey(User) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class Reaction(models.Model): author = models.ForeignKey(User) review = models.ForeignKey(Review, related_name='reactions') like = models.BooleanField() # True = like, False = dislike And I want to show list of posts with like and dislike counters and also somehow mark that logged user already liked or disliked a post. I made view to list posts with counters, but don't know how to include information about post was rated by user. class ListReviews(generics.ListAPIView): serializer_class = ProductReviewSerializer def get_queryset(self): product_slug = self.kwargs['product_slug'] queryset = Review.objects.filter(product__slug=product_slug).annotate( likes_count=Count('reactions', filter=Q(reactions__like=True)), dislikes_count=Count('reactions', filter=Q(reactions__like=False)), user_reaction=... ) return queryset Is it possible at all? Or it's better to just make another endpoint to get user reactions for current page? -
Django password change view
I am trying to implement password changing in my django app, with my own template and form. So i decided to create my own view function instead of using django's. The problem Im having is the change password page doesn't change the password. I can't figure out what my problem is and could really use some help, thanks. chgpwd.html template {%extends 'auth_base.html'%} {%load static%} {%block title%} CX Labs SOC LogIn {% endblock%} {%block content%} <div class="wrapper" style="max-width:450px"> {%if form.errors %} <p style="text-align:center; margin-bottom:30px; color:red;">something went wrong</p> {%endif%} <div class="logo"> <img src="{%static 'website/cxlabs.jpg'%}" alt=""> </div> <div class="text-center mt-4 name"> CXLabs SOC <br/> Password Change</div> <form method="post" class="p-3 mt-3"> <div class="form-field d-flex align-items-center"> <span class="far fa-user"></span> {{form.oldPwd}} </div> <div class="form-field d-flex align-items-center"> <span class="far fa-user"></span> {{form.newPwd1}} </div> <div class="form-field d-flex align-items-center"> <span class="fas fa-key"></span> {{form.newPwd2}} </div> <button type="submit" class="btn mt-3">Change Password</button> {%csrf_token%} </form> </div> {%endblock%} Urls.py import django from django.contrib import admin from django.contrib.auth import views as av from django.urls import path, include from authentication.forms import CustomAuthForm, CustomPwdChgForm from website import views from authentication import views as authv urlpatterns = [ path('logout/', av.LogoutView.as_view(template_name='registration/logout.html', next_page=None), name='logout'), path('chgpwd/', authv.changepwview, name='chgpwd'), path('sign/', include('sign.urls')), path('download/<int:id>', views.zip_download, name='zipDL') ] views.py from django.shortcuts import render, redirect from django.contrib.auth … -
Django "duplicate key value violates unique constraint" because of the save method
I am trying to update an existing instance from a model in Django admin interface but I'm getting django.db.utils.IntegrityError: duplicate key value violates unique constraint because of the save method. According to the documentation, the save method should not have any problems UPDATING the model, but it seems like the primary key is set to a value that evaluates as False. https://docs.djangoproject.com/en/4.0/ref/models/instances/#how-django-knows-to-update-vs-insert . Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save() and the object’s primary key attribute does not define a default, Django follows this algorithm: If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database), Django executes an INSERT. Now this is my model and the save method: class Examene(models.Model): saptamani = models.IntegerField(default=3, validators=[MinValueValidator(1), MaxValueValidator(5)]) zile = models.IntegerField(null=False, blank=True) profesor = models.ForeignKey(Materii_profesor, on_delete=models.CASCADE) materii = models.ManyToManyField(Materie) def save(self, *args, **kwargs): self.zile = (self.saptamani * 5) super(Examene, self).save(self, *args, **kwargs) I am … -
Microsoft auth doesn't redirect after successful login
I am integrating Microsoft's login using Django Microsoft Authentication Backend. I have managed to to get a successful response and create a new "Microsoft" user and am able to see it in the admin site if I login to the admin site as a local superuser. When I login using Microsoft, the pop up window to Microsoft opens, authenticates, and it doesn't redirect to anywhere. But, with a local non-Microsoft user, it can successfully redirects to the admin panel. I don't understand why this is so, it doesn't make sense. I have a frontpage constructed that I would like this login page to redirect to after successful login. I have included LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' in the settings.py file but that does not change anything. -
Python selenium send_keys not working on password field
send_keys() works with the username field but not the password field. Here is my code: class PpeLiveTest(LiveServerTestCase): # test that the first cell for the tennessee total row is the correct sum # for quince and allenbrooke for the incentives table def test_sums_incentives_tennessee(self): options = webdriver.FirefoxOptions() options.add_argument("--headless") driver = webdriver.Firefox(options=options) driver.get('https://[redacted]/pr-run-ppe?group=MS%2FTN%2FLA&check_date=05%2F01%2F2022') # login first username_element = driver.find_element_by_id('id_login') username_element.send_keys('[redacted]') password_element = driver.find_element_by_id('id_password') password_element.send_keys(os.environ.get('ADMIN_PASS')) login_button = driver.find_element_by_xpath('/html/body/div/div/div/form/button') login_button.click() I look at driver.page_source in the console when running this test. It's still the login page. username is filled with the [redacted] as expected but the password field is blank. Anyone know why? os.environ.get('ADMIN_PASS') is not blank. password_element is the correct element that we expect -
HTMX does not trigger get on load if it's a radio check
I am working on Django and using htmx I have checkbox input, select tag and radio input both work as expected on page load it sends a request to an endpoint to the server to retrieve certain information which is rendered through a partial template. The problem is only radio deosn't trigger it when the appropriate input value is checked. Here is the radio input. <input id="option_{{ option.id }}" class="form-check-input" type="radio" name="radio_{{ question.id }}" value="{{ option.id }}" {% if question.required %} required {% endif %} {% if question.disable %} disabled {% endif %} {% if option.id == radio_response %} checked {% endif %} hx-get="{% url 'survey:dynamic_loader' %}" hx-trigger="load, change" hx-target="#radio-result-{{question.id}}"/> Is this a normal behaviour for htmx? Or I am doing something wrong. -
How to pass undefined parameters in Serializer DRF?
I have an API in DRF where I want to get information from a non-relational database. The parameters of the API request vary, they can be many or few, and they can change. For this reason, I would like to know how I can pass multiple undefined arguments/parameters to a serializer. # serializers.py class MySerializer(Serializer): foo_1 = IntegerField() foo_2 = CharField() foo_3 = DictField() foo_n = ... ... Instead of this I would like to do this: # serializers.py class MySerializer(Serializer): # have undefined number of parameters # views.py class MyView(APIView): ... def post(self, request): params = requests.data.get('my_params') # dictionary object I'm very new to DRF so I'm not sure how to do it. I found solutions using ModelSerializer, but still I need to define a model, the parameters that I want are undefined in number and datatpye, but the output as a dictionary. -
Factory Boy Iterator generates the wrong order
I use Iterator to create a strict sequence of values. class MyModelFactory(DjangoModelFactory): class Meta: model = MyModel django_get_or_create = ("first_field",) first_field = Iterator(["value_1", "value_2", "value_3", "value_4"]) second_field = Iterator("aaaa", "bbbb", "cccc"]) third_field = Iterator([1, 2, 3, 4]) I expect that result should be next: [ ("value_1", "aaaa", 1), ("value_2", "bbbb", 2), ("value_3", "cccc", 3), ("value_4", "aaaa", 4) ] But the outcome is unpredictable: [ ("value_1", "aaaa", 4), ("value_2", "bbbb", 3), ("value_3", "cccc", 1), ("value_4", "aaaa", 2) ] And when I use this MyModelFactory as a RelatedFactory two times in row, my database raise an error duplicate key value violates unique constraint third_field. Yes third_field must be unique. The question is why does this error occur if I use django_get_or_create? Any ideas? -
Problem with aggregation by annotated fields
I have models: class Publisher(Model): name = TextField() class Author(Model): name = TextField() class Book(Model): publisher = ForeignKey("Publisher") author = ForeignKey("Author") class Magazine(Model): publisher = ForeignKey("Publisher") writer = ForeignKey("Author") I want to know which authors wrote for publishers. My version is this: from django.db.models import TextField, F, Subquery, OuterRef from django.contrib.postgres.aggregates import StringAgg # I use postgres # to lead to the same name books = Book.objects.annotate(author_name=F("author__name")) magazines = Magazine.objects.annotate(author_name=F("writer__name")) books = books.values("publisher_id", "author_name") magazines = magazines.values("publisher_id", "author_name") product = books.union(magazines) # !! here I have a problem with grouping product = product.group_by( "publisher_id" ).annonate( author_names=StringAgg("author_name", ";") ) publishers = Publisher.objects.all().annotate( author_names=Subquery( product.filter(publisher_id=OuterRef("id")).values("author_names")[:1], output_field=TextField() ) ) # I was expecting something like # name | author_names # ------------------------------------------ # Publisher1 | Author1;Author2;Author3 # Publisher2 | Author2 # Publisher3 | Author2;Author3 The problem is that QuerySet has no .group_by() method, instead the .values() method is suggested (product.values("publisher_id").annonate(...)). But this is complicated by the fact that I had previously called .values("publisher_id", "author_name") to bring two different models into the same view. I also tried using .only("publisher_id", "author_name"), but (maybe it's a Django bug) this method can't work together with annotated and normal fields. Is there any way to fix this problem or … -
NoReverseMatch error when filtering from Django ListView ('is not a valid view function or pattern name')
I'm trying to filter the objects from a Django ListView to render them in a template, but I'm getting a 'NoReverseMatch at' error ('Reverse for 'advanced' not found. 'advanced' is not a valid view function or pattern name'). Here are my Model, View, URL, and href: **Model** class Course(models.Model): location = models.ForeignKey(Location, blank=True, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) level = models.CharField(max_length=200) date = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): # establishes canonical url for the Course model return reverse('course_detail', args=[str(self.id)]) **View** class AdvancedListView(ListView): model = Course context_object_name = 'course_list' template_name = 'courses/advanced.html' def get_queryset(self): return Course.objects.filter( level__icontains='Advanced') **URL** from django.urls import path from .views import CourseListView, CourseDetailView, SearchResultsListView, AdvancedListView urlpatterns = [ path('', CourseListView.as_view(), name='course_list'), path('<int:pk>/', CourseDetailView.as_view(), name='course_detail'), path('search/', SearchResultsListView.as_view(), name='search_results'), path('courses/', AdvancedListView.as_view(), name='advanced'), ] **Link** <a class="dropdown-item" href="{% url 'advanced' %}">Advanced</a> Any advice greatly appreciated! -
Calculate the number of deltas between two dates
I want to calculate how many relativedelta() there are between two date objects. My code is below, it's not working though as a relative delata cannot divide a date, but maybe it shows what I'm trying to do. For example, if my relative delta is two weeks relativedelta(weeks=1) and my dates are 2022-05-01 and 2022-05-15 then two of the 1 week deltas will fit into the two dates that are two weeks apart. delta=relativedelta(days= self.cleaned_data['delta_days'], months=self.cleaned_data['delta_months']) no_loops = (self.cleaned_data['to_date'] - self.cleaned_data['from_date']) / delta if no_loops > 36: raise ValidationError('Too many iterations.') -
Django : Updating ForeignKey automatically with 'add' button
Using Python 4.03. I have two models that are connected, with Asset: class Asset(models.Model): Order_Number = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True) Asset_QR = models.CharField(max_length=100, default='') .... more fields below being a child to Order: class Order(models.Model): Order_Number = models.CharField(max_length=100) Customer = models.CharField(max_length=100, default='') Customer_Address = models.CharField(max_length=100, default='') What I'm trying to do is to create a simple "Add" button next to a list of assets that are not attached to any Order yet. I've created a view: def attachassets (request, id): order = Order.objects.get(id=id) #This displays the Order I want to add my assets to assets = Asset.objects.exclude(Order_Number__isnull=False) #This filters to display only Assets that have no Order assigned On my HTML page I display my order info and below it just a simple table which iterates over assets and has and "ADD" button next to them: <table class="table table-hover"> <thead class="thead-dark"> <tr> <th scope="col">Attach</th> <th scope="col">Asset</th> </tr> </thead> <tbody> {%for asset in assets %} <tr> <td> <form action="" method=POST> {% csrf_token %} <button type="submit" class = "btn btn-dark", name="add" value={{order.id}}>Add</button> </td> <td><a class="btn btn-outline-secondary" name="assetid" value={{asset.id}} href='/asset/{{asset.id}}'>{{asset.Asset_QR}} {{asset.Make}} {{asset.Model}} {{asset.Serial_Number}}</a></td> </tr> </form> {% endfor %} </tbody> </table> Then in my Views I tried the following: if request.method == 'POST': x … -
Implimenting a ranking algorithm in Django query
I currently have upvotes and downvotes stored. I am trying to make a ranking algorithm as such ranking = log(upvotes - downvotes) But in doing my query in Django I am using annotate``as such, and am unsure where I would add in the math.log` to the annotate so it ranks it by log? Here is the code defeniciones = Palabra.objects.prefetch_related( 'tag_set' ).filter( nombre__iexact=palabra, aprobada=True ).annotate(total_votes=Count('userUpVotes') - NullIf((Count('userDownVotes')) ,0)).order_by(F('total_votes').desc(nulls_last=True),"total_votes") -
Django CreateView not saving all fields...but UpdateView does
I'm using Django CBV's to allow managers to add and update user information in the front end. When I create a new user, two of the fields are not saved to the database; Django's built in permission groups, and a manytomanyfield that determines what newsfeeds the user can view. The strange thing is, when I update the user using an updateview, it saves just fine. No errors when I submit on the createview, and all o Am I missing something blatantly obvious here? Both templates are laid out the same, both with enctype="multipart/form-data" method="post" . Django 4.0.4 / Allauth Model: class CustomUser(AbstractUser): #auth id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False, primary_key=True) username = models.CharField(max_length = 50, blank=True, null=True, unique=True) email = models.EmailField(gettext_lazy('email address'), unique=True) #Employment info department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=False) job_title = models.CharField(max_length = 50, null=True, blank=False) #Personal Info profile_picture = ProcessedImageField( upload_to='profile_images/', processors=[ResizeToFill(width=1000, height=1000, upscale=True)], format='JPEG', options={'quality': 100}, null=True, blank=True ) # Newsfeeds viewable_newsfeeds = models.ManyToManyField(Department, blank=True, related_name='viewable_newsfeeds') #Permissions department_head = models.OneToOneField(Department, related_name='department_head', on_delete=models.SET_NULL, unique=True, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'job_title'] class Meta: ordering = ['first_name',] verbose_name = "User" verbose_name_plural = "Users" permissions = [ ('manager_dashboard', 'Can view the manager dashboard'), ('manager_content', 'Can view … -
How to get the code returned by Cognito Hosted UI Autentication in Django?
I want to implement the Cognito Hosted UI for some users in my Django application. I have successfully been able to redirect the users to the desired url for authentication using the following: return redirect(https://....amazoncognito.com/oauth2/authorize?client_id=....redirect_uri=localhost). I am able to successfully authenticate and redirect back to my localhost where the url in the browser is localhost/?code=xyz. I do not understand how I can retrieve this code xyz back in python to perform next steps? I see that in the Django Terminal that it reads the required code. This is what the terminal shows: [04/May/2022 16:08:15] "POST /login HTTP/1.1" 302 0 [04/May/2022 12:09:04] "GET /?code=xyz HTTP/1.1" 200 8737 I just do not know how to get this code xyz in my views.py so that I can continue the login. I tried variations of request.GET that did not work. Any help is appreciated!!