Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: The view Account.views.Login didn't return an HttpResponse object. It returned None instead
Anyone has an idea why my code is not running on the line 'if user is not None:' onwards? traceback 1 2 Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 137, in _get_response "returned None instead." % (callback.module, view_name) ValueError: The view Account.views.Login didn't return an HttpResponse object. It returned None instead. [18/Jan/2019 21:59:25] "POST /login/ HTTP/1.1" 500 56866 views.py class Login(View): form_class = AccountForm template = 'login.html' def get(self, request): form=self.form_class(None) return render(request, self.template, {'form':form}) def post (self, request): if request.method=="POST": form = self.form_class(request.POST) if form.is_valid(): print('1') username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") print('2') user = authenticate(username=username, password=password) if user is not None: print('3') if user.is_active: login(request, user) return redirect('home.html') else: return HttpResponse("Inactive user.") else: return render(request, 'login.html') urls.py urlpatterns = [ ... path('emailverification/passwordchange/', views.PasswordChange, name='passwordchange'), ] template {%extends 'base_form.html'%} {%block content%} <div class=container-fluid> <form method="POST"> {%csrf_token%} <label for="username">username</label> <input type="text" placeholder="username" name="login" required><br> <label for="password">password</label> <input type="password" placeholder="password" name="login" required><br> <button type="submit" class="btn btn-success">Submit</button> </form> <div class="container signin"> <p>Do not have an account? <a href="{% url 'registration'%}">register here</a>.</p> <p>Forgot password?<a href="{%url 'passwordreset'%}">retrieve password</a></p> <p>Improve your password security.<a href="{%url 'passwordchange'%}">change password</a></p> </div> <div> {%endblock content%} -
Troubles making an user update view
I have a custom user model, subclass of AbstractBaseUser. I'm currently having troubles making an update view, so user could change his profile. Changing user through admin interface works fine. This is a form that I use to change user objects in both admin and app`s interface. class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField( label=_("Password"), help_text=_( "Raw passwords are not stored, so there is no way to see this " "user's password, but you can change the password using " "<a href=\"{}\">this form</a>." ), ) class Meta: model = User fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) password = self.fields.get('password') if password: password.help_text = password.help_text.format('../password/') user_permissions = self.fields.get('user_permissions') if user_permissions: user_permissions.queryset = user_permissions.queryset.select_related('content_type') def clean_password(self): return self.initial["password"] I'm using fields = '__all__' to be able to change all the fields through admin interface. But in app's intreface I want user to change only some fields. This in my view: def update_user(request): form = UserChangeForm(request.POST or None, instance=request.user, fields=('email', 'first_name')) if request.method == 'POST': if form.is_valid(): form.save() return redirect('home') return render(request, 'update_user.html', {'form': form}) return render(request, 'update_user.html', {'form': form}) If I pass fields parameter like that UserChangeForm(request.POST or None, request.user, fields=('email', 'first_name')) I get __init__() got an unexpected keyword argument 'fields' … -
Setup firebase mobile auth with django allauth
Is it possible to integrate firebase mobile auth with django-allauth? As all providers that are pre-configured in django-allauth are using OAuth2 protocol but not firebase mobile auth. -
Django admin crashes when adding or editing object
I have a django model: class Foo(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) def __str__(self): return self.user.username With the admin registered as a model admin. When I try to either edit an existing Foo object (which I first added directly to the DB with SQL) or click 'add' to create a new Foo object, the server crashes. Does this have something to do with the fact that the User table contains about 50,000 objects, and the server is running out of memory when it tries to load the Foo admin, because it OneToOne keys out to User? Is there a way around this? -
Validate Date and Time with date in database - Django
I want to validate a form where i am updating TimesheetEntry Model. I want to check if timesheet_clock_out_date and timesheet_clock_out_time is not less than timesheet_clock_in_date and timesheet_clock_in_time. If yes then raise error 'Please enter proper date'. In my url i am send primary key of TimesheetEntry urls.py path('useradmin/timesheet/clock-out/<int:pk>', views.ClockOutAddView.as_view(), name='admin_timesheet_clock_out'), Forms.py class ClockOutForm(forms.ModelForm): class Meta: model = TimesheetEntry fields = [ 'timesheet_clock_out_date', 'timesheet_clock_out_time', ] Models.py class TimesheetEntry(models.Model): timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users') timesheet_clock_in_date = models.DateField() timesheet_clock_in_time = models.TimeField() timesheet_clock_out_date = models.DateField(blank=True, null=True) timesheet_clock_out_time = models.TimeField(blank=True, null=True) Views.py class ClockOutAddView(LoginRequiredMixin, generic.View): template_name = 'admin/clock/clock_form.html' success_url = '/useradmin/timesheet/' def get(self, request, pk, *args, **kwargs): form = ClockOutForm(instance=TimesheetEntry.objects.get(id=pk)) return render(request, self.template_name, {'form': form}) def post(self, request, pk, *args, **kwargs): form = ClockOutForm(request.POST, instance=TimesheetEntry.objects.get(id=pk)) if form.is_valid(): form.save() return HttpResponseRedirect(self.success_url) return render(request, self.template_name, {'form': form}) How can i validate dates and time. -
Django patch save in unittest
In my code I have the class players with an method add_player: class Players: def __init__(self): self.players = Player.objects.all() self.active_player_index = 0 def add_player(self, player): player.save() In my test I tried to do this: class PlayersTest(unittest.TestCase): def setUp(self): self.players = Players() self.players.players = [] def fake_add_player(self, player): self.players.players.append(player) @patch.object(myproject.entities.Players, 'add_player', fake_add_player) def test_add_players(self): self.players.add_player(Player('player', 'blue', True)) self.assertEqual(len(self.players.players), 1) When running this test I get the error" AttributeError: <module 'riskgame.entities.Players' from '/entities/Players.py'> does not have the attribute 'add_player'. What is wrong in this test? Are there better ways to make Django unittests? -
Reverse for 'password_reset_confirm' with keyword arguments (followed by arguemnt list) not found
New to django here. I am trying to implement password reset functionality in my app.I am using the console email backend. I am using django 2.x and python 3.5.x. When I enter the email and hit submit I get following error Kindly tell me how to get rid of this error. NoReverseMatch at /reset/. Reversefor'password_reset_confirm' with keyword arguments '{'uidb64': 'NQ', 'token':'533-3b115e87321ed5f71bbe'}' not found root urls.py from django.contrib import admin import boards from django.urls import include, path, re_path from django.contrib.auth import views as auth_views urlpatterns = [ path('boards/', include('boards.urls')), path('reset/', auth_views.PasswordResetView.as_view( template_name='boards/password_reset.html', email_template_name='boards/password_reset_email.html', subject_template_name='boards/password_reset_subject.txt', ), name='password_reset'), path('reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='boards/password_reset_done.html' ), name='password_reset_done'), re_path('reset/<uidb64>/<token> /',auth_views.PasswordResetConfirmView.as_view( template_name='boards/password_reset_confirm.html'), name='password_reset_confirm'), path('reset/complete/', auth_views.PasswordResetCompleteView.as_view( template_name='boards/password_reset_complete.html' ), name='password_reset_complete'), path('setting/password/', auth_views.PasswordChangeView.as_view(template_name = 'boards/password_change.html'),name='password_change'), path('setting/password/done/', auth_views.PasswordChangeDoneView.as_view(template_name='boards/password_cha nge_done.html'), name='password_change_done'), path('admin/', admin.site.urls), ] It shows error during template rendering at the following line {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} -
making caraousel using bootstrap and django, with the images from database
I am trying to use images from the database, and want to display them in a carousel format. i tried using queryset and looping to get data from the database but its not showing me the desired output its just displaying normal images, and not in carousel format templatecode: {% for i in q %} <!-- <img src=" {{i.image.url}} "> --> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{{i.image.url}}" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="{{i.image.url}}" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="{{i.image.url}}" class="d-block w-100" alt="..."> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% endfor %} Models: class Image(models.Model): title = models.CharField(max_length=120) image = models.ImageField(null = True,blank = True,upload_to = 'uploaded_images/') def __str__(self): return self.title VIEWS: from django.shortcuts import render from .models import Image # Create your views here. def images(request): q = Image.objects.all() return render(request,"1.html",{'q':q}) -
Can't render on base.html?
I have a base.html which essentially provides the navigation for my app. I want to be able to add some stats into the nav bar - so I am trying to render them onto base.html The same script works, if I change base.html to home.html, but I don't want to repeat the same code on every page, to retain the stats when I navigate away from home. Here is my view: def stats(request): incompletetasks = Todo.objects.filter(complete=False, creator=request.user).count() shared = Todo.objects.filter(Q(shareslotone=request.user) | Q(shareslottwo=request.user) | Q(shareslotthree=request.user) | Q(shareslotfour=request.user) | Q(shareslotfive=request.user)).count() closedtasks = Todo.objects.filter(complete=True, creator=request.user).count() context = {'incompletetasks':incompletetasks, 'shared':shared, 'closedtasks':closedtasks} return render(request, 'base.html', context) How can I make this render to base.html, rather than copying the same code for every page? Thanks -
How to tell Visual Studio Code to follow Django itself source code while debugging Django applications?
I have a Django application and I set Visual Studio Code to debug it using the default launch.json configuration. When I start the server (manage.py runserver) and make a request, VSCode stops at the first breakpoint (that is correct), but when I step into a function, VSCode never follows/shows Django source code itself and I would like to see what is happening inside that Django source code. How could I configure VSCode to follow/show Django (and Django REST) source code while debugging Django applications? -
Django noob - view Render/HttpResponse question
Django noob here. Some what comfortable with basics of models and some such. In short I have a Django project working on localhost properly producing a view that I need with (mind the messy code): def entry_list(request): editedbooks = EditedBook.objects.all() treaty = Treaty.objects.all() pilcases = PILCase.objects.all() journalarts = JournalArt.objects.all() return render(request, 'text/test.bib', {'treaty': treaty,'editedbooks': editedbooks,'pilcases': pilcases, 'journalarts': journalarts}, content_type='text/x-bibtex; charset=UTF-8') The view works for present purposes as I need it. In short I need to push a text file of the view to a publicly available repository such as git. I've read a little on HttpResponse and Content-Disposition but not sure how to modify the existing view function so that it functions as it does now but renders a bib (plain text) file. Could you please advise? Second, am I best to render to localhost and manually push the repository or is it possible to render to a remote location. I did try deploying to Heroku but got a bit stuck with migrating the local sqlite DB with quite a bit of content to the remote postgresql DB. In the long run I suspect I will need to learn this properly but in the meantime the localhost environment works as … -
Slicing in django datatables
def get_initial_queryset(self): msisdn=9898989898 EntityID=1 resultset=CONSENTS.objects.filter(iStatus= settings.STATUS_FLAGS['Active'],iEntityID=EntityID,iMSISDN=int(msisdn)).order_by('-iConsentID')[:10] return resultset i want to get 10 records on page load.but i got the following error AssertionError: Cannot filter a query once a slice has been taken. -
django 2 mysql database backend does not accept 0 as a value efor AutoField error
I don't know why: the makemigrations command works fine but when I insert something from the browser, the terminal outputs error message... File "D:\software\WinPython-64bit-3.5.4.0Qt5\python-3.5.4.amd64\lib\site-packages\django\db\backends\mysql\operations.py", line 172, in validate_autopk_value raise ValueError('The database backend does not accept 0 as a ' ValueError: The database backend does not accept 0 as a value for AutoField. in my note/models.py class notecategory(models.Model): categoryname = models.CharField(max_length=150,null=False,default="") isPublic = models.BooleanField() owner = models.ForeignKey(User,on_delete=models.CASCADE,null=True,related_name='%(class)s_requests_created') class note2(models.Model): category = models.ForeignKey(notecategory,on_delete=models.CASCADE,null=True) content = models.CharField(max_length =settings.CONSTANT_DICT['noteContentLen'] ,null=True) book = models.ForeignKey(book,on_delete=models.CASCADE,null=True) chapter = models.ForeignKey(chapter,on_delete=models.CASCADE,null=True) sentence = models.ForeignKey(sentence,on_delete=models.CASCADE,null=True) anchorAt = models.IntegerField(null=True) highlightLen = models.IntegerField(null=True) language = models.ForeignKey(language,on_delete=models.CASCADE, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True,related_name='%(class)s_requests_created') in my note/views.py toSave = note2(book_id=int(bookId),chapter=chapterInstance, sentence_id = int(sentenceId), category_id=int(categoryId), content=userInputNoteContent,anchorAt = int(anchorAt),highlightLen=int(highlightLen), language=languageInstance, owner=userInstance) toSave.save() in note/migrations/001_initial.py class Migration(migrations.Migration): initial = True dependencies = [ ('sentence', '0008_auto_20190118_1608'), ('language', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='note2', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.CharField(max_length=150, null=True)), ('anchorAt', models.IntegerField(null=True)), ('highlightLen', models.IntegerField(null=True)), ('book', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='sentence.book')), ], ), migrations.CreateModel( name='notecategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('categoryname', models.CharField(default='', max_length=150)), ('isPublic', models.BooleanField()), ('owner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notecategory_requests_created', to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='note2', name='category', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='note.notecategory'), ), migrations.AddField( model_name='note2', name='chapter', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='sentence.chapter'), ), migrations.AddField( model_name='note2', name='language', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='language.language'), ), migrations.AddField( model_name='note2', name='owner', … -
Is there a way to integrate Django with Next.js?
I've integrated Reactjs with Django by having a function to access build/index.html. The below codes show how I do that. config/urls.py urlpatterns = [ ... re_path(r'search/', react_views.ReactAppView.as_view()), ] PROJECT_NAME/views.py class ReactAppView(View): def get(self, request): try: with open(os.path.join(str(settings.BASE_DIR), 'frontend', 'build', 'index.html')) as file: return HttpResponse(file.read()) except: return HttpResponse( """ Build your React app. """, status=501, ) ReactAppView function accesses index.html which is created with yarn build on React side. Basically, I used React just for search view, and other than search view, I used jQuery as it was developed with jQuery first. Since I found that I need Next.js to use Server Side Rendering (SSR) with React, I've been trying to migrate React app to Next.js. But, Next.js doesn't have index.html. It just has pages/index.js instead. I've tried very hard to figure out how to integrate Django with Next.js, but I can't find any helpful resource. Can anyone help me about this? -
set constant globally in python Django project
I am making web application where I want to set some constant's globally so I can access it in multiple apps present in my Django project. -
Create MultiSelect field in Django 2
I'm working on a project using Python(3.7) and Django(2) in which I need to create a multi-select field inside one of my form. Here's what I have tried: from models.py: class ExperimentModel(models.Model): user = models.ForeignKey(User, related_name='experiments', on_delete=models.CASCADE) name = models.CharField(max_length=255) start_date = models.DateField() change_date = models.DateField() end_date = models.DateField() assets = models.CharField(max_length=450, choices=choices) goals = models.CharField(max_length=255, blank=True) comments = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now=True) From forms.py: class ExperimentForm(forms.ModelForm): choices = ( ('CO2 SCRUBBER', 'CO2 SCRUBBER'), ('CORN OIL', 'CORN OIL'), ('DRYERS', 'DRYERS'), ('ENVIRONMENTAL', 'ENVIRONMENTAL'), ('UTILITIES', 'UTILITIES'), ('LAB', 'LAB'), ('SIEVES', 'SIEVES'), ('GRAINS & MILLING', 'GRAINS & MILLING'), ('SEPARATION', 'SEPARATION'), ('AIR & GAS', 'AIR & GAS'), ('COOK', 'COOK'), ('EVAPORATION', 'EVAPORATION'), ('WATER', 'WATER'), ('STORAGE', 'STORAGE'), ('BOILER', 'BOILER'), ('FERMENTATION', 'FERMENTATION'), ('DISTILLATION', 'DISTILLATION'), ('BUILDING AND FACILITIES', 'BUILDING AND FACILITIES'), ('CHEMICAL', 'CHEMICAL'), ) assets = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=choices) class Meta: model = ExperimentModel fields = ('user', 'name', 'start_date', 'change_date', 'end_date', 'assets', 'goals', 'comments') From template.html: <form method="POST" action="{% url 'new-experiment' %}"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} … -
Django database file on linux missing
I recently transferred my django project folder from a windows pc to a linux machine, and ever since then my django app is reading its database from an unknown location. I confirmed this by deleting the database in my project folder, and somehow i can still see all my models in the admin. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
How to dynamically search from multiple offset inside an index in elasticsearch?
Say I have a string indexed and I want to take out a substring from it at the time of search query. How will I achieve this? For example - String to be indexed - "The quick brown fox" Searches that I want to make - - "the" - "thequ" - "quick" - "th" How should I do this if I am working with Django and elasticsearch? I have tried to use ngrams and have merged the whole string to create an n gram index for every combination possible. This is on the code side, How to do this with elastic search. -
Getting a count of objects the spans a relation
I'm trying to get a count of objects the spans a relation. Every TestPlan contains n cases. The method plan_case_count() gives me the count. Every TestPlanCase contains n steps. I want to get the total of all steps for all cases associated with the plan. The method plan_case_step_count() is supposed to do that by iterating through the queryset and adding up the counts. But it doesn't work. The error message I get is: 'RelatedManager' object has no attribute 'testplanstep_set' class TestPlan(models.Model): tp_title = models.CharField(max_length=200) tp_version = models.IntegerField() tp_date = models.DateField(default=timezone.now) def plan_case_count(self): """This one works""" return self.testplancase_set.count() def plan_case_step_count(self): """This one doesn't""" pcs_count = 0 for case in self.testplancase_set: pcs_count += case.testplanstep_set.count() return pcs_count class TestPlanCase(models.Model): tpc_plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE) tpc_case = models.ForeignKey(TestCase, on_delete=models.CASCADE) tpc_seq_no = models.IntegerField(default=1) class TestPlanStep(models.Model): tps_case = models.ForeignKey(TestPlanCase, on_delete=models.CASCADE) tps_step = models.ForeignKey(TestSteps, on_delete=models.CASCADE) tps_ok = models.CharField(max_length=4, choices=Choices.yes_no) tps_issue = models.CharField(max_length=200, blank=True) What am I doing wrong? -
django cookies set for multiple domains
i have two domains www.momo.com/dumpling and dumpling.momo.com. I want to set cookies in dumplings.momo.com and want to retrieve in the other one. How can it be achieved? do i need to specify these two in SESSION_COOKIE_DOMAIN? -
After using prefetch_related still facing n+1
I am facing multiple duplicate db call even after I am using prefetch_related. Here is my views: def index(request): product_qs = Product.objects.filter(shop_type='Grocery', featured=True, hide=False) product_list = product_qs.prefetch_related('image', 'size_list').order_by('ranking') products = terminator(request, product_list, 25) // reusable paginator! context = {'categories': categories, 'products': products} return render(request, 'grocery/index.html', context) Here is my models: class ProductImage(models.Model): image = models.ImageField(upload_to='shop/product') color = models.BooleanField(default=False) image_thumbnail_index = ImageSpecField(source='image', processors=[ResizeToFill(308, 412)], format='JPEG', options={'quality': 100}) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Product(models.Model): shop_type = models.CharField(choices=shop_options, max_length=40) name = models.CharField(max_length=200, unique=True) image = models.ManyToManyField(ProductImage) category = TreeForeignKey('Category', null=True, blank=True, on_delete=models.PROTECT) slug = models.SlugField(max_length=200, db_index=True) featured = models.BooleanField(default=False) size = models.BooleanField(default=False) size_list = models.ManyToManyField(SizeList) available = models.BooleanField(default=True) # out of stock ? hide = models.BooleanField(default=False) # archive a product ranking = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and the template: <figure class="product-image-container"> <a href="#" class="product-image"> <img src="{{ product.image.first.image_thumbnail_index.url }}" alt="{{ products.name }}"> </a> <a href="{% url 'grocery_quickview' %}?product={{ product.name }}" class="btn-quickview">{% trans 'Quickview' %}</a> </figure> <div class="product-details"> <h2 class="product-title"> <a href="/grocery/product/{{ product.slug }}"> {% if LANGUAGE_CODE == 'en' %} {{ product.name }} {% else %} {{ product.name_bn }} {% endif %} </a> </h2> <div class="price-box"> <span class="product-price"> {% if LANGUAGE_CODE == 'en' %} ৳ {{ product.price }} {% else … -
White-Space and Characters after white-space are not getting passed in GET request
Suppose I have a django model like this: class myModel(models.Model): names = models.Charfield(max_length=200) Values of objects stored in this model are 'Amanda','John Nash', 'Richard Benson' and 'Joe Williams' Now i have a html form which has a select element.I am fetching values to be put in option element from myModel using ajax function.Form is something like this: <form> <select multiple name='MyNames'> <option value='Amanda'>Amanda</option> <option value='John Nash'>John Nash</option> <option value='Richard Benson'>Richard Benson</option> <option value='Joe Williams'>Joe Williams</option> </select> <input type='submit' name='Save'> </form> If i select 'Amanda','John Nash' and 'Richard Benson' and click on 'Save' following is the GET request i am getting on my server. HTTP GET /testPage/?MyNames=Amanda&MyNames=John&MyNames=Richard&Save=Submit It is clear from the GET request that white-space and characters after white-space are not being picked up if values are fetched from the server. What could be the possible reason and possible solution for this. If i donot fetch values of options from server and rather put the values in option element manually, then this is not happening. Request in that case is like this. HTTP GET /testPage/?MyNames=Amanda&MyNames=John+Nash&MyNames=Richard+Benson&Save=Submit P.S:This is only a sample code.I have not given actual code for the sake of clarity as actual code is quite lengthy.Thanks in advance -
how can i display other user information in django
I'm creating a website that the user can look at other users profile but the problem is when the user enter another user profile it show his personal information this is the urls.py file code urlpatterns = [ path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), ] this is the view.py file code class UserPostListView(ListView): model = Post = Profile template_name = 'website/user_posts.html' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user) def get_username_field(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Profile.objects.filter(user=user) this is the models.py file class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(verbose_name='Ålder', default=15, blank=True) def get_absolute_url(self): return reverse('user_posts', kwargs={'pk': self.pk}) def __str__(self): return f'{self.user.username} Profile' user_posts.html file {{ user.get_full_name }} {{ user.profile.age }} {{ view.kwargs.username }} in the template it's show the username but it didnt' show the name and the age. -
How to search string in children categories of parent?
I want to search 'query' in every children and render results to list.html. I couldn't find the solution so I decided to ask here. Here is my code: def search_query_string(request, path=None, instance=None): query = request.GET.get('query', False) category = request.GET.get('category', False) if category: cat = get_object_or_404(Category, name=category) children = cat.get_descendants(include_self=False) ads = None if query: if category: ads = Ad.objects.filter(Q(name__icontains=query) ) # I want to search query in children here return render_to_response('ads/list.html', locals(), context_instance=RequestContext(request)) ads = Ad.objects.filter(Q(name__icontains=query)) return render_to_response('ads/list.html', locals(), context_instance=RequestContext(request)) As you can see I already have the list of children categories, but still don't know how to search in them. Please help :( -
What is the problem with web crawl for-loops?
I am going to crawl the web with python and selenium. You attempted to crawl a loop with 500 operations to fetch 4 elements from a single line. The three elements will crawl without problems, but one element will stop with a 'no such element' error message during the loop. Below is the code I wrote. What's wrong? The page you want to crawl is a good access to the queryselector from Google Developer Tools. I will try for various days and try various things and ask for help. for i in range(0, review_page_count - 1): if i is not (review_page_count - 2): driver.find_element_by_xpath('//div[@id="south"]/div/nav/div/ul/li/a[contains(text(), "{}")]'.format(i+1)).click() time.sleep(5) if i > 0: driver.find_element_by_xpath( '//div[@row="{}"]/div[@colid="productName"]/a'.format(j)).send_keys(Keys.CONTROL + Keys.HOME) for j in range(0, 500): if j is not 0 and j % 4 is 0: driver.find_element_by_xpath( '//div[@row="{}"]/div[@colid="productNo"]/a'.format(j)).send_keys(Keys.PAGE_DOWN) product_num = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="productNo"]/a'.format(j)).text product_name = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="productName"]/a'.format(j)).text score = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="reviewScore"]'.format(j)).text review_content = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="reviewContent"]/a'.format(j)).get_attribute('text') review_date = driver.find_element_by_xpath('//div[@row="{}"]/div[@colid="createDate"]'.format(j)).text print(j) print(product_num, product_name, score, review_content, review_date) when get review_content row=126 caused ERROR plz help me! thx