Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am working on search and get a index not found error?
I get a regular "index not found" in django, my code is as follow, I am trying to implement search. The string passed to ReceiveStr(String) will look for a file name, in this case "views.py" based on a search for '.' and ' ' (space) def ReceiveStr(String): n = len(String) print(n) d = String.find('.') g =[] t=' ' res1 = [] res2 = [] res = [i for i in range(len(String)) if String.startswith(t, i)] m = len(res) for x in String: for i in range(0,len(res)-1): if res[i] < d: print(res[i]) print (d) res1[i] = res[i] print (res1) break ReceiveStr('Where can I find views.py ') Error at res1[i] = res[i] I have tried everything. The other thing I can't assign a string object to a list[i] ? What is the work around ? -
How url dispatcher include apps urls
I have project urls.py from django.contrib import admin from django.urls import path,include from django.contrib.auth import login urlpatterns = [ path('admin/', admin.site.urls), path('login/',include ('authorization.urls')), ] My included authorization/urls.py file is followed from django.urls import path from . import views urlpatterns = [ path('login',views.login_name), ] While i started to learn url dispatcher logic i much times faced with The current path, login/login/, didn't match any of these. As pointed in documentation Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing. When i am trying to access my login page i see Using the URLconf defined in forecast.urls, Django tried these URL patterns, in this order: admin/ login/ login The current path, login/, didn't match any of these. As i see from traceback and from documentation notes while inside path function included include() function. Path parse given arguments and by examplefrom my project first of all path parse given url pattern login than when path face with include function its give parsed url pattern to included urls. Than when included urls.py parsed its face with another url pattern login its chain them login/login … -
How to display the last login date and time on the users list on the django admin site?
I've built a social authentication system on an django application using the social_django app. It works and I can see users on the admin site as well. Here is the screenshot: What I want is to see the last login date and time in the list too. How can I accomplish that? I am using sqlite3 as a database and 2.1.4 of django. -
function sum(boolean) does not exist
switching from sqlite to postgres and i get this error in django function sum(boolean) does not exist LINE 1: ..."."longitude", "pins_pin"."category_id", COALESCE(SUM("pins_... HINT: No function matches the given name and argument types. You might need to add explicit type casts. viewsets class PinViewSet(viewsets.ModelViewSet): queryset = pin.objects.annotate( numOfUpvotes=Coalesce(Sum('upvoters__upvote'), Value(0)) ) permission_classes = [ permissions.AllowAny # permissions.IsAuthenticated, ] serializer_class = PinSerializer filter_backends = [DjangoFilterBackend] filterset_fields = '__all__' serializer class PinSerializer(serializers.ModelSerializer): username = serializers.CharField( source="owner.username", read_only=True) numOfUpvotes = serializers.IntegerField(read_only=True) upvoters = upVoteStorySerializer(many=True, read_only=True) commentstory = class Meta: model = pin fields = '__all__' class upVoteStorySerializer(DynamicFieldsMixin, serializers.ModelSerializer): class Meta: model = upVoteStory fields = '__all__' model class pin(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() latitude = models.CharField(max_length=50) longitude = models.CharField(max_length=50) category = models.ForeignKey( "categoryType", on_delete=models.CASCADE, null=True, related_name='selected_category') # 1 is community, 2: historical, 3: personal #upVotes = models.PositiveSmallIntegerField(default=0) def __str__(self): """String for representing the Model object.""" return self.title class upVoteStory(models.Model): pinId = models.ForeignKey( "pin", on_delete=models.CASCADE, null=True, related_name='upvoters') upVoter = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) upvote = models.BooleanField(default=False) numOfUpvotes counts the upvotes = true from upvotestory. Initially set as 0 when a pin is added to the database. When using sqlite, it works but when i tried migrating to postgres, i … -
Celery tasks running much slower than expected (compared to a synchronous task)?
I have a function that does a bunch of time-consuming calculations that I run asynchronously using celery+redis (everything is run locally). I, of course, expect the process to take longer given the additional overhead involved, however, there is a nested for-loop functionality in the code that is disastrously slow compared to the same code executed without celery (probably by a factor of 10 or so). Some notes about the workflow. I define the function to be run asynchronously in tasks.py using the @shared_task decorator and call it using: task_id = uuid() task = time_consuming_function.apply_async((arg1, arg2), task_id=task_id) I check the status of the task using the code blow: class TaskView(View): def get(self, request, task_id): task = current_app.AsyncResult(task_id) if task.status == 'SUCCESS': # do stuff Other than that, I use pretty much all the default settings. Is there any way I can speed things up? Maybe reduce the overhead somehow? I am thinking of re-writing the code to do away with the nested for loops but without understanding the problem properly I don't know if that is worthwhile. I use: celery #4.4.0 redis-server #3.2.100 django #2.2.5 -
How to edit an object using model form in django?
This may possibly be a duplicate of this answer. Currently, i'm working on updating an object using the same model form that is used to create the object. my views.py looks like: (as from the answer): def newpost(request): form = PostForm(request.POST) if request.method == "POST": if form.is_valid(): obj = form.save(commit=False) obj.save() return redirect('newpost') return render(request, 'console/newpost.html', {'form':form}) def editpost(request, pk): obj = Post.objects.get(id=pk) form = PostForm(instance=obj) if request.method == "POST": if form.is_valid(): obj = form.save(commit=False) obj.save() return redirect('editpost') return render(request, 'console/editpost.html', {'form':form}) And my html form in editpost looks like: <form method="POST" action="{% url 'newpost' %}"> {% csrf_token %} {{form.as_p}} <button type="submit"> Submit</button> </form> and my urls.py looks like: path('console/post/', c_views.newpost, name='newpost'), path('console/post/<int:pk>/', c_views.editpost, name='editpost'), And the above codes works perfectly fine, but creates a new instance, with the data of the object taken from pk. I added a obj.delete() code like this: def editpost(request, pk): obj = Post.objects.get(id=pk) form = PostForm(instance=obj) obj.delete() if request.method == "POST": if form.is_valid(): obj = form.save(commit=False) obj.save() return redirect('editpost') return render(request, 'console/editpost.html', {'form':form}) This code gives me the exact thing i wanted, but i know it's not a good practice. My question here is, is this a correct way or am i lagging somewhere. … -
Bootstrap studio templated used with Django
I was wondering if it is possible to design at website with Bootstrap studio and then use the template/html code generated with bootstrap studio with django? -
How to create a webpage in django that allows the user to select objects, then display stats relating to said objects
I'm currently trying to make a calculator for a video game. I want the user to be able to select characters from the video game, then the webpage calculates stats about the selected character. So far, all I have is a page that displays a list of names of every character in the database so far. I want a user to be able to select a character from the list, then the program grabs data about that character from the database, and does some calculations on it. I have a solid enough grasp on models.py, and I have pretty much everything I want in there currently working. I'm I have no idea what direction to head in next. My guess is to edit both views and my html files. This is what my views currently looks like. The characters are named units, and think of class like a job class characters can take on if you're familiar with games. from django import forms from .models import Unit from .models import Class # Create your views here. def index(request): unit_list = Unit.objects.order_by("unit_name") context = {'unit_list': unit_list} return render(request, 'calc/index.html', context) def unit(request, unit_id): try: unit = Unit.objects.get(pk=unit_id) except Unit.DoesNotExist: raise Http404("Unit … -
Capture ALL query parameters in GET request
I have a GET request with an endpoint looking like this: http://127.0.0.1:8000/api/tweets/alldata/?0=1&1=2 I know I can reach individual values with the key, but how do I capture ALL values in one variable? I've tried it like this but nothing is captured at all: followers = self.request.query_params.get('') -
How do I store a hashed password on Django and how do i compare with another hashed password?
I have been lookign for a way to store hashes but i still without finding the correct way to do it in models.py models.py class QL_USR_DT(models.Model): ql_usr_img_link=models.ImageField(upload_to="user-profile-picture") ql_usr_name=models.CharField(max_length=60) ql_usr_email=models.EmailField()#By default the max_Length is 254 ql_usr_pass=models.CharField(max_length=254) ql_usr_username=models.CharField(max_length=30) gender = ( ("M","Male"), ("F","Female"), ) ql_usr_gender = models.CharField(max_length=1, choices=gender, default="M", null=False) ql_usr_created=models.DateTimeField(auto_now_add=True) settings.py PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', ] -
Django development server quits itself when accessing admin page
I am following the django docs tutorial to build a polls app i just created the superuser but whenever i try to access the admin page the server quits on its own with no error message that's in both chrome and firefox i'm on windows -
How to host Django webapp on IBM Cloud?
I have developed a django web app, now I want to host in on IBM Cloud. IBM has provided the softlayer ID and IP addresses. Can any one guide me please that how to host the django app on IBM cloud, which has already been created in local machine? -
The current path, auth/, didn't match any of these
I am trying to setup url dispatcher in my project. I have project with follwing structure forecast |___ forecast |_______ __init__.py |_______ settings.py |_______ urls.py |_______ wsgi.py |____authorization |_______ urls.py |_______ models.py |_______ views.py |___ templates |_______ registration |____________ login.html In my forecast/urls.py i put logic of from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('main.urls')), path('auth', include('authorization.urls')), ] The main point for my question is path('auth',include('authorization.urls')) i include urls.py from authorization/ and in this urls.py i want to put all logic for authorization of my project like login page registration page reset_password page i have the following code in authorization/urls.py from django.urls import path from . import views urlpatterns =[ path('registration', views.registration_form), path('login', views.login_name), ] For output my logic on front-end side i created in my project templates directory and inside it registration directory and inside it i put login.html file. in settings.py i enabled created templates directory. Than after running server and opened http://127.0.0.1:8000/auth/registration but django erised page not found exception.Can anyone guide me where is error occured??? -
Django - How do I show a user's group?
models.py How do I show my group in my profile information within the admin? class UserProfile(models.Model): new_group_name = models.ManyToManyField(Group, max_length=20, verbose_name="Grup", blank=True) forms.py How do I show my group when I edit my profile information on the site? class UserProfileForm(forms.ModelForm): new_group_name = forms.ModelChoiceField(queryset=Group.objects.all(), required=True) class Meta: model = User fields = ['new_group_name'] -
Find the last of an annotated record in Django
So I have 3 models: Products, Profile and Waitlist I would like to find all the Waitlist that share more than 1 of the same Product and Profile, and then find the last Waitlist for each group. This works: duplicates = ( Waitlist.objects .values('profile', 'product') .annotate(Count('profile')) .filter(profile__count__gt=1) ) for dup in duplicates: profile_id = dup['profile'] profile = Profile.get_by_id(profile_id) last_product_waitlist = profile.productwaitlist_set.latest('timestamp') I'm trying to see if I can do this in one Django query. -
Heroku hosted Django model: __str__ returned non-string
this is my first time asking a question on stackoverflow. If some info is missing, just ask and I'll add it. So I've tried for hours trying to locate what is causing this error. I'm hosting a Django project on Heroku and have an issue with a certain model when trying to render a modelform. Hosting the project on localhost works like a charm, so I'm guessing the issue is Heroku related. Can someone please point me in the right direction? Thx. https://i.gyazo.com/e5c08391de2d8a59cce1634872407059.png https://i.gyazo.com/0c0b8190d7a0770f9cdef619cd2122b4.png https://i.gyazo.com/d489a971237f3e6e340253be4b167ca3.png https://i.gyazo.com/ebd11e35869958a7af483fadf0772c63.png -
Django manage.py runserver graceful reloading
I am working on a Django project, which integrates a webcam and OpenCV. For the webcam access, I use following code. The webcam can be released if I use Ctrl + C to end a running server, but if the server reloads itself after the code change, the webcam can not be released properly and therefore will be not available. How can I detect hot reloading so I can close the webcam properly? class VideoCamera(object): def init(self): self.video = None def __del__(self): if self.video is not None and self.video.isOpened(): self.video.release() def get_frame(self): try: self.video = cv2.VideoCapture(0) success, image = self.video.read() self.video.release() ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() except (SystemExit, KeyboardInterrupt, Exception) as e: self.video.release() raise e -
Django pre-populate form fields with api data
I'm attempting to populate a form field with data gathered from a third party api from a user's search. I'd like the form data to be saved into the user's database when they click 'add artist'. Currently just trying to pass the name of the artist searched. <form action="{% url 'add_artist' %}" method="post"> {% csrf_token %} <input type="hidden" name="name" value="{{ artist.name }}"> <input type="submit" class="btn" value="Add Artist"> </form> Because I'm not using a CBV I'm having difficulty saving to the database because I don't have the built in form/model relationship. I was wondering if there's a way to use form methods on non CBV form submission within Django. Ideally the view function would look something like this: def add_artist(request, artist_id): form = request.POST if form.is_valid(): new_artist = form.save(commit=False) new_artist.user = request.user new_artist.save() return render(request, 'artists/index.html', { 'artists': new_artist }) Here is the model: class Artist(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('detail', kwargs={'artist_id': self.id}) -
Django- using same html template for the same purpose but for different users- blog web
I'm working on a blog web app and I want to know if there is a way to make 1 html template called blog.html for example that its content is different for each user who made it? Like if I have 200 users who create a blog in my web app and I dont want to make for each of them a special template.. I mean I want every one to have his unique blog but using the same blog.html template and then I can direct to their own unique blog using different end to the path.. and i'll take that end from the model field of the user.. like I can iterate through user.name model field and set it as the end path.. like in the ListView.. and I want each end path will direct to the specific blog using the same html template but dynamicly. Anyway thanks for helping and if there is some one who build web apps with Django and want to work together with me, ill glad to :) Hope you understand my intention. -
How to store field values of a django form into the default database MySQL through django models using django framework?
# forms.py # -------- from django import forms # Create your forms here class _CredentialsForm(forms): Site_Name = forms.CharField(max_length = 10, min_length = 5, strip = True, empty_value = None, `required = True, initial = 'Title of the Site')` _Site_Address = forms.URLField(required = True, disabled = False) __UserID = forms.EmailField(max_length = 20, min_length = 10, required = True, help_text = 'What `is your user name?', initial = 'Enter UserID')` __Password = forms.PasswordInput(attrs = None, render_value = False) # models.py # --------- from django.db import models from PYTHON.forms import _CredentialsForm # Create your models here. class _Credentials(models): id = models.AutoField(primary_key = False, unique = True, auto_created = True) site = models.CharField(_CredentialsForm.Site_Name, unique = True, blank = False, null = False) url = models.URLField(_CredentialsForm.Site_Address, primary_key = True, blank = False, null = `False)` user = models.EmailField(_CredentialsForm.__UserID, unique = True, null = False, blank = False) password = models.fields.forms.PasswordInput(_CredentialsForm.__Password) Issue:- TypeError: module() takes at most 2 arguments (3 given) Interpreter used:- Python 3.7.4 x64 architecture Packages used to create this Project:- pip 19.3.1, django 3.0.1 IDE used: Jetbrains PyCharm CE 2019.3.1 Target File Name: models.py and forms.py Application Name: PYTHON Project Name: DJANGO Virtual Environment Name: frameworks My Error Report is as follows when … -
Saving formset when a compulsory field was not supplied?
I get an error "NOT NULL constraint failed" when I try to save a formset in an update view and the formset has had new forms added. I think the reason is that the database has a required field (journal_entry) that isn't part of the Formset ModelForm. So when the formset is attempted to be saved lineitem_formset.save() I get the error. How can I add this required field value before saving the formset? View.py @login_required def entries_update(request, pk): journal_entry = get_object_or_404(JournalEntry, pk=pk) journal_entry.date = journal_entry.date.strftime('%Y-%m-%d') #Convert date format to be suitable for Datepicker input. journal_entry_form = JournalEntryForm(instance=journal_entry) LineItemFormSet = modelformset_factory(LineItem, fields=('ledger','description','project','cr','dr'), extra=2) line_items = LineItem.objects.filter(journal_entry=journal_entry) lineitem_formset = LineItemFormSet(queryset=line_items) if request.method == 'POST': lineitem_formset = LineItemFormSet(request.POST) journal_entry_form = JournalEntryForm(request.POST, instance=journal_entry) if lineitem_formset.is_valid() and journal_entry_form.is_valid: lineitem_formset.save() <-- ERROR HAPPENS HERE journal_entry_form.save() messages.success(request, "Journal entry successfully updated.") return HttpResponseRedirect(reverse('journal:entries_show_detail', kwargs={'pk': journal_entry.id}) ) Models.py class JournalEntry(models.Model): # User needs to be set back to compulsory !!! user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True) date = models.DateField(null=False, blank=False) TYPE = ( ('BP', 'Bank Payment'), ('YE', 'Year End'), ('JE', 'Journal Entry') ) type = models.CharField( max_length=2, choices=TYPE, blank=True, default='0' ) description = models.CharField(max_length=255, null=True, blank=True) def __str__(self): if self.description: return self.description else: return 'Journal Entry' + str(self.id) … -
Stripe create customer for one time charge
I am working with stripe to build a donation form in python Django. Some donations are one-time and others are recurring. What I want to do is create a customer object with both types of charges, so we can gather mailing address, email address, etc for each donation. The problem I am having, is I can process a one-time payment using the stripe token. But I can't figure out how to do it with a customer. This is what I have tried to so far. The error I receive is No such token: cus_asdfasdfasdf. Any idea what I'm doing wrong? Javascript on donate.html page: var stripe = Stripe('public_key'); var elements = stripe.elements(); var card = elements.create('card'); card.mount('#card-element'); // Create a token or display an error when the form is submitted. var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createPaymentMethod({ type: 'card', card: card, billing_details: { email: 'my_email@gmail.com', }, }).then(function(result) { stripePaymentMethodHandler(result.PaymentMethod) }); stripe.createToken(card).then(function(result) { if (result.error) { // Inform the customer that there was an error. var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { // Send the token to your server. stripeTokenHandler(result.token); } }); }); function stripePaymentMethodHandler(token) { // Insert the token ID into the form so it … -
Django retrieving JSON key/value from JSON string in textfield
I'm currently working on an app for logging changes to model fields. The changes are logged as a JSON string {"field": field.name, "old_value": old_value, "new_value": new_value} in a textfield. How can I get specific keys/values of the JSON string? Current code: views.py def userChangelog(request, pk): user = User.objects.get(pk = pk) changelogs = ChangeLog.objects.filter(user_id = pk) context = { 'user': user, 'changelogs': changelogs, } return render(request, 'users/backend/user/user_changelog.html', context) template {% for changelog in changelogs %} <p>1. {{ changelog.user }}</p> <p>2. {{ changelog.changes }}</p> <p>3. {{ changelog.date_of_change }}</p> {% endfor %} Ideally, I would like to do <p>2. {{ changelog.changes.field }} changed from {{ changelog.changes.old_value }} to {{ changelog.changes.new_value }}</p>, but can't seem to figure out how to translate only part of the query to json.loads, and display it in the tempalte. -
Django fill field value type expression based on multiple crieria
My project has two models boq and dpr model Both the models contain building,level,activity and subactivity as foriegn keys I need to fill up the actual start on boq model with date in dprmodel when all the above mentioned fields are equaled boq model choicestype=(('start','start'),('finish','finish')) class boqmodel(models.Model): code = models.IntegerField() building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) duration = models.IntegerField() linkactivity = models.CharField(max_length=300,null=True,blank=True) linktype = models.CharField(choices=choicestype,max_length=300,null=True,blank=True) linkduration = models.IntegerField(default=0) plannedstart = models.DateField(null=True,blank=True) plannedfinish = models.DateField(null=True,blank=True) actualstart = models.DateField(null=True,blank=True) actualfinish = models.DateField(null=True,blank=True) DPR class dprmodel(models.Model): Date=models.DateField() Contractor=models.CharField(max_length=300) Building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) Level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) Activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) Subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) Status=models.CharField(choices=choicestype,max_length=300) Labor=models.IntegerField() Both the models have Building,Level,Activity,Sub Activity as common fields. My entry in BOQ code=1 building=A-1 Level=L-1 Activity=Activity-1 Subactivity-Subactivity-1 duration=2 linkactivity=null linktype=null linkduration=null planned start=01-01-2019(as linkactivity=null) plannedfinish=03-01-2019(planned start+duration) MY DPR Entry Date :10-1-2019 contractor :A building=A-1 Level=L-1 Activity=Activity-A Subactivity=Subactivity-A Status =Start Labor=2 I need to populate the Actual start date in boqmodel such that if boqmodel.building = dprmodel.building and boqmodel.level = dprmodel.level and boqmodel.activity = dprmodel.activity and boqmodel.subactivity = dprmodel.subactivity and dpr.status=start. If the above condition exists then boq.actualstart=dpr.date *em -
Django - Problem of including user in the group
I'm using django-groups-manager. In my project, the user can create a group when registering. After registering, the user can enter the group he created. I'm getting this error after registering. How can I solve this problem? TypeError at /accounts/register/ 'Group' instance expected, got <-Group: Technology-> views.py from groups_manager.models import Group, GroupType, Member def register_view(request): form = RegisterForm(request.POST or None) if form.is_valid(): user = form.save() new_group_name = form.cleaned_data['new_group_name'] new_group, created = Group.objects.update_or_create(name=new_group_name) user.groups.add(Group.objects.get(name=new_group_name)) user.save() password = form.cleaned_data.get('password1') new_user = authenticate(username=user.username, password=password) login(request, new_user) return redirect('home') return render(request, 'accounts/form.html', {'form': form, 'title': 'Üye Ol'}) problematic place in code: user.groups.add(Group.objects.get(name=new_group_name))