Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I Autocomplete using JSON response
I am making a mock trading website and I need to populate an autocomplete dropbox with options, gotten from a JSON response. Here is some background, I am using Django for the backend and Materialize framework for the front end. And I am getting the JSON response from the IEX cloud API. I am using their search functionality. The problem: When a user enters the name of the company they don't always necessarily know the right symbol as well, so if I can make a drop-down box that makes it easier for them that would be awesome. The solution I envision: As the user types the name of the company it starts to give us autocomplete suggestions just like this: What I need: If you could give me a direction, a starting point, a resource I would be very happy. I have been roaming around the interwebs but I seem to find a solution, so if you can point me in the right direction that would be very much appriciated. -
Insert lat and lon in model fields after user fills in address
Is it possible to call an API (eg. Google Maps API) on submit (or even before submit?) and insert lat and lon values in the model's fields so they are saved to the DB my app is connected to? I want to re-use those values later in a view on the front-end outside the admin to plot them an a map. models.py: from django.db import models from django.db.models import Q class Address(models.Model): street = models.CharField(max_length=100) number = models.IntegerField(null=True) postal = models.IntegerField(null=True) city = models.CharField(max_length=100) country = models.CharField(max_length=100) is_primary = models.BooleanField(null=False) geo_lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) geo_lon = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) customer = models.ForeignKey("Customer", on_delete=models.CASCADE, related_name="addresses") class Meta: verbose_name_plural = 'Addresses' constraints = [ models.UniqueConstraint( fields=['customer'], condition=Q(is_primary=True), name='unique_primary_per_customer' ) ] def save(self, *args, **kwargs): if self.is_primary: self.__class__._default_manager.filter(customer=self.customer, is_primary=True).update(is_primary=False) super().save(*args, **kwargs) def __str__(self): return f"{self.street} {self.number}, {self.postal} {self.city}, {self.country}" class Customer(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True) vat = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name}" -
I don't know why instance is not working in form django
views.py @login_required def put(request, id): question = get_object_or_404(Question, id=id) poll_form = PollForm(request.POST, instance=question) print(poll_form) choice_forms = [ChoiceForm(request.POST, prefix=str( choice.id), instance=choice) for choice in question.choice_set.all()] if poll_form.is_valid() and all([cf.is_valid() for cf in choice_forms]): new_poll = poll_form.save(commit=False) new_poll.created_by = request.user new_poll.save() for cf in choice_forms: new_choice = cf.save(commit=False) new_choice.question = new_poll new_choice.save() return redirect('poll:index') context = {'poll_form': poll_form, 'choice_forms': choice_forms} return render(request, 'polls/edit_poll.html', context) html template {{poll_form.as_table}} {% for form in choice_forms %} {{form.as_table}} {% endfor %} models.py class Question(models.Model): title = models.TextField(null=True, blank=True) created_by = models.ForeignKey(User, null=True, blank=True, related_name="created", on_delete=models.CASCADE) forms.py class PollForm(forms.ModelForm): title = forms.CharField(max_length=333, label='Question') class Meta: model = Question fields = ['title'] class ChoiceForm(forms.ModelForm): text = forms.CharField(max_length=255, label='Choice') class Meta: model = Choice exclude = ('question',) when i inspect the element <td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="title" maxlength="333" required="" id="id_title"></td> fields are empty (but instead it should be filled by existing id questions and choice ) but i see errorlist class i dont know please help me but when i fill edit form and try to update things it worked -
For loop in django templates using Integerfield in model object
I have a model like this: class Testimonial(models.Model): rating = models.IntegerField(_("Rating")) I'm looping over all testimonials in Django templates using one for loop, now how do I display the ratings for each testimonial object. My stars class in HTML looks like this: <ul class="list-unstyled"> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star-half-alt"></i></li> </ul> How do I solve this issue? -
Implement f-string like magic to pimp Django's format_html()
I would like to pimp format_html() of Django. It already works quite nicely, but my IDE (PyCharm) thinks the variables are not used and paints them in light-gray color: AFAIK f-strings use some magic rewriting. Is there a way to implement this, so that the IDE knows that the variables get used? Related: Implement f-string like syntax, with Django SafeString support -
Send to the frontend what permissions user have
I'm building an app that have React on the frontend and Django on the backend. My problem is that I need to restrict CRUD operations by user permissions. I need to send some information to the frontend Example when I request something to the backend API to receive something like this: { data: [], permissions: [ read: true, write: true, upload: false, delete: false, ] } Can anyone have some idea how to do that? Or is a better way? -
Make edit funcion without conflict on edit booking django
i make bus reservation system which have filtering to prevent double booking on same bus at same date.. here's the code on forms.py : class BookingEditForm(forms.ModelForm): class Meta: model = Booking fields = '__all__' widgets = { 'idbooking': forms.HiddenInput(attrs={'class': 'form-control', 'id': 'id_booking', 'style':'text-transform: uppercase'}), 'BusId': forms.Select(attrs={'class': 'form-control', 'id': 'bus_id'}), 'start' : forms.DateInput(format=('%Y-%m-%d'), attrs={'type': 'date', 'class': 'form-control', 'required':'true'}), 'end_date' : forms.DateInput(format=('%Y-%m-%d'), attrs={'type': 'date', 'class': 'form-control', 'required':'true'}), } def clean(self): start = self.cleaned_data['start'] end_date = self.cleaned_data['end_date'] BusId = self.cleaned_data['BusId'] res_all = Booking.objects.all().filter(BusId=BusId) for item in res_all: if start <= item.start and item.start <= end_date or start <= item.end_date and item.end_date <= end_date: raise forms.ValidationError("Bus already reserved on same date!") Now, i need help to run this filtering on edit function, because that works on create booking but when i try implement on edit, its not work I think there is something to do on idbooking -
How to extract text from an HTML div tag file with BeautifulSoup?
My python code is as below import requests from bs4 import BeautifulSoup flipurl = "https://www.flipkart.com/search?q=realme+7&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=off&as=off" r = requests.get(flipurl) htmlContent = r.content soup = BeautifulSoup(htmlContent,'html.parser') #i scrap flipkart product price price= soup.find_all("div",class_="_30jeq3 _1_WHN1") print(price.get_text()) #**i got this error how i get text:** "ResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?" % key AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()? As you can see from the above snippet i have tried to extract all the text but all i get an error and None. please solve this -
Iam a beginner in data mining and Iam using Django for a project. How can i perform social media data mining?
iam a beginner in data mining. Iam working on a project that has to collect data from various social media for predicting events like disease outbreak, sports, etc... using machine learning models I am working on django. how can i collect data from various social media sites(mainly social medias like twitter) at the same time? -
Django- Display queries in Django admin with group, max count and timestamp all together
models.py(App: Article) from django.contrib.auth.models import User class Article(models.Model): # code... url_title = models.CharField(max_length=80, unique=True, db_index=True) HATE_SPEECH = 'HS' SPAM = 'SP' FAKE_INFO = 'FI' REPORT_REASON = ( (FAKE_INFO, 'Fake Information'), (HATE_SPEECH, 'Hate Speech'), (SPAM, 'Spam')) class Report(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_id = models.ForeignKey(Article, on_delete=models.PROTECT) user_id = models.ForeignKey(User, on_delete=models.PROTECT) reason = models.CharField(max_length=2, choices=REPORT_REASON) solved_status = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=now) admin.py(App: Article) class ArticleAdmin(admin.ModelAdmin): pass # code... class ReportAdmin(admin.ModelAdmin): list_display = ('id', 'article_id', 'user_id', 'reason', 'solved_status', 'date_created') admin.site.register(Article, ArticleAdmin) admin.site.register(Report, ReportAdmin) In django admin I want to display all these records in such a manner. Unsolved queries should display first (which i am able to achieve using ordering = ['solved_status']) The article which is (i) not solved and (ii) reported highest number of times should come first(Here article a1: because it is reported 3 times. Do NOT consider a2 because in last record, it is considered as solved Highest Number of same reason from same article (Here Hate Speech is coming 2 times, so it should come first and then spam should come) NOTE: Do not consider Spam as 4 times because we have to fulfill condition 2 first. The article which is reported first should display first according to … -
Django's Memcache VS Database Cache. Which is better?
I am trying to develop a site using django framework which might have a mid level traffic and I have hit a wall. I want to include sessions in my pages but to implement session I need to employ caches. There are two different types of cache based sessions as given here. My site will be on only for a certain time in a year during which I expect mid level traffic of say around 200 visitors per day. What kind of cache system should I use for this? I understand that database cache means that every time a user visits my site, the backend will have to search the database which means more processing power, but for my requirements I think this would not matter so much. Any help and advice appreciated -
Django Rest Framework Include ManyToMany attributes in slash with all features
I'm using Django Rest Framework, here's my code: models.py class Course(models.Model): name = models.CharField(max_length=200) class Formation(models.Model): name = models.CharField(max_length=200) courses = models.ManyToManyField(Course, blank=True) serializers.py class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = '__all__' class FormationSerializer(serializers.ModelSerializer): class Meta: model = Formation fields = '__all__' courses = CourseSerializer(many=True) views.py class FormationView(viewsets.ReadOnlyModelViewSet): queryset = Formation.objects.all() serializer_class = FormationSerializer class CourseView(viewsets.ReadOnlyModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer urls.py router = routers.DefaultRouter() router.register('formations', views.FormationView) router.register('courses', views.CourseView) urlpatterns = [ path('api/', include(router.urls)), ] When I use http://localhost:8000/api/formations/{id} it works just fine, and I can benefit from all its features (like PATCH), what I can't do though is http://localhost:8000/api/formations/{id}/courses, so also no localhost:8000/api/formations/{id}/courses/{id} and no features. I feel like the solution is not that far, or complicated So What is the solution for this? -
Item id and order_variants id stored as null while creating an order in django rest framework
I created an order-create API where I am creating order by creating order items objects and billing details objects at the same time. Everything was working fine a few days back, but when I try today to call the order api from the postman, item id and order_variants are stored as null in the database, although I am passing item id and variants id and the objects exist as well. I am sending raw JSON data like this. I have sent the item id and order_varaints id as shown above. But the result I get is null as shown below. My models: class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) #items = models.ManyToManyField(OrderItem,blank=True, null=True,related_name="order_items") #start_date = models.DateTimeField(auto_now_add=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.PositiveIntegerField(blank=True,null=True,) def __str__(self): return f"{self.quantity} items of {self.item} of {self.order.user}" class Meta: verbose_name_plural = "Cart Items" ordering = ('-id',) class BillingDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order = models.OneToOneField(Order, … -
Django how to remove default string " Currently: avatar/default.png " from template
I'm using Django to upload user avatar,my question is ,how to remove the default string " urrently: avatar/default.png Clear " from template Model: class User(AbstractUser): nickname1 = models.CharField(max_length=30, blank=True, null=True, verbose_name='昵称') url = models.URLField('个人网址', blank=True, help_text='提示:网址必须填写以http开头的完整形式') avatar = ProcessedImageField(upload_to='avatar', default='avatar/default.png', verbose_name='头像', processors=[ResizeToFill(100, 100)], # 处理后的图像大小 format='JPEG', # 处理后的图片格式 options={'quality': 95} # 处理后的图片质量 , blank=True ) identifier = models.CharField(max_length=40, unique=True,blank=True, null=True) ... USERNAME_FIELD = 'identifier' def save(self, *args, **kwargs): if len(self.avatar.name.split('/')) == 1: self.avatar.name = self.username + '/' + self.avatar.name super(User, self).save() class Meta: verbose_name = '用户信息' verbose_name_plural = verbose_name ordering = ['-id'] def __str__(self): return self.username url: path('<str:username>/', views.account_profile,name = 'process'), view.py: @login_required def account_profile(request, username): profile_user = get_object_or_404(User, username=username) messages = [] if request.method == 'POST': form = UserDetailForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() messages.append('资料修改成功!') form = UserDetailForm(instance=request.user) return render(request, 'user/user_detail.html', context={'form': form, 'messages': messages, 'profile_user': profile_user,}) form: class UserDetailForm(ModelForm): class Meta: model = User fields = ['avatar',] template: <form class="profile" method="post" enctype="multipart/form-data" action="/<str:username>/"> {% csrf_token %} {{ form|crispy }} <div class="avatar"> <img class="img-rounded" src="{{ request.user.avatar.url }}"> </div> <button class="primaryAction" type="submit">更新资料</button> </form> In the form I only set filed avatar there,but there is always a string " Currently: avatar/default.png Clear " Any friend know how to remove this string? -
Django submitting multiple forms in one page
I have a store with the models: Items, Cart. I created a loop to display the Items in the html file but only if they are in stock (if quantity > 0). However, the user can only add 1 item at a time and the page has to refresh. I'm trying to do it so that the user can enter the quantity for each item and then have one submit button for them all, but I can't seem to figure it out. I tried modelformset and formset, but the examples are confusing. Django's documentation shows it in console mode and it doesn't match when I'm trying to do. Here are the models: #model: Items class Items(models.Model): STORAGE_TYPE = { ('Dry', 'Dry'), ('Frozen','Frozen'), ('Refrigerated','Refrigerated'), ('Other','Other'), } ITEM_TYPE = { ('Produce', 'Produce'), ('Grains', 'Grains'), ('Protein/Dairy', 'Protein/Dairy'), ('Extra Items', 'Extra Items'), } item_name = models.CharField(blank=False, null=False, max_length=255, unique=True) weight = models.FloatField(blank=False, null=False, default=0) quantity = models.IntegerField(blank=False, null=False, default=0) description = models.TextField(max_length=1279, blank=True, null=True) image = models.ImageField(upload_to='fp/', null=True, blank=True) price = models.IntegerField(default=1, blank=False, null=False) storage_type = models.CharField(max_length=255, null=True, choices=STORAGE_TYPE, default="Dry") item_category = models.CharField(max_length=255, null=True, choices=ITEM_TYPE, default="Produce") limit = models.IntegerField(default=999, blank=False) show = models.BooleanField(default=True, blank=False, null=False) date_created = models.DateTimeField(auto_now_add=True, null=True) modified_timestamp = models.DateTimeField(auto_now=True, null=True) #model: … -
Creating a Simple form using django. Stuck between two error, Attribute Error and Key error
This is my form code and I am getting error an Keyerror on line 7 i.e name and also email.I am also getting attribute error on line with ValidationError. from django import forms from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class StudentRegistration(forms.Form): name= forms.CharField() email= forms.EmailField() def clean(self): cleaned_data = super().clean() valname= self.cleaned_data ['name'] valemail=self.cleaned_data [ 'email'] if len(valname) < 8: raise forms.ValidatonError('Name should be more than or equal to 4') if len(valemail) < 10: raise forms.ValidatonError('Abe dhang se daal') -
Django models.OneToOneField(User) not able to access data by user.profile in profile.html
I am trying to display the fields qualification and name that I defined in my Profiles>>models.py file to show on the web page itself. I am trying to call the info with user.profile.name and user.profile.qualification.all but it doesnt find it models.py: from django.db import models from django.contrib.auth.models import User class UserQualifications(models.Model): name = models.CharField(max_length=64, unique=True) normalizedName = models.CharField(max_length=64, unique=True) description = models.CharField(max_length=200) def __str__(self): return self.name class Profiles(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") qualification = models.ManyToManyField(UserQualifications, blank=True) name = models.CharField(max_length=50, blank=True, null=True) isHighSchoolGraduate = models.BooleanField(default=False) isUndergraduate = models.BooleanField(default=False) isCollegeGraduate = models.BooleanField(default=False) isDoctor = models.BooleanField(default=False) isExpert = models.BooleanField(default=False) def __str__(self): return f'{self.user.username} Profiles' profile.html {% extends 'base.html' %} {% block content %} <h1> {{ user.get_full_name }} (@{{ user.username }}) </h1> {% with profile=user.profile %} {% if profiles %} <h2> {{ profile.name|default:"" }} </h2> <br/> <div> Qualifications: {% for qualifacation in profile.qualification.all %} <span> {{ qualifacation.name }}{% if not forloop.last %}, {% endif %} </span> {% endfor %} </div> {% endif %} {% endwith %} {% endblock %} -
Django: ModelFormSet.is_valid() throws django.core.exceptions.ValidationError: ManagementForm data is missing or has been tampered with
I know this error has been asked about before plenty of times on SO, but none of the other threads that I read seem to have the same situation as me, in that I am not trying to render the formset AT ALL. I simply want it for posted data validation purposes alone. Is this not a supported way of using ModelFormSets? The Django docs suggest that I can do this: from django.forms import modelformset_factory from django.shortcuts import render from myapp.models import Author def manage_authors(request): AuthorFormSet = modelformset_factory(Author, fields=('name', 'title')) if request.method == 'POST': formset = AuthorFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() # do something. else: formset = AuthorFormSet() return render(request, 'manage_authors.html', {'formset': formset}) So I can't for the life of me understand why the below code is apparently so illegal: def add_player_to_teams(request): AddPlayerToTeamsFormSet = modelformset_factory( Team, fields=['players']) team_ids = post_data.getlist('team_ids') # Tried adding this, but the stupid thing **still** refuses to work! teams_init_data = { 'teams-TOTAL_FORMS': len(team_ids), 'teams-INITIAL_FORMS': '0' } post_data = post_data.copy() post_data.update(teams_init_data) teams_form_set = AddPlayerToTeamsFormSet(post_data, queryset=Team.objects.filter(unique_id__in=team_ids)) status_dict = { 'status': True, 'errors': None } user = request.user if not teams_form_set.is_valid(): # Here's where it breaks status_dict['status'] = False status_dict['errors'] = teams_form_set.errors else: user.registration_step += 1 user.save() for team … -
Is there way to add paypal to website for buying courses
Is there a way to add paypal to the website to buy the courses in my website .. I have a section for the courses and I want to make it paid, I want the user to choose a specific course and pay by paypal and when the user pays it will be opened for him forever What should I do this .. I mean, what are the right steps to do this ? -
Django rest framework - Nested queries, Passing queryset to response
I am using the Django rest framework and trying to fetch a response for a logistics use case that is based on two models. Model 1 is basically a model that stores the data on which users are assigned which lanes(routes). class BuyerFreightLaneMatrix(models.Model): buyer_email_id = models.ForeignKey(BuyerDetail, on_delete=models.CASCADE, related_name='buyer_Freight_Lane_matrix_buyer_detail_email_id_set') user_email_id = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="user_mapped_lanes") assigned_freight_lanes = models.ManyToManyField(MasterTableLane, related_name='user_mapped_lanes') and model 2 is where we store the data on the freight rates for each lane. class FreightRate(models.Model): lane_name = models.ForeignKey(MasterTableLane, on_delete=models.DO_NOTHING, related_name='Freight_rates_by_lane_name') lane_rate_per_ton = models.DecimalField(max_digits=12, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) created_by_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='freight_rates_created_by_User') updated_at = models.DateTimeField(auto_now=True) updated_by_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='freight_rates_updated_by_User') class Meta: ordering = ['-updated_at'] get_latest_by = ['-updated_at'] def __str__(self): return str(self.lane_name)+str('-Rs ')+str(self.lane_rate_per_ton)+ str('per MT') My serializer is class BuyerMappingWiseFreightRateSerializer(serializers.ModelSerializer): user_mapped_lanes = BuyerFreightLaneMatrixSerializer(many=True,read_only =True) class Meta: model = BuyerFreightLaneMatrix fields = ['user_mapped_lanes'] depth = 2 what I am trying to achieve is, for a given user_email_id in model 1, fetch the assigned_freight_lanes that are mapped to him, and then for each of those lanes, get the latest lane_rate_per_ton based on updated_at timestamp from model 2. I have attempted to do this using Viewsets and generics in the Django rest framework and here are my views class BuyerFreightRateView(generics.ListAPIView): serializer_class = BuyerMappingWiseFreightRateSerializer … -
How long it will take you to complete this project?
My daily job is fixing code and implementing small features, so I never actually start any project from scratch, just wondering, on average how long will took for any developer to build this project? There's few part of the project that will connect to each other, the main goals is to create a simple GUI to extends functionality of existing SPA. Selenium: Login to the SPA Submit form thru the SPA Scrape the data from the SPA Get the status of the submitted form Django Get the data from Selenium Sent command to Selenium Keep the data in database Provide API to view (React) React Render new application for displaying data, submit data I know everyone got their own pace on building something, just I want to get a benchmark, if you are building this project, how many hours you will take? and How many hours you think is average. Please give your opinion. Sorry if the project requirement seem vague. Thanks! -
Django - How add a user to a group with Class Based View
I'm having some issues trying to add a user to specific group with generic CreateView. The trouble is that i want that only one user creates the user's accounts and assign him to a group The form is rendering correctly and it seems select the correct group without issue, but when i check the user doesn't have any group assigned. I tried many ways that i sow but any seems work for me. I dont know if i should do it in (Post method), or form_valid() Im using the CreateView but I'm not so good modifying the class it self, Please any help Im using the default user and this is my create class Views.py class CreateUserView(LoginRequiredMixin, CreateView): model = User form_class = CustomUserForm template_name = 'accounts/create_user.html' queryset = User.objects.all() def get_success_url(self): return reverse_lazy('accounts:list_user') def post(self, request, *args, **kwargs): if self.request.method == 'POST': form = self.form_class(self.request.POST) if form.is_valid(): self.object = form.save(commit=False) # form_class = self.get_form_class() # form = self.get_form(form_class) # position = int(request.POST['groups'])-1 # self.object.groups.add(position) my_group = Group.objects.get(name="Usuario Avanzado") my_group.user_set.add(self.object) self.object.save() return HttpResponseRedirect(self.get_success_url()) return HttpResponseRedirect(self.get_success_url()) Please any help I'll be so grateful -
Django get_or_create how to use it on foriegnkey?
How do i use get_or_create in foriegnkey? i have this code, that if the Student_Users(foriegnkey) doesnt exist the data will inserted and if not the data will update, but in my case even though the Student_Users exist the record inserted. insert_data, created = studentsRecord.objects.get_or_create( Student_Users=student, School_Year = schoolyear Education_Levels = educationlevel ) if not created: insert_data.Student_Users = student insert_data.School_Year = schoolyear insert_data.Education_Levels = educationlevel insert_data.save() -
How to implement password change in Django Rest Framework without repeating code (DRY principle)
I have a Django app that already has a web interface for changing passwords. It uses django.contrib.auth functions and django.views.generic.UpdateView. Here is the code: class PasswordChangeView(LoginRequiredMixin, generic.UpdateView): form_class = PasswordChangeForm template_name = 'form.html' input_value = 'update password' def post(self, request, *args, **kwargs): form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! try: request.user.auth_token.delete() # Important! except (AttributeError, ObjectDoesNotExist): pass messages.success(request, 'Your password was successfully updated!') return redirect('/') else: messages.error(request, 'Please correct the error below.') def get(self, request, **kwargs): form = PasswordChangeForm(request.user) return render(request, self.template_name, {'form': form, 'input_value': self.input_value}) The above code works fine in the web interface. Now I want to implement REST API for changing passwords. I know that I can create APIView/viewset and serializer to do that (like the answers for this question), but it will violate DRY principle. What is the best way to implement the REST API interface for that given that there is already a fully-functional web interface? -
Stripe API error when running Django server
I am trying to run a django server under my localhost and I need help with an error. Everytime I try to run my django server with python manage.py runserver, I get this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/john/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/home/john/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/home/john/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, …