Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which URL link pattern should I use in Django
Please help me take a look at this question. I just find out there are some ways to create a link in Django: 1. <a href='/blog/{{ object.id }}'>{{ object.title }}</a> 2. <a href='{% url "blog:detail" id=object.id %}'>{{ object.title }}</a> 3. <a href='{{ object.get_absolute_url }}'>{{ object.title }}</a> When should I use these pattern? Are there any special for earch one? Thank you so much. -
logging users actions in django
seeking to log what users do in mi django app, i try to log when a django session is opened and also when a view is executed. To do that i found a solution but i wonder if it is correct and also if there are not other better ways or tools to do that. Could somebody tell me ? Thanks a lot. the log file is written like this : # in case django session open datetime / ----New Session ------ / session_id # in case view execution datetime / -session_id- / view_name I have for this a function : # logs visited page and session id and session opening def f_lou_log(request, page="???"): if not request.session.session_key: request.session.create() logger.warning(str(datetime.datetime.now()) + " -------------------- New session --- #" + request.session.session_key) logger.warning(str(datetime.datetime.now()) + " - #" + request.session.session_key + " - " + page) return 1 and at the beginning of every view i call the function like that : def some_view(request): # log record v_wait = f_lou_log(request,"some_view") # (...) here is the view code and for instance my log file looks like that : 2021-09-24 17:24:27.110718 -------------------- New session --- #x0u30n1th4b3z0otv311883ikf0d8y34 2021-09-24 17:24:27.110718 - #x0u30n1th4b3z0otv311883ikf0d8y34 - home 2021-09-24 17:24:31.373336 -------------------- New session … -
django rest framweork: combine ValidationError from multiple validation
Let's say I have the following serializers: class AnswerSerializer(ModelSerializer): answer_text=CharField() def validate_answer_text(self, value): ... return value def validate(self, value): ... return value class QuestionSerializer(ModelSerializer): question_text=CharField() answer=AnswerSerializer(many=True, read_only=False) def validate_question_text(self, value): ... return value def validate(self, value): ... return value If validate_answer_text or validate in AnswerSerializer or validate_question_text in QuestionSerializer raise a ValidationError, the validate of QuestionSerializer won't be runned. Thus, I cannot explain all the problem of the POST datas. Is there a way to run the validate function of a serializer even if one of it's field validator or children serializer validation failed and then combine all the errors ? I have tried the following but did not succeed make it work properly. It does run both validate function and other validators but you cannot nest AllErrorSerializer and more importantely, it does not work when you do not have error: you cannt save instance because you have inspect serializer.data. -
Why does django cart template_tags bring the error message object has no attribute 'is_authenticated'
register = template.Library() @register.filter def cart_item_count(user): if user.is_authenticated: qs = Order.objects.filter(user=user, ordered=False) if qs.exists(): return qs[0].item.count() return 0 -
Django query is not reaching to the the page
I want to add a contact html page in my existing project. I put the html page in template where homepage is already residing. Now I have added a url for contact in project level directory which directing the query to app level url. This app level has a contact function in views. I have setup app level url as well but contact link isnt responding. In debug its showing a 200 ok status. Could somebody can point out to me what wrong i am doing??? This is project level url file urlpatterns = [ path('admin/', admin.site.urls), path('', include('articles.urls')), path('contact', include('articles.urls')), ] this is app level url file urlpatterns = [ path('', views.articles, name='articles'), path('', views.contact, name='contact'), ] this is view function in which one function is returning article page but other one not responding def articles(request): return render(request, 'articles/home.html') def contact(request): return render(request, 'articles/contact.html') -
Field 'id' expected a number but got '' error on creating table entry
I'm working on an ebay style auction website. I've created my models and have a form that creates a new listing. When the POST request goes out, the listing gets created when I try to add the listing to the bid, I get the error Field 'id' expected a number but got '' I'm fairly new to Django so if you need anything that I haven't included, please let me know! models.py class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() author = models.ForeignKey('User', on_delete=models.CASCADE, name='author') category_id = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="") def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = models.IntegerField() listing = models.ForeignKey('Listing', on_delete=models.CASCADE, name='listing', default="") def __str__(self): return f'{self.slug} ({self.price})' views.py def newListing(request): try: if request.method == "POST": newListingForm = NewListingForm(request.POST) if newListingForm.is_valid(): title = newListingForm.cleaned_data['title'] description = newListingForm.cleaned_data['description'] url = newListingForm.cleaned_data['url'] bid = newListingForm.cleaned_data['bid'] category_name = newListingForm.cleaned_data['category'] category = Category.objects.get(title=category_name) category_id = category.id current_user = request.user l = Listing(title=title, description=description, url=url, author=current_user, category_id=category_id) l.save() print(l.id) b = Bid(price=bid, bid_count=0) b.listing.add(l.id) b.save() return HttpResponseRedirect(reverse("index")) else: newListingForm = NewListingForm() return render(request, "auctions/newListing.html", { 'form': newListingForm }) except Exception as exc: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, exc_obj, fname, exc_tb.tb_lineno) … -
django define a json type instead of jsonb type on models
I am using the JSONField for my Django model for JSON type but in the background, it makes my attributes column type JSONB which I don't want to do here because it breaks my exact order of JSON'S internal field that I pushed from my frontend app. You can see the order of fields is not my exact value. To store it as it is, I need to use JSON instead of jsonb. So my question is how to do that? What I pushed: { "type": "array", "title": "action_right", "additionalProperties": true, "items": { "type": "object", "required": [ "label", "url" ], "properties": { "label": { "type": "string", "custom_type": "string", "title": "label", "default": "" }, "url": { "type": "string", "custom_type": "string", "title": "url", "default": "" } } } } What is stored: { "type": "array", "items": { "type": "object", "required": [ "label", "url" ], "properties": { "url": { "type": "string", "title": "url", "default": "", "custom_type": "string" }, "label": { "type": "string", "title": "label", "default": "", "custom_type": "string" } } }, "title": "action_right", "additionalProperties": true } Code snippets: class Component(models.Model): name = models.CharField(max_length=200, unique=True) attributes = models.JSONField(default=dict, help_text='Component attributes in JSONSchema') Notes: PostgreSQL has two native JSON based data types: json and jsonb. … -
Ye error aa rha -------- Django.db.utlis.IntegrityError: UNIQUE constraint failed : accounts_user. username
Integrity error in my code in Django . I have created a custom user model -
Submit dynamic dual list box with django
I have a dual dynamic list box in a django form, I'm using jquery..it is an adaptation of this plugin: https://www.jqueryscript.net/form/Dual-List-Box-Multi-Selection.html It works when I try to pass an element from the left box to the other. When I submit the form If I print the form variable, for the second box I receive an error: <tr><th><label for="id_selected_stations">Selected stations:</label></th><td><ul class="errorlist"><li>Scegli un&#x27;opzione valida. 22 non è tra quelle disponibili. </li></ul><select name="selected_stations" required id="id_selected_stations" multiple> Is it wrong the box type? When I submit the form I need to acquire only the data of the right box (users selected options). This is my code: forms.py from django import forms from station.models import Station station_all=Station.objects.all() class VdlForm(forms.Form): vdl_name = forms.CharField(label='nome virtual data logger', max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'})) stations = forms.ModelMultipleChoiceField(queryset=station_all) selected_stations = forms.ModelMultipleChoiceField(queryset=Station.objects.none()) views.py from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from .forms import VdlForm def new_vdl(request): template_name = 'vdl.html' heading_message = 'Add a new vdl' if request.method == 'POST': form = VdlForm(request.POST or None) if form.is_valid(): vdl_name = form.cleaned_data.get("vdl_name") stations = form.cleaned_data.get("stations") selected_stations = form.cleaned_data.get("selected_stations") return HttpResponseRedirect('new_vdl') else: form = VdlForm() return render(request, template_name, {'form': form, 'heading': heading_message, }) vdl.html {% extends 'base.html' %} {% block content %} … -
Persian text in url djngo
I have some links that include Persian texts, such as: http://sample.com/fields/طب%20نظامی and in the view function i want to access to Persian part, so: request.path_info key = re.findall('/fields/(.+)', url)[0] and i get the error: IndexError at /fields/ list index out of range Actually, the problem is with the index zero because it can not see any thing there! It should be noted that it is a Django project on IIS Server and I have successfully tested it with other servers and the local server. I think it has some thing related to IIS. Moreover i have tried to slugify the url without success. I can encode urls successfully, but i think it is not the actual answer to this question. -
FF92.0 on linux introduces caching issues with django 3.2 inline forms
I've noticed a strange behavior with FF 92.0 (Manjaro Linux, but likely all linux I guess) when using inline forms. Setup: Django inline forms A way to add inlines ajax. I'm using the django forms empty_form Some arbitray # of inline saved on the server for that object (for example, say 3) Load the form, add say 2 inlines using javascript. TOTAL_FORMS now shows value=5 Do NOT submit the form, but F5 for a refresh instead After reload, the inlines shown in the table will mirror that of the server However the TOTAL_FORMS from the management_form will show value=5, instead of the 3 it should. page.js: function insert_inlinedets_form () { let form_idx = $('#id_details-TOTAL_FORMS').val(); console.log("inserting new form " + form_idx); let newrow = $('<tr></tr>').appendTo($('#details_form')); newrow.append($('#empty_form_inlinedets').html().replace(/__prefix__/g, form_idx)); $('#id_details-TOTAL_FORMS').val(parseInt(form_idx)+1); console.log("added row to inlinedets formset"); }; function remove_inlinedets_form () { console.log("remove last form "); let form_idx = $('#id_details-TOTAL_FORMS').val(); if (form_idx>0) { $('#details_form > tr').last().remove(); $('#id_details-TOTAL_FORMS').val(parseInt(form_idx)-1); console.log("removed row from inlinedets"); calc_grand_total(); // existing rows haven't changed but the total might } else { $('#id_details-TOTAL_FORMS').val(); // if no form left, this SHOULD be 0. console.log("No more dets left - nothing done."); } }; html - empty form: <div style="display:none"> <table> <thead></thead> <tbody> <tr id="empty_form_inlinedets"> {% … -
Handle login with JWT auth in reactjs
im trying to handle login with JWT auth and axios in my reactjs app; but everytime i send my data into the backend i get "'data' is not defined no-undef" error... this is my handle submit code in Login.js: class Login extends Component{ constructor(props) { super(props); this.state = {username: "", password: ""}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({[event.target.name]: event.target.value}); } handleSubmit(event) { event.preventDefault(); try { const response = axiosInstance.post('/token/obtain/', { username: this.state.username, password: this.state.password }); axiosInstance.defaults.headers['Authorization'] = "Bearer " + response.data.access; localStorage.setItem('access_token', response.data.access); localStorage.setItem('refresh_token', response.data.refresh); return data; } catch (error) { throw error; } } render() { return (... and this in my axiosInstance file : const axiosInstance = axios.create({ baseURL: 'http://127.0.0.1:8000/', timeout: 5000, headers: { 'Authorization': "Bearer " + localStorage.getItem('access_token'), 'Content-Type': 'application/json', 'accept': 'application/json' } }); how can in handle this error "'data' is not defined no-undef" ???? -
How to build a download counter in django
I am building a freebie website where I allow users to download my source files when they click on the download button. I would like to get the total downloads for each item. Since I am still learning. I need to know what approach I should take to build this. Appreciated it in advance as I have learned soo much from this community. So to summarize I need to have a download counter on each item in admin to know how many times this item has been downloaded. -
JWT authentication in reactjs
im trying to handle login with JWT auth and axios in my reactjs app; but everytime i send my data into the backend i get "'data' is not defined no-undef" error... this is my handle submit code in Login.js: constructor(props) { super(props); this.state = {username: "", password: ""}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({[event.target.name]: event.target.value}); } handleSubmit(event) { event.preventDefault(); try { const response = axiosInstance.post('/token/obtain/', { username: this.state.username, password: this.state.password }); axiosInstance.defaults.headers['Authorization'] = "Bearer " + response.data.access; localStorage.setItem('access_token', response.data.access); localStorage.setItem('refresh_token', response.data.refresh); return data; } catch (error) { throw error; } } how should i handle saving data in localStorage? -
Django Queryset and Union
I have 2 models for global tags and user tags. Both Global_Tag and User_Tag have common field encapsulated in an abstract class. When a user is logged in I show user both user tags and global tags in a list sorted by name. I have defined a queryset of global_tag and user_tag and later doing union on them and order by name. Now my question is if django is actually firing 3 query to database or just 1 query. In pycharm debugger I see it printing data as soon as global_tag queryset is defined and later for user_tag queryset as well. Later for union queryset as well. So my question is django firing 3 queries to db or 2 and doing union and order by in memory OR just firing 1 query to db. I need output of only union query. What the best way to have django only fire last query and not 2 queryset used for preparation of final query. -
How can I login to a service's API using OAuth2 in a Django Web App?
I have a small Django app, that I want to allow users to login to an API with, so then I can perform operations on the data from their account. I know Django has built in libraries to deal with social network authentications, but I wanted to know how to login to services to use the API to interact with the persons account. When a user logs in, it won't be used to log them into my web app as they have a separate account for that it's purely to give me access to the API and their data on the service they log in to. Any help or ideas would be greatly appreciated -
How to CRUD data that's created only by the current user in DRF?
Hi Im currently using DjangoRESTFramework to create an API which I would fetch in ReactJS. My app is a project management system where logged in user could create new clients and projects of each client. Now, I would like my DRF to send the data through the API only those which are created by the current/logged in user. What I have so far is as such: serializers.py: class Client Serializer(serializers.ModelSerializer): class Meta: model = Client fields = '__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' views.py class ClientView(viewsets.ModelViewSet): serializer_class = ClientSerializer queryset = Client.objects.all() permission_classes = [IsAuthenticated] authentication_classes = (TokenAuthentication, ) class ProjectView(viewsets.ModelViewSet): serializer_class = ProjectSerializer queryset = Project.objects.all() permission_classes = [IsAuthenticated] authentication_classes = (TokenAuthentication, ) How can I alter this so that I could only access those data created by the logged in / current user? Thank you so much in advance cheers! -
can't add plus button to django model form
I have to add plus button feature , similar to django admin form , for example when i try to add a new instance and the form has foreign key , in sometimes we dont have the object in the foreign key field , so we have to add a new object for the foreign key field , in django admin its so easy , just added a plus button , and it opens a pop up form , i tried this bellow code to achieve that , but it wont open any pop up form , it just replace the current url in the same window , and when fill the form and hit the save button , it just shows a blank page !? this is what i tried my models.py class MainGroup(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) def __str__(self): return self.main_type class Meta: db_table = 'maingroup' class PartGroups(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) main_type = models.ForeignKey(MainGroup,on_delete=models.PROTECT,related_name='maintypes') part_group = models.CharField(max_length=30) def __str__(self): return self.part_group and this is my forms.py from django.contrib.admin import site as admin_site,widgets class MainGroupForm(forms.ModelForm): class Meta: model = MainGroup fields = ['main_type'] error_messages = { 'main_type':{ 'required':_('some message'), 'unique':_('some message'), } } widgets = { 'main_type':forms.TextInput(attrs={'class':'form-control','placeholder':_('placeholder')}) … -
Show django form in a designed page
How are you? I m totally new in Django.I designed a page and I wanted to show a django form(edit or create) in a well designed HTML page. but i do not know how. This is my owner method: class OwnerUpdateView(LoginRequiredMixin, UpdateView): """ queryset to the requesting user. """ def get_queryset(self): print('update get_queryset called') """ Limit a User to only modifying their own data. """ qs = super(OwnerUpdateView, self).get_queryset() return qs.filter(user=self.request.user) class OwnerCreateView(LoginRequiredMixin, CreateView): """ Sub-class of the CreateView to automatically pass the Request to the Form and add the owner to the saved object. """ # Saves the form instance, sets the current object for the view, and redirects to get_success_url(). def form_valid(self, form): print('form_valid called') object = form.save(commit=False) object.user = self.request.user object.save() return super(OwnerCreateView, self).form_valid(form) This is my views.py class TaskUpdateView(OwnerUpdateView): model = Task fields = ["title", "text", "endDate"] class TaskCreateView(OwnerCreateView): model = Task fields = ["title","text","status","endDate"] This is my urls.py: app_name='task' urlpatterns = [ path('', views.TaskListView.as_view(), name='all'), path('task/<int:pk>/', views.TaskDetailView.as_view(), name='detail'), path('task/create', views.TaskCreateView.as_view(success_url=reverse_lazy('task:all')), name='task_create'), path('task/update/<int:pk>', views.TaskUpdateView.as_view(success_url=reverse_lazy('task:all')), name='task_update'), path('task/delete/<int:pk>', views.TaskDeleteView.as_view(success_url=reverse_lazy('task:all')), name='task_delete'), path("accounts/login/", views.login, name='login'), path("accounts/logout/", views.logout, name='logout'), ] And this is the models.py: class Task(models.Model): title=models.CharField(max_length=250) text=models.TextField() user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) status=models.ForeignKey('Status',on_delete=models.SET_NULL,null=True) startDate=models.DateTimeField(auto_now_add=True) endDate=models.DateField(null=True) def __str__(self): return self.title class Status(models.Model): … -
which approach is best to create django react application?
I am coming with a basic question that which approach should I use and why? create Django application and integrate react inside it- so when we run Django it will render react instead of its own templates. create Django project and API's separately and react app separately and let them both talk through API's, on the same server or other. -
How to implement js to django to run 3 functions?
I have found this question which colud work for me, but I don't know js. I want to run 3 function like you see in my views.py, but I'm unable to do that because I use from forms one document that is uploaded to run 3 functions. Can you help me implement this js to my django site. Please provide precise answer. Thanks in advance! This is forms.py class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') This is views.py def save_exls(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() return redirect('html_exls') else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form,} return render(request, 'list.html', context) def pandas_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #pandas stuff done.to_excel(writer, sheet_name=name) output.seek(0) response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) def html_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df … -
Converting dict into different objects
I am building a Blog App and I made a queryset which is showing blog date and likes of every day since blog date, But it is showing in dictionary and i am trying to show both instances differently in table like. Blog Date Likes 20 Sep. 6 Likes 21 Sep. 2 Likes 22 Sep. 4 Likes But it is showing like :- ({20: 6},{21: 2},{22: 4}) views.py from django.db.models.functions import ExtractDay from collections import Counter def page(request): blogpost = get_object_or_404(BlogPost,pk=pk) totals = blogpost.likes_set.filter( blogpost__date=blogpost.date, ).annotate( date=ExtractDay('blogpost__date'), ).values( 'date' ).annotate( n=Count('pk') ).order_by('date').values() results = Counter({d['date']: d['n'] for d in totals}) context = {'results':results} return render(request, 'page.html', context) What have i tried ? :- I have tried lists = [{'id': blog.date, 'name': blog.n} for blog in results ] But it is showing only date like 24 not the likes. than i tried json.dumps(list(results )) than i tried from calendar import monthrange __, ds = monthrange(blogpost.date) finalSecond = [data[i] for i in range(1, ds+1)] But it showed monthrange() missing 1 required positional argument: 'month' I have tried many times but it is still not working. Any help would be much Appreciated. Thank You -
module 'jwt' has no attribute 'ExpiredSignature' GET
module "jwt" has no attribute "ExpiredSignature" I'm getting this error through POSTMAN -
Razorpay window is not loading
I have developed a website using react and django i used razorpay(test-mode) for payment transaction It was working fine but it is not loading payment page when i changed the port 8000 to 7000 it is also not working when i deployed it or used the same code in another project But it is working fine in old project (only when the port is 8000) It is sending success status but the page is not loading: [24/Sep/2021 12:28:51] "POST /razorpay/pay/ HTTP/1.1" 200 243 orders.py @api_view(['POST']) def start_payment(request): # request.data is coming from frontend amount = request.data['amount'] # setup razorpay client this is the client to whome user is paying money that's you client = razorpay.Client(auth=("id", "id")) payment = client.order.create({"amount": int(amount) * 100, "currency": "INR", "payment_capture": "1"}) serializer = "Success" data = { "payment": payment, "order": serializer } return Response(data) -
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use meeting.set() instead. Error with Django m2m fields
i am beginner in Django and i am stucked with the many to many relationship. here i am fetching the google meet data from my google calendar through the calendar API. i have successfully fetched the data but when i save the participants of the meeting.. this error comes. TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use meeting.set() instead. here is the code where problem exists create a partcipant object & save it for email in participants_emails: participant_obj,created = Participant.objects.create( meeting=meeting_obj, email=participants_emails) print(f'participant {participant_obj} was created==== ',created) In the Above code i have access to all emails of participants in the participants_emails and I was to save them in the model. Here below is the models.py from django.db import models from django.contrib.auth.models import User class Meeting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) unique_key = models.CharField(max_length=100, unique=True) subject = models.CharField(max_length=400, null=True, blank=True) start_at = models.DateTimeField( auto_now_add=False, auto_now=False, null=True) end_at = models.DateTimeField( auto_now_add=False, auto_now=False, null=True) feedback_status = models.BooleanField(null=True, default=False) def __str__(self): return self.subject class Participant(models.Model): meeting = models.ManyToManyField(to=Meeting) email = models.EmailField(default=None, blank=True, null=True) def __str__(self): return self.email class Question(models.Model): question_type = [ ('checkbox', 'CheckBox'), ('intvalue', 'Integar Value'), ('text', 'Text'), ('radio', 'Radio Button'), ] question_label = models.TextField(null=True, blank=True) question_type …