Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve UnicodeDecode error in django
I was making a project but I accidentally deleted the git changes. The files were all lost but fortunately i recovered them using Recuva. The problem i am now facing is this, when i open the website, the first page shows up normally but the when i click that object to get its details, i get this error: UnicodeDecodeError at /cartoon/2 'utf-8' codec can't decode byte 0x9d in position 0: invalid start byte can someone help me with this, thank you in advance -
Array validation using AJAX: show error message
Trying to validate arrays via FormRequest validation. I can access the error message for the field 'name' as data.responseJSON.error.name[0] and show it to the user. error: function(data, xhr, errmsg, err){ console.log("data") console.log(data.responseJSON) $(".form-alert").fadeIn(); $(".form-error").text(data.responseJSON.error.phone[0]); This works fine. With the same way i access error messages for other fields, however i cannot modify script to handle all errors, i can make it work only with one field as shown above. How can i modify script to catch errors for example for 'field1', 'field2'. Thank you -
Use django sessions for requests not from a browser (terminal + mobile app)
I'm currently working on a mobile app development and using Django for backend (and Kivy for GUI frontend) services and database and trying to use sessions for login purposes. As I'm compiling the app from the terminal, everytime I launch build and launch it, try to log in, a new session is created. I can see that in the database as I'm the only one to test it and that there are more than 100 rows in django.session table. The server is locally runned. So what I do, at the moment is: get request to check if something is stored in request.session['used_id'] if nothing then display signin/signup forms and in this case, I created a new session at the login. Actually I've no idea on how I can use sessions to stay connected for my tests in the terminal. In the future, let users stay connected on the app on their devices might be an issue too but I've already that asnwer that can be very useful. Is there a way to do that? Thank you! -
prevent user creating if another create unsuccessful django
Probably there is the answer to this question, but I couldn't find it. How to prevent User - from django.contrib.auth.models import User, creation if userProfileSerializer creating is unsuccessful. I saw a database transaction is an option but it says While the simplicity of this transaction model is appealing, it also makes it inefficient when traffic increases. Opening a transaction for every view has some overhead. The impact on performance depends on the query patterns of your application and on how well your database handles locking. @api_view(['POST']) @permission_classes([AllowAny]) def register(request): ''' Registers user to the server. Input should be in the format: {"username": "username", "password": "1234abcd"} ''' # Put the data from the request into the serializer serializer = CreateUserSerializer(data=request.data) # Validate the data if serializer.is_valid(): # If it is valid, save the data (creates a user). serializer.save() userProfileSerializer = UserProfileSerializer(data=request.data) userProfileSerializer.context['user_id'] = serializer.data['id'] userProfileSerializer.is_valid(raise_exception=True) userProfileSerializer.save() Serializer classes class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name',) extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'organization', 'user_id') def create(self, validated_data): user_id = self.context["user_id"] user_profile = UserProfile(**validated_data, user_id=user_id) user_profile.save() … -
How to apply colour in row according to condition in python Django
table.py class resultTable(BaseTable): class Meta(BaseTable.Meta): model =Modelname attrs = {'class': 'table table-striped table-bordered table-hover row-color=green' , 'width': '70%'} fields = ( "field1", "field2 ", "status", "field4", "field5" ) admin.py @admin.register(Modelname) class resultAdmin(admin.ModelAdmin): list_display=('field1', 'field2 ', 'status','field4 ','field5') how to apply the condition in table. if the status is warring and ok the row color should be yellow. -
Running two modals works runnig a third one in a different bootstrap tab does not
I am using django-bootstrap-modal-forms. I have bootstrap tabs with crispy forms I made a modal for files and it worked; But I am trying to add two modals; one for authors the other for translators. Ill show the code that is loaded in a table. {% include "_modal.html" %} <div id="linkeddocuments"> <div class="col-12 mb-3"> {% include "_authors_table.html" %} </div> </div> <div id="searchdocumentpanel" class="container"> <div class="row"> <div class="col"></div> <div class="col"> <button type="button" class='btn btn-primary btn-danger' id='create-author-async'><span class="fa fa-plus mr-2"></span>new author async</button> <br/> <br/>Search Authors:<br/> <br/> <input type="text" id="id_search_authors"> </input> </div> <div class="col"></div> </div> <br/> <div class="col-12 mb-3"> {% include "_authors_candidates_table.html" %} </div> </div> <div id="linkeddocuments"> <div class="col-12 mb-3"> {% include "_translators_table.html" %} </div> </div> <div id="searchdocumentpanel" class="container"> <div class="row"> <div class="col"></div> <div class="col"> <button type="button" class='btn btn-primary btn-danger' id='create-translator-async'><span class="fa fa-plus mr-2"></span>new translator async</button> <br/> <br/>Search Translator:<br/> <br/> <input type="text" id="id_search_translators"> </input> </div> <div class="col"></div> </div> <br/> <div class="col-12 mb-3"> {% include "_translators_candidates_table.html" %} </div> </div> <script type="text/javascript"> $(function () { var asyncSuccessMessageCreateAuthor = [ "<div ", "style='position:fixed;top:0;z-index:10000;width:100%;border-radius:0;' ", "class='alert alert-icon alert-success alert-dismissible fade show mb-0' role='alert'>", "Success: Author was created.", "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>", "<span aria-hidden='true'>&times;</span>", "</button>", "</div>", "<script>", "$('.alert').fadeTo(2000, 500).slideUp(500, function () {$('.alert').slideUp(500).remove();});", "<\/script>" ].join(""); var asyncSuccessMessageUpdateAuthor = … -
Query from template in Django
I am coming from Ruby-on-Rail background. I have a user table and an employee table. In the index page of all the employee, I am looking to retrieve their first name which is in the user model and not in the employee table. I tried the following which is very rubyesque: {% User.objects.filter(id=employee.user_id) %} But i get the error: Invalid block tag on line 163: 'User.objects.filter(id=employee.user_id)', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Although the user_id clearly exists. What is the best way for such queries in Django please ? -
Django Rest Framework: router is not working
I have used DefaultRouter() and viewset. Here is the code from rest_framework import routers from .api import TweetViewset, OwnersTweet from django.urls import path router = routers.DefaultRouter() router.register('', TweetViewset, 'tweets') router.register('own/', OwnersTweet, 'owner') And project-level urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), path('tweet/', include('tweets.urls')) ] When I send a request to '<URL>/tweet/own/' It returned an error Not Found. But <URL>/tweet/ is working. OwnersTweet view also working fine. But I think there is smth wrong with URL. Can you help, please? -
create link of selenium file not to call link in selenium file
all fresh to codding world. I am working on python and created a random project of selenium I am tired of searching on google. I just want to create a simple link (localhost) of my selenium project. So that whenever I hit the link in a browser, it should start my project testing(opening crome->link->logging, etc). I don't want to run it from the terminal. as I want to add jquery -
CRUD web application with Bigquery?
I have a bigquery table about 1000 rows, i need to insert,delete and update values in this through a web interface(the table cannot be migrated to any other relational or non-relational database). The web application will be deployed in google-cloud on app-engine and the user who acts as admin and owner privileges on Bigquery will be able to create and delete records and the other users with view permissions on the dataset in bigquery will be able to view records only. I am planning to use the scripting language as python, server(django or flask or any other)-> not sure which one is better The web application should be displayed as a data-grid like appearance with buttons like and create,delete or view according to their roles. I have done anything like this in python,bigquery and django. I am seeing examples only related to django with their inbuilt model and not with big-query. Can anyone please help me and clarify whether this is possible to implement and how? -
Django <uuid:id> redefinition error. Pattern Problem
i've become an ErrorMessage because i think i have the wrong reference pattern in my url.py. In my models.py i create this models class Quiz(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100) details = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return '/quiz/quiz' class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) fk_quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.CharField(max_length=100) class Answer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) fk_quizfrage = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=100) correct = models.BooleanField(default=False) An in my urls.py i make refernces like this: path('quiz/<uuid:id>/', QuizDetailView.as_view(), name='quiz-detail'), I think i have to change the pattern from <uuid:id> The complete Error is: :in _parse raise source.error(err.msg, len(name) + 1) from None re.error: redefinition of group name 'uuid' as group 2; was group 1 at position 90 -
How to make it such that if comments have been edited before, an "edited" permanent message will be displayed beside the comment?
How to make it such that if comments have been edited before, an "edited" permanent message will be displayed beside the comment? So that everyone will be able to see that the comment has been edited before. (it'll be good if i can keep a copy of the original pre-edited message too, but if thats too difficult, i'm just hoping to display an "edited" permanent message will be displayed beside the comment. models.py class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE) body = models.TextField() class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) views.py def edit_own_comment(request, post_id): context = {} comment = get_object_or_404(Comment, id=post_id) if request.method == 'POST': form = UpdateCommentForm(request.POST or None, instance=comment) if form.is_valid(): obj.save() messages.success(request, 'Your comment has been edited', extra_tags='editedcomment') return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug })) form = UpdateCommentForm( initial = { "body": comment.body, } ) context['form'] = form return render(request, 'HomeFeed/edit_comment.html', context) class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() blog_post.save() forms.py class UpdateCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] def save(self, commit=True): comment = self.instance comment.body = self.cleaned_data['body'] if commit: comment.save() return comment detail.html {% for comment in … -
Django: Create a custom order of objects in django model
I'm trying to build a teaching website of sorts in Django. I have a model called Test: class Test(models.Model): test_name = models.CharField(max_length=100) test_directions = models.TextField(null=True) test_status_new = models.ManyToManyField('StudentProfile', related_name='test_status_new') test_status_good = models.ManyToManyField('StudentProfile', related_name='test_status_good') test_status_repeat = models.ManyToManyField('StudentProfile', related_name='test_status_repeat') test_repeat_due = models.IntegerField(default=6) test_status_due = models.ManyToManyField('StudentProfile', related_name='test_status_due') def __str__(self) -> str: return f"{self.test_name}" def __repr__(self) -> str: return f"<{self.test_name}>" I'd like to give them a custom ordering somehow. I am displaying them in a table like so: and would like to change the order of each individual tests from the two buttons in the Order column. If I click Up, the test moves one row up. If I click down, the test moves down one row. How would I implement something like this? -
How to disable a decorator on a method, if that method is called in django tests?
I have a function that is like: @dec_func def a(): do_something; In my django tests this function is ran in execution. Now i want that whenever the tests run my function a should not get decorated dec_func but if the function runs in development or production environment, method should be decorated. How to do so. -
Adding a second password field to Django User model
I would like to add a second password field override_password to my User model. It will be used for admin overrides so I want it to be separate to the users password. I have defined the additional password field below with 73 max because I want it to be hashed, but need advice on how to go about setting this password. User model: class User(AbstractUser): """Default user.""" #: First and last name do not cover name patterns around the globe name = CharField(_("Name"), blank=True, max_length=255) override_password = models.CharField(max_length=73) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) Setting the password in forms.py: class UserUpdateForm(ModelForm): override_password = forms.CharField( label="Override password", max_length=8, strip=False, widget=forms.PasswordInput, ) class Meta: model = User fields = ['name', 'override_password'] view.py: class UserUpdateView(LoginRequiredMixin, AdminRequiredMixin, UpdateView): form_class = UserUpdateForm class Meta: model = User def get_success_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) def get_object(self): return User.objects.get(username=self.request.user.username) def form_valid(self, form): messages.add_message( self.request, messages.INFO, _("Info updated successfully") ) return super().form_valid(form) user_update_view = UserUpdateView.as_view() So right now it just saves in plain text. I have tried using make_password and then setting that in the password field, but then when I tried to use check_password, … -
Django weird symbols while downloading excel file
Django returning weird symbols while trying to download excel file file_name = 'data.xlsx' response = HttpResponse(open(file_name, 'rb'), content_type="application/xlsx") response['Content-Disposition'] = "attachment; filename=Report-{}.xlsx".format(datetime.now().strftime("%d.%m.%Y")) return response -
How to query only the pending interest and not interest that is already accepted/declined?
How to query only the pending interest and not interest that is already accepted/declined? Currently, i am able to query the number of interests that has been submitted. How can I query only the interest that has the status on pending and not accept/decline for my views? I tried to do total_interests = blog_post.interest_set.status.pending.count() but got AttributeError..'RelatedManager' object has no attribute 'status' models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class Interest(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) class InterestInvite(models.Model): ACCEPT = "ACCEPT" DECLINE = "DECLINE" PENDING = "PENDING" STATUS_CHOICES = [ (ACCEPT, "accept"), (DECLINE, "decline"), (PENDING, "pending"), ] interest = models.OneToOneField(Interest, on_delete=models.CASCADE, related_name="interest_invite") status = models.CharField(max_length=25, choices=STATUS_CHOICES, default=PENDING) views.py class BlogPostMixin(object): model=BlogPost class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() total_interests = blog_post.interest_set.count() context['total_interests'] = total_interests -
I'm trying to add comment posting on my Django website
I was trying to create a form with django, but it raises NoReverseMatch error. Django version 3.1.5. Views: try: a = Article.objects.get(id =article_id) except: raise Http404("Article not found") a.comment_set.create(author_name= request.POST['name'], comment_text =request.POST["text"]) return HttpResponseRedirect(reverse("aricles:detail", args = (a.id,))) Urls: app_name = "articles" urlpatterns = [ path("", views.index, name="index"), path("<int:article_id>", views.detail, name="detail"), path("<int:article_id>/leave_comment", views.leave_comment, name="leave_comment"), ] Html: <form action="{% url 'articles:leave_comment' article.id%}" method="POST"> {% csrf_token %} <input type="text" required placeholder="Your name" name = "name"><br> <textarea name="text" required="" placeholder="Comment" cols="30" rows="10"></textarea><br> <button type="submit">Post a comment</button> </form> Thanks for your help! -
Django queryset top 3 of sum for each year
I need to find the top 3 customers per year from the sum of their related invoices. So, I got 2 models Customer related to Invoice by a FK. I get the total sales foreach as following: qs = Company.objects\ .filter(invoices__status=Invoice.PAID)\ .annotate(year=TruncYear('invoices__created')).values('year', 'name')\ .annotate(total=Sum('invoices__total'))\ .exclude(total=None)\ .order_by('year', 'total') But what if I'd like to get only the top 3 per year? Should I iterate manually: years = [year.year for year in set(qs.values_list('year', flat=True))] for y in years: new_qs = qs.filter(year__year=y).order_by('-total')[:3] my_top.append(new_qs) Isn't it a way to get the limited queryset in one shot? -
How to set value of model field as currently logged user? Django
I have Event model which has a field creator as ForeignKey with attribute User. In views.py I have create_event which creates event using EventForm. How to set default value of creator in EventForm as currently logged user? It is set default as admin, I do not want to set it manually every time I create an event, because it would me annoying if I have a lot of users created. modely.py class Event(models.Model): SPORT = ( ('Football', 'Football'), ('Volleyball', 'Volleyball'), ('Basketball', 'Basketball'), ('Futsal', 'Futsal'), ('Tennis', 'Tennis'), ('Handball', 'Handball'), ('Ice Hockey', 'Ice Hockey'), ('Paintball', 'Paintball') ) creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) sport = models.CharField(max_length=20, null=True, choices=SPORT) event_name = models.CharField(max_length=30) event_date = models.DateTimeField(default=date.today()) end_event_date = models.DateTimeField(default=date.today()) current_members = models.IntegerField(default=1) total_members = models.IntegerField(default=0) event_location = models.CharField(max_length=50) cost = models.FloatField(default=0, max_length=5) description = models.CharField(max_length=300, blank=True) def __str__(self): return self.event_name views.py @login_required(login_url='login') def create_event(request): form = EventForm() if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'events/create_event.html', context) forms.py class EventForm(ModelForm): class Meta: model = Event fields = ['creator', 'sport', 'event_name', 'event_date', 'end_event_date', 'total_members', 'current_members', 'event_location', 'cost', 'description'] -
Django User.objects.filter() with list of strings?
I am trying to filter QuerySet from a list of strings using __in lookup, I am not sure how I can get all users with first_name in the list. names = ['Bob', 'Tina', 'Ankit'] User.objects.filter(first_name__in=names) What it's returning is, First correct match ignoring other items in list. This lookup works fine with list of integers ie. ids = [1, 2, 3] User.objects.filter(id__in=ids) May be I've to use some other lookup, but I am not sure which one. Thanks -
Fieldset values displaying in profile page but if another person registered it showing error in profile page -django
I have member table for registered persons.. I want to display that member table values of particular person in profile page who is logged in... i used Member.objects.get() data is displaying in the profile page of the person who is logged in. but if another person registered it showing error in profile page like.. this is my error MultipleObjectsReturned at /web/profile/ get() returned more than one Member -- it returned 2! this is my views.py code def profile(request): member = Member.objects.get() print(member.Email) return render(request, 'web/profile.html',{'member':member} ) -
Flutter Razorpay Payment gateway integration from Django rest Framework
I am using razorpay payment integration for my project. I am stucked in one prblm. The problem is that when I am pressing the Success button after payment peoceed, I want to Store the data into db like payment_id, order_id, payment_signature from an API call. The API is written in django. How can I store thise data to the db? Is it depends on the API? Or I can directly do this from flutter sdk integration itself?? Can anyone have any Idea regarding this? -
How to connect pinax.points and pinax.badges with oscar.customer user model?
How to connect pinax.points and pinax.badges with oscar.customer user model ? After forking customer app from oscar -> , e.g: I declared this model : class UserBadge(models.Model): user = models.ForeignKey( AUTH_USER_MODEL, related_name="badges_earned", on_delete=models.CASCADE, null=True, verbose_name=_("User")) I want to add new tow new fields : points from pinax.points, badge from pinax.badges. -
When I try to logout showing Page not found (404)
Whenever I click log out this error is showing My html is: views.py : apps urls.py : procjects urls.py :