Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form saved twice when using super() in Django cbv
I don't seem to understand super() very well, specially now because I am starting to use it with Django class-based views, Can someone tell me the use of super() here: views.py: class TaskCreate(CreateView): form_class = TaskForm template_name = 'task_new.html' success_url = '/notifyMe' def form_valid(self, form): self.object = form.save() return HttpResponseRedirect(self.get_success_url()) #return super(TaskCreate, self).form_valid(form) I thought I should use the commented line instead of redirect from the docs, but it was saving the form twice, why is that? In case this is useful forms.py: class TaskForm(ModelForm): ... def save(self, commit=True): task = super(TaskForm, self).save(commit=False) day = self.cleaned_data['day'] time = self.cleaned_data['time'] task.when = datetime.combine(day, time) if commit: task.save() return task -
Django next redirect with default view
I'm trying to enter the page while I'm not logged in and app redirect me to login page and getting the next parameter is working (ex. localhost:8000/login/?next=/blog/add/), but when I enter login and password and click login button it redirect me to home page, not that one that is in the next parameter (localhost:8000, not localhost:8000/blog/add/). I'm using default django login view so it is possible to do this without changing anything in login view? -
Updating/overwriting HTML data with jQuery?
I am trying to loop through response data and insert values them into the HTML of my webpage, the HTML might already contain some values so I want to clear them and insert only the new ones so it is up to date. My HTML code looks like this; <div id="ind"> {% for inf in prospect.prospect_industries.all %} {% if inf.is_interested %} <div> <span id="industryInterest" data-fit="id_industry{{inf.id}}"></span> <p>{{inf.get_industry_display}}</p> </div> {% endif %} {% endfor %} </div> My JS looks like this: for (i = 0; i < response.length; i++) { //alert(response[i].industry + ":" + response[i].is_interested); if (response[i].is_interested) { $("#industryInterest").html(response[i].industry); $("#industryInterest").attr("data-fit", response[i].industry); } } I tried to do something like this "$('#ind').html('');" however, that removes the HTML within the #ind div so then I am not able to insert the new values. What is the correct approach to update the HTML in this case? Do I first clear the HTML of the #ind div and then recreate it from jQuery? Thanks for the help! -
Creating a mailing list with Django & Sendgrid?
I would like to add a newsletter signup to my website which has a backend set up with Django. How should I go about handling email information when submitted to my site? Should I create a new model just for emails? Is there a way I can take emails inputted into my site and have them saved dynamically to my sendgrid account? I would like to use sendgrid for all of my email campaigns and I would prefer having my data sent there instantly rather than saving in a model table and then manually inputting the contacts into my account. -
Django form with imagefield loses the file when editing an instance
working with django, my code for modifying a model with an image field, forces me to choose a new file; I want it to default/populate field with the existing image. Any thoughts welcome. models.py class Imageotd(models.Model): def __str__(self): return self.title title = models.CharField(max_length=70) image = models.FileField(upload_to='imageotd/%Y/%m/%d') ************************* forms.py class ImageotdForm(forms.ModelForm): class Meta: model = Imageotd fields = [ 'title','image', 'date','uname', 'desc','likes','dislikes','likdisdif'] widgets = { 'likes': forms.HiddenInput, 'dislikes': forms.HiddenInput, 'uname':forms.HiddenInput, 'likdisdif':forms.HiddenInput, } labels = { 'desc':('Photo Description'), } views.py @csrf_protect @login_required(redirect_field_name='/accounts/login/') def modify(request,pic_id): if request.POST: form = ImageotdForm(request.POST,request.FILES) if form.is_valid(): ******************************************** else: image=get_object_or_404(Imageotd,pk=pic_id) form=ImageotdForm(instance=image) form.image=image.image args = {} args['form'] = form args['id'] = pic_id args['user']=request.user return render(request,'imageotd/modify.html',args)#templates folder when i render this to a template the following appears click here to see html renderred id like to see it default to "currently" but the form wants to me to choose a new file, or re-pick orinigal -
Why does my Django view display the correct model fields without the data?
I'm trying to create a user profile for my users with Django. Overall it seems to have mostly worked and I am able to see everything correct in the admin page. On my actual HTML page I correctly see the model fields that I need, however they aren't populated with any data, and the data I put in won't actually save even though it says it does. views.py class DemoUserEditView(UpdateView): form_class = DemoUserEditForm template_name = "user/profile.html" view_name = 'account_profile' success_url = '/member/' def get_object(self): return self.request.user def form_valid(self, form): form.save() messages.add_message(self.request, messages.INFO, 'User profile updated') return super(DemoUserEditView, self).form_valid(form) account_profile = login_required(DemoUserEditView.as_view()) models.py. class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) avatar_url = models.CharField(max_length=256, blank=True, null=True) skills = models.CharField(max_length=256, blank=True, null=True) avatarpic = models.ImageField(_('avatar photo'), blank=True, null=True, upload_to=user_directory_path, validators=[validate_img_extension]) Bio = models.TextField(_('Bio'), max_length=200, blank=True, null=True, unique=False) EDUCATION_CHOICES = ( ('0', "Didn't complete High School"), ('1', 'High School or GED'), ('2', 'Associate Degree'), ('3', 'Batchlors Degree'), ('4', 'Masters Degree'), ('5', 'PhD Degree'), ('6', 'Professional Degree'), ) Education = models.CharField(_('Education'), max_length=100, blank=True, null=False, choices=EDUCATION_CHOICES, unique=False, help_text="Level of Education") urls.py url(r'^accounts/', include('allauth.urls')), url(r'^accounts/profile/$', 'base.views.account_profile', name='account_profile'), I'm trying to use Generic Views, and I thought UpdateView would be the appropriate tag for this. I have read … -
Django use external file for htnl
I'm new in Django (I know some python) and I want to use an external file for the html, because otherwise my views.py file is very unorganised, and my Autism can't handle that (I'm not joking, I have autism). Does anyone know how to do this? -
Flask's routes and POST method to Django
I have this fragment of code in Flask @app.route('/search', methods = ['POST']) def search(): if request.method == 'POST': results_arr = [] img_path = request.form.get('img') How to make this in Django or where I can read about it? -
Django form - changing queryset dynamically
I have a simply model: class ModelA(models.Model): type = models.ForeignKey(Type) amount = models.DecimalField() product = models.ForeignKey(Product) And I have create view and model form for it class ModelAForm(ModelForm): class Meta: model = ModelA fields = [ 'type', 'amount', 'product' ] And how can I do this: When user in form choose 'type' - TYPE1 then in 'product' he has all products. And it works now. But when user choose TYPE2 I want to show him in only few product (e.g. older then one year) -
How to get multiple checkbox values from modal form and populate in html?
I have a set of multiple checkboxes on a modal form and when the user selects submit on the form the checkbox values are saved to the table. This part is working great and if I refresh the webpage I can see the correct values. However, I would like to not have to refresh the webpage to see the values populated, for this I need to insert the values from the same JS function that is saving them to the table, but I'm not sure how to read the values from the modal form :(. Here is my JS code which calls the python function to save the values to the database: $(document).ready(function() { $(".containerProfile").on("click", "#saveCheckboxes", function() { var url = "/profile/updateCheckboxes"; csrftoken(); $.ajax({ type: "POST", url: url, data: $('#checkboxForm').serialize(), }).done(function(response){ $("#modalCheckboxTest").modal("hide"); //I want to modify the HTML here to display the checkbox values on the webpage }); }) }) If I take a look at the serialized data that is sent to the database it looks something like "chk1=4.00&chk2=0.00". How can I loop through and read the value of each checkbox before it serialized? Thanks for the help! -
Local React Frontend, Django REST Framework Backend (Trouble accessing CSRF cookie under CORS)
I'm creating a web app with a React frontend and Django REST Framework backend. Due to some circumstances, I have to develop the React frontend locally while the backend server is at a remote location. The backend server requires me to use the CSRF token for every POST after login, and I'm supposed to be able to retrieve the csrftoken from the cookie that the backend sends. I've verified that the cookie does get sent over the network and is included in the response headers in the form of: Set-Cookie:csrftoken=******; Domain=localhost; expires=Sat, 09-Dec-2017 18:50:56 GMT; Max-Age=31449600; Path=/ Unfortunately, since the the domain of the frontend (localhost) and the domain of the backend (remote.com) are different, the browser ignores this set-cookie header, and I am unable to access it. If I enable CORS_ALLOW_CREDENTIALS (and specify localhost as an accepted domain), and use withCredentials from the frontend, then the cookie does get set but under the remote.com cookie store, in which case I am still unable to access it due to same origin policy for cookie access. How do I get access to this csrftoken cookie? Or should I have Django send the csrftoken as part of the body somewhere? If so, … -
How to filter in django query in database based on last inserted record for specific foreign key?
I am working with django in my company project and I am trying to filter out information. Let me explain the table first, ticket state table where ticket id and state id is FK: ---------------------------------------------- | ID | date_created | ticket_id | state_id | ---------------------------------------------- | 1 | 01/01/2017 | 1 | 1 | ---------------------------------------------- | 2 | 01/01/2017 | 1 | 2 | ---------------------------------------------- | 3 | 01/01/2017 | 2 | 1 | ---------------------------------------------- | 4 | 01/01/2017 | 3 | 1 | ---------------------------------------------- | 5 | 01/01/2017 | 3 | 2 | ---------------------------------------------- | 6 | 01/01/2017 | 1 | 3 | ---------------------------------------------- and ticket table: ----------------------- | ID | date_created | ----------------------- | 1 | 01/01/2017 | ----------------------- | 2 | 01/01/2017 | ----------------------- | 3 | 01/01/2017 | ----------------------- | 4 | 01/01/2017 | ----------------------- So I am trying to filter out tickets using django query where ticket has state id 2. I don't want all the tickets with all state id but I want ticket with last updated sate id which is 2. If there is not state id 2 in record, I don't want ticket. Here is my query which is giving all the … -
Images not being served with Django/Nginx
I can't seem to figure out why my images aren't being served when my other static files are. I'm following along with this tutorial, and everything is working except for the images aren't being served. All other static files (css, js, etc.) are served however. I've tried looking at the Django Docs, several SO posts, and the Nginx Docs. After reading the above, I have tried moving the static files to different places and including STATICFILES_DIR. It looks like the static files are getting found and served by Nginx (except for the img dir). I can see the css and js files when I check Sources with Chrome Developer Tools, just not the img dir and files. I really appreciate any help you all may have! Settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # TEMPLATE_DIRS = ( # os.path.join(SETTINGS_PATH, 'templates'), # ) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '**' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['138.197.19.209'] # Application definition INSTALLED_APPS … -
Django Bootstrap custom grid
I've a template like below grid system. @import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'); .row div{ padding: 20px; border: 1px solid #ccc; } <div> <div class="container"> <div class="row"> <div class="col-sm-8">Data 1</div> <div class="col-sm-4">Data 2</div> </div> <div class="row"> <div class="col-sm-4">Data 3</div> <div class="col-sm-8">Data 4</div> </div> <div class="row"> <div class="col-sm-4">Data 5</div> <div class="col-sm-4">Data 6</div> <div class="col-sm-4">Data 7</div> </div> </div> </div> How to implement this on django where fetching data from database. Suggestion please. -
'range' object has no attribute 'method'
'range' object has no attribute 'method' Why do I get this error in Python 3.5.1 while trying to execute this code in Django? x = list(range(1, 5)) I have executed the same code in cmd (same version of Python) and it works... -
Django OrderBy using ManyToMany table
I have the models: class Category(models.Model): description = models.CharField(unique=True, max_length=200) class Car(models.Model): categorys = models.ManyToManyField(Category) Constantly new cars are added. I'd like to get the last 20 categories that had a car of her type added. I got to set up a filter, but when I got to order by I could not get it anymore. Since I can not close any logic I will not put what I have tried here. -
Django-Crontab with deployment environment
I'm developing a module with the crontab. Actually, the framework I'm using is django so I did install 'django-crontab' I did test as the instruction did and make it with localhost environment. When I deployed("sudo service apache2 restart") it on AWS after doing a command 'python manage.py crontab add', it didn't work. I thiknk it's working on only localhost environment, isn't it? How can I solve this problem? -
Optimizing dictionary creation and manipulation of Django query sets
In a Django app of mine, users create groups for others to visit, and can appoint certain users as captains. Given a set of user_ids, I need to create a dictionary containing corresponding user objects and whether they're a group captain or not (saved in another table in the DB). What's the most efficient way to perform this? Here's what I'm currently doing: visitors = User.objects.filter(id__in=all_relevant_ids) captains = GroupCaptain.objects.filter(which_user_id__in=all_relevant_ids, which_group=group) # print captains groupies = {} for visitor in visitors: try: captain = captains.get(which_user_id=visitor.id) groupies[visitor] = captain except: groupies[visitor] = None Ideally, I don't want to ensconce this in the relatively heavy try except block, given how rare captains are among visitors. Any tips? -
Flask get_flashed_messages() in Django
How can I replace the Flask's {% for message in get_flashed_messages() %} in Django? -
AssertionError : UserSerializser()
class DjangoRestFrameworkUsageApiTestCase(TestCase): def setUp(self): self.factory = APIRequestFactory() self.user = UserFactory(first_name='Biola', last_name='Oyeniyi', email='b_oye@example.com', id=1) self.booking = BookingFactory(user=self.user, order='ABCDEFGHIJKL') WalletTransactionFactory(booking=self.booking, wallet=self.user.wallet, total=20000) self.patch = patch('tuteria_application_test.users.views.UserSerializer') self.mock = self.patch.start() self.mock.return_value = UserSerializer(UserFactory.get_user(self.user)) def test_api_view_get_request_returns_valid_response(self): response = self.client.get(self.reverse('users:the_api', self.user.pk)) self.mock.assert_called_once_with(self.user) data = json.loads(response.content.decode('utf-8')) self.assertEqual(data, { 'first_name': 'First name', 'last_name': 'Last Name', 'booking_order': ['ABCDEFGHIJKL'], 'transaction_total': '1000' }) serializer.py UserSerializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' views.py class UserApiView(APIView): authentication_classes = authentication.TokenAuthentication ###Am assuming you're authenticating via a token def get(self, request): """ Get user based on username. Am getting only the username since that's the only field used above. :param request: :param format: :return: """ details = User.objects.all() serializer = UserSerializer(details) return Response(serializer.data ) def post(self, request, format=None): """ Create a new user instance :param request: :param format: :return: """ serializer = UserSerializer(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) I have the above test class am carrying out. When i run the above test case, i get the result below which fails all the time. AssertionError : Expected call:UserSerializer(<User: user-3>) ActualCall : UserSerializer(<QuerySet [<User: user-3>]>) Now, how do i convert it to a UserSerializer object instead of the QuerySet object? -
Django1.8 and Python2.7: Uncaught TypeError: Cannot read property '0' of undefined(…)
I'm using Django v1.8 in Python v2.7. I'm trying to read data from an API I created. The response of the API is in json format. The error I get is: ERROR -> Uncaught TypeError: Cannot read property '0' of undefined(…) for this line of code (var key in response['alzDysphagia'][0] ) in an ajax call. Calling the API from browser itself, is working properly and I get the json response. Can you help me please? Below you can find my views.py code and the ajax call in my template. views.py for myfields in l_v: if counter ==0: print "counter=0" counter = counter +1 elif counter !=0: if counter == count-1: myfields = '{'+myfields dictionary = json.loads(myfields) dict= {"DysphagiaComment" : dictionary["DysphagiaComment"] , "Imipaxireusta" : dictionary["Imipaxireusta"] , "Liquids":dictionary["Liquids"] , "Solid":dictionary["Solid"] } print "dict " print dict print "dictionary" # print dictionary else: counter += 1 # print form_collection print "diction" # print dictionary # temp = json.dumps(dict) temp = json.dumps({"alzDyshpagia":[dict]}) print temp return HttpResponse(temp) template html file **$.ajax({ url: "/Dysphagia", type: "post", data: { csrfmiddlewaretoken: '{{ csrf_token }}', patientId: aValue, Select_dys: true }, dataType:'json', async: true, success: function (response){ console.log("response :"); console.log(response.type); console.log("rw"); for (var key in response['alzDysphagia'][0] ){ {# console.log(response['alzDysphagia'][0][key]);#} $('[name="' … -
Error while importing custom module within Django app
I have a django app within a django project in this structure : my_project/ my_app/ migrations/ static/ template/ admin.py apps.py views.py . . . my_module.py My requirement is to import my_module within views.py. I have so far tried the following ways: 1.import my_module 2.from my_app import my_module 3.from . import my_module I start the server using ./manage.py runserver In all the above 3 cases I get the following error: manage.py: error: unrecognized arguments: runserver Any suggestions on how to import correctly would be of great help. -
How do I access a CSRF Token on my server?
I have my API running on port 8000 and then I have my client running on port 8080. I called out a registration method account/register/ (django's built in registration) and it gave me a 403. So I made sure my CORS was set up, ensured I allowed requests from localhost:8080, and then I accessed the csrftoken token (which I logged to ensure I was getting it) and then I passed it by header method. I still had some issues so I had to set up CORS_ALLOW_HEADERS to allow the csrf token and whatever else was required. After all that, I was back to my 403 error. Not sure if I gave enough detail here but was hoping someone might have an idea based on what I gave, I can also provide more detail as needed. I am a little new at this and not sure how it ALL works probably. -
Django: Redirect from a form
I'm writing a sports league app. I get a drop down list of all my teams. And I can display the wins/losses data on a separate view. But I can't get the StandingsView (with the form) to correct redirect to the TeamView (display information). I've tried both POST and GET. I've run into a bunch of issues I don't understand. First, the url from the form is directed to /teamview/?team_name=6 I don't understand why that is, even if my view specifies otherwise. Second, the view doesn't redirect unless I do so in the form action. I think that's a product of the GET function, but I'm not sure. I'm hesitant to use POST because I'm not changing the DB I've looked into RedirectView, but worry (as always) I'm overcomplicating this. Thank you much, Views.py class StandingsView(FormView): form_class = SelectTeam template_name = 'teamsports/standings.html' model = Teams success_url = '/teamview/' def form_valid(self, form): team = form.cleaned_data['team'] return redirect('teamview', team = team) def form_invalid(self,form): HttpResponse ("This didn't work") def TeamView(request, team): try: team = Teams.objects.filter(team=team).values() except Teams.DoesNotExist: raise Http404("Team does not exist") return render(request, 'teamview.html', {'team':team}) urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^standings/$', views.StandingsView.as_view(), name="standings"), url(r'teamview/(?P<team>[0-9]+)/$', views.TeamView, name="teamview") forms.py class … -
Getting an error running Djago command in Ipython
When running commands in IPhon3.4 console with this command, from django import template t = template.Template('My name is {{ name }}.') I get, ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_M ODULE or call settings.configure() before accessing settings. Any ideas?