Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF:Updating particular fields in database
I have created an api to create users. But now I require to update their information based on their id.(I want to create a new api for this task). So I wrote the following: views.py class ProfileView(APIView): permission_classes = (AllowAny,) serializer_class = ProfileSerializer def update(self, request, *args, **kwargs): instance = self.get_object() instance.branch = request.data.get("branch") instance.year = request.data.get("year") instance.save() serializer = self.get_serializer(instance) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Account In my model I have fields as username, email, branch, year, full name. If at time of registration user fills few fields and after some time he gets to fill other fields(branch, year). How do I make it possible -
Why aren't the images of an inlineformset_factory being saved?
I have two models: Profile and CredentialImage. I am trying to allow each Profile to upload, optionally, up to 5 maximum images(CredentialImage). I've decided to use an inlineformset_factory for the images because on the UpdateView users will be given the option of updating their general Profile information as well as their 5 select images. The code goes without error, but the images do not save to the database. Here are the two models: class Profile(models.Model): ... def get_absolute_url(self): return reverse("profile:profile_detail", kwargs={"username": self.user}) class CredentialImage(models.Model): profile = models.ForeignKey(Profile, default=None) image = models.ImageField(upload_to=credential_photo_upload_loc) The modelforms + initialization of the inlineformset_factory: from django.forms.models import inlineformset_factory class ProfileUpdateForm(ModelForm): class Meta: model = Profile fields = [ "introduction", "biography", ] class CredentialImageForm(ModelForm): image = ImageField() class Meta: model = CredentialImage fields = ['image', ] CredentialImageFormSet = inlineformset_factory(Profile, CredentialImage, fields=('image', ), extra=4) A class-based UpdateView for updating a Profile: class ProfileUpdateView(LoginRequiredMixin, UpdateView): form_class = ProfileUpdateForm template_name = 'profile/profile_edit.html' def get_context_data(self, **kwargs): context = super(ProfileUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['credential_image'] = CredentialImageFormSet(self.request.POST) else: context['credential_image'] = CredentialImageFormSet() return context def get_object(self, *args, **kwargs): user_profile = self.kwargs.get('username') obj = get_object_or_404(Profile, user__username=user_profile) return obj def form_valid(self, form): data = self.get_context_data() formset = data['credential_image'] if formset.is_valid(): self.object = form.save() formset.instance = self.object … -
Does django-fsm call save() method after state changed?
I am using django_fsm to manage state in my model. My model looks like: from django.db import models, from django_fsm import FSMField, transition class MyModel(models.Model): STATES = ( ('pending', _('Pending')), ('active', _('Active')) ) state = FSMField(choices=STATES, default='pending', protected=True) @transition(field=state, source='pending', target='active') def change_state(self): pass Should I add self.save() to change_state? Will it be called? -
Django query using datetime flter
In my (Post) model I have published = models.DateField(null=True) My urls include the year/month/day eg /post/category-1/2017/11/06/some-post/ which I am capturing through kwargs in my urls.py In my view my query is model = Post.objects.get(slug=kwargs['slug'],published__year=kwargs['year'], published__month=kwargs['month'],published__day=kwargs['day']) However, this is not working. The only date element which works is for year. I've read some posts here which talk about unsetting USE_TZ in settings.py which is obviously not a solution. I have tried using a DateTime field as well, but that makes no difference. Any help much appreciated. -
How to filter csv file?
I have csv file which have random data But I want to filter data from file. I want filter row which have data with starts $ and end with # 2017-09-07 03:11:03,5,hello 2017-09-07 03:11:16,6,yellow 2017-09-07 03:11:22,28,some other stuff with spaces 2017-09-08 20:24:36,157, 2017-10-28 04:39:25,54,$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@# 2017-10-28 04:39:48,108,$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@#$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@# 2017-10-28 04:40:26,54,$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@# 2017-10-28 04:40:29,54,$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@# -
django.db.utils.IntegrityError: column submittedby_id is not unique
I am having a hard time getting around this error. This is how my model looks like right now. class trendingideas(models.Model): submit = models.CharField(max_length=10) iname = models.CharField(max_length=15, unique = True) idea = models.TextField(unique = True) support = models.PositiveSmallIntegerField() submittedon = models.DateTimeField() readbyadmin = models.BooleanField() feasibilitycheck = models.BooleanField() def __str_(self): return str(self.iname) class trendingidea_admin(admin.ModelAdmin): list_display = ('submit','iname','idea','support','submittedon','readbyadmin','feasibilitycheck') submit defined above was before defined as: submittedby = models.ForeignKey(User) I made some changes and now no matter what i do, I keep getting the error: return self.cursor.execute(sql, params) File "/usr/lib64/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: column submittedby_id is not unique. if I do inspectdb i see the poblematic column(stale entry) class HomeTrendingidea(models.Model): id = models.IntegerField(primary_key=True) # AutoField? iname = models.CharField(unique=True, max_length=15) idea = models.TextField(unique=True) submittedon = models.DateField() support = models.PositiveSmallIntegerField() readbyadmin = models.BooleanField() feasibilitycheck = models.BooleanField() submittedby = models.ForeignKey(AuthUser, models.DO_NOTHING) assignedto = models.ForeignKey(AuthUser, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'home_trendingidea' How can i get it working back? thank you in advance. -
Django Post.objects.all() does not show object
Hi I'm learning Django based on the Django girls tutorial. I'm stuck in chapter 9 when I am trying to display all of my Post objects in the python shell. from blog.models import Post Post.objects.all() It should display [<Post: Title>, <Post: Title2>] but instead it displays [<Post: Post object>, <Post: Post object>] I was trying to find the solution for this but all say may be the cause of the error is in the models.py. I checked my blog\models.py and it seems to be good. It contains __str__ method with the indentation. I'm using Python 3.6.0 and Dajngo 1.11.6. Please help me My blog/models.py is the following from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
Django UpdateView doesn't get the values of the object and get blank instead
So I'm creating a django website and I have an Edit Button. The edit shows a pop up with a few forms to edit. The problem is that the forms to edit are blank! instead of having the previous data. e.g- ServerName="Yossi" When I click edit instead of having "Yossi" in the form I have nothing. What do I need to add to the index.html or the Class of PostEdit so I will have the previous data in the forms and not blank forms? models.py - from django.db import models # Create your models here. class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) #date = models.DateTimeField(auto_now=True) views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = … -
Display specific table field (blog text) using Django
Hopefully a simple one, but I can't find what's wrong myself. I have a simple blog app, and I can display the posts titles, in a weird format, but can't pull through the posts body/text - all I get is a blank row. /models.py from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title /views.py from django.shortcuts import render from .models import Post def index(request): posting = Post.objects.filter() context = { 'posting':posting, } return render(request, 'posts/index.html', context) /templates/posts/index.html <li>{{posting}}</li> <li>{{posting.body}}</li> <li>test text</li> The output to the page is similar to (apologies not exact due to html formatting, but note blank middle line) : QuerySet [Post: First Post>, Post: Second Post>, Post: Third Post>]> test text Thank you. -
Testing django with jquery on the page for empty select fields?
I have been using the following test for the django admin and it has been working really well. Recently I added django-smart-selects to the project and the chained selects do not have options and are empty. def test_invalid_duration_entry(self): '''Ensure error if duration is greater than 24''' response = self.app.get( reverse('admin:entries_entry_add'), user=self.super_user ) form = response.form form['date'] = '2017-11-03' form['project'] = self.project.id form['user'] = self.user.id form['task'] = self.task.id form['duration'] = '24.25' response = form.submit() self.assertEqual( response.status_code, 200 ) self.assertFormError( response, 'adminform', 'duration', 'Ensure this value is less than or equal to 24.' ) When I inspect the value is empty: ipdb> form.get('user') <Select name="user" id="id_user"> ipdb> form.get('user').options [] ipdb> form['user'] = self.user.id *** ValueError: Option 14 not found (from ) jquery is adding the options when the project field is changed. How can I test this now. -
CORE issue for specific type of url .AJAX [duplicate]
This question already has an answer here: Why does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not? 31 answers While making ajax call I am getting below error . Get request to "http://*****/api/profile/2" is not working , however a GET request to "http://*****/api/profile/" is working fine(The diff is adding 2 at last" . My web api server is configured to handle CORE . Failed to load http://*****/api/profile/2: Redirect from 'http://*****/api/profile/2' to 'http://*****/api/profile/2' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. Code: $.ajax({ type: 'GET', url: 'http://*****/api/profile/2', success: function(profiles){ $.each(profiles,function(i,profile){ Alert("Success"); }); }, -
Django: DateTimeField taking UTC format only, not others
The time that is being inserted in database is default UTC, not the timezone based time..I do not understand why is this happening, even though I am particularly specifying, in the query, the time that I want to be inserted. In my Model I have class leave(models.Model): date_created = models.DateTimeField(auto_now_add=True) In my settings I have TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True In my views i am setting timezone based on employee country if employees.objects.get(emp_id=request.user.username).emp_loc == 'IND': tzone=pytz.timezone('Asia/Calcutta') elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MLA': tzone=pytz.timezone('Asia/Manila') elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MPLS': tzone=pytz.timezone('CST6CDT') And then I am creating leave and updating timezone based on country new_leave = leave.objects.create(employee=employees.objects.get(emp_id = userid.emp_id), start_date=sdt, end_date=edt, ltype=ltyp, message=des,date_created=datetime.now(tzone)) new_leave.save() Thanks in Advance. -
Django - runserver error- value error: source code string cannot contain null bytes
I just started learning django and I was trying out some tutorials online. Please help. This is just a small web app the accepts user input and displays it on the message board. I am using windows and django 1.11.7. I use sublime text editor for python. I am not sure whAt the error means. If somebody could help, it would be of great help. This is the error that I got: ` Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03BF8F18> Traceback (most recent call last): File "C:\dev\message_board\mb\lib\site-packages\django\utils\autoreload.py", l ine 228, in wrapper fn(*args, **kwargs) File "C:\dev\message_board\mb\lib\site-packages\django\core\management\command s\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\dev\message_board\mb\lib\site-packages\django\core\management\base.py ", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\dev\message_board\mb\lib\site-packages\django\core\management\base.py ", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\registry.py ", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\urls.py", l ine 16, in check_url_config return check_resolver(resolver) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\urls.py", l ine 26, in check_resolver return check_method() File "C:\dev\message_board\mb\lib\site-packages\django\urls\resolvers.py", lin e 254, in check for pattern in self.url_patterns: File "C:\dev\message_board\mb\lib\site-packages\django\utils\functional.py", l ine 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\dev\message_board\mb\lib\site-packages\django\urls\resolvers.py", lin e 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\dev\message_board\mb\lib\site-packages\django\utils\functional.py", l ine 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\dev\message_board\mb\lib\site-packages\django\urls\resolvers.py", lin … -
Unknown column 'userprofile.id' in 'field list
I ma getting this error while calling save method. the error is Unknown column 'userprofile.id' in 'field list class Userprofile(models.Model): user = models.OneToOneField(User) profile_id = models.IntegerField(db_column='profile_id') # Field namemade lowercase. f_name = models.CharField(max_length=45, blank=True, null=True) middle_name = models.CharField(max_length=45, blank=True, null=True) l_name = models.CharField(max_length=45, blank=True, null=True) dob = models.DateField(db_column='DOB', blank=True, null=True) # Field namemade lowercase. contact_number = models.IntegerField(blank=True, null=True) email = models.CharField(max_length=45, blank=True, null=True) joining_date = models.DateField(db_column='Joining_date', blank=True, null=True) # Field name made lowercase. temp_address = models.CharField(max_length=45, blank=True, null=True) permanant_add = models.CharField(db_column='Permanant_add', max_length=45, blank=True, null=True) # Field name made lowercase. user_image = models.CharField(max_length=45, blank=True, null=True) # group_idgroup = models.ForeignKey(AuthGroup, models.DO_NOTHING, db_column='group_idgroup') gender_idgender = models.ForeignKey(Gender, models.DO_NOTHING, db_column='gender_idgender') class Meta: managed = False db_table = 'userprofile' unique_together = (('profile_id', 'gender_idgender'),) This is my model -
How to display django project in web browser as website?
Someone gave me django project to make it with front-end, I can't open it to see the design. what can i do? -
What is the need for forms in Django?
I am a noob in Python/Django and want to know what additional benefits Django forms offer compared to html forms? From what I have seen in a few tutorials, Django forms are mostly used for front-end validation only, which can also be done by html/JavaScript, so why should I use Django forms? -
I am trying fill a datatable from a json serialized by django
I am trying fill a datatable from a json serialized by django and for to do it I try as follows HTML <table id="table"> <thead> <tr> <th>Name</th> <th>Options</th> </tr> </thead> </table> JavaScript $(document).ready(function() { list(); }); var list = function() { var my_table = $('#table').DataTable({ "ajax": { "processing": true, "url": "/get_json/", "dataSrc": "" }, "columnDefs": [{ "targets": -1, "data": null, "defaultContent": "<button>View</button>" }] }); $('#table tbody').on('click', 'button', function(){ var data = my_table.row($(this).parents('tr')).data(); }); } I receive a json that was serialize in a view in Django with the next format: [ { "model": "application.model", "pk": 1, "fields": { "name": "Name", "path_icon": "/path/icon.png" } } ] Simply serialize a queryset: serializers.serialize('json',Model.objects.all()) I want show in the column Name the name received in the json and in column Options a button that redirect to another page using the pk of the model, but when I try to do this receive the next message error: DataTables warning: table id=tabla-model - Requested unknown parameter '0' for row 0, column 0. help in documentation -
How to make a set of forms in a div into a JSON dictionary and then pass it to a django view
So I have a jQuery function which will append a form to a div of forms. The code for this here: <div id = 'questions'> </div> <button id="newquestion">Add question</button> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript"> var question_form = '<div><form><label>Question: </label><input type="text"/><br><label>Numeric: </label><input type="checkbox"/></form></div>' //Builds the questions $(document).ready(function() { //Selector where you will add your questions var placeholder = $("#questions"); // Selector for the button var add_button = $("#newquestion"); $(placeholder).append(question_form); // Adding new fields when the user click the button $(add_button).click(function(e){ e.preventDefault(); $(placeholder).append(question_form); }); }); </script> The user is able to add as many or as little questions as they wish. I am passing this information to a django view. I want to do this by turning it into a json dictionary, and then pass it to my view. How do I do this? -
HTML/Django/Jinja/Python : How to post a fixed value back
This is a HTML template that displays all of the proposals in a database (passed through views.py as a list in the dictionary parameter). I then use a jinja for-loop to go through all the proposals in the database and display their attributes. How can I Post-request the {{ proposal.id }} back to my python code when the "Learn more" button is clicked? I need this to allow me to display the corresponding values in my other html template. Sorry if this is a basic question, i'm a high school student and extremely new to django! Thanks alot in advance! {% block body %} {% for proposal in proposals %} <div class="jumbotron"> <h2> Proposal : {{ proposal.title }} </h2> <h4> Status : {{ proposal.status }} </h4> <h4> Out of --- Votes: </h4> <div class="progress"> <div class="progress-bar progress-bar-success" style="width: {{ proposal.votes_for }}%"> <span class="sr-only">35% Complete (success)</span> {{ proposal.votes_for }}% For </div> <div class="progress-bar progress-bar-danger" style="width: {{ proposal.votes_against }}%"> <span class="sr-only">10% Complete (danger)</span> {{ proposal.votes_against }}% Against </div> </div> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p> </div> -
How to pass context variable from template to views.py in python django?
Suppose I have this my views.py def exampleclass1(request): #do other things examplevar = request.POST.getlist('id[]') data_dicts = [{'id': id} for id in examplevar] for data in data_dicts: master_data=ExampleModel.objects.get(id=data.get('id')) master_data.save() context={ 'sampleid':examplevar, } #do other things return render(request, 'examplepage.html',context) In my examplepage.html, I have this line: <a href="{% url 'exampleclass2' sampleid %}"></a> My exampleclass2 looks like this in my views.py : def exampleclass2(request,sampleid): examplevar = sampleid data_dicts = [{'id': id} for id in examplevar] for data in data_dicts: master_data=ExampleModel.objects.get(id=data.get('id')) master_data.save() What I am trying to do is pass 'sampleid' context variable from 'exampleclass1' to 'examplepage' template and then pass that 'sampleid' from 'examplepage' template to 'exampleclass2'. What will be my urlpattern in my urls.py ? How can I achieve this ? -
Get email address of user from twitter in django using allauth
I need to get email address from twitter. And i have added policy URL and Terms of Service URL in Twitter App settings. And enable checkbox of request for email address. And in django settings.py file: SOCIALACCOUNT_QUERY_EMAIL = True Anything else missing? and Sorry, But i am also not getting how to get in views.py. Thanks. -
whether it is necessary to add status_code and msg in response of rest framework APIs? If is , how to do with that?
How to add status_code and msg to a rest framework api? If we use the rest framework to write APIs, the Response will be like bellow JSON data: But, you know, in the Java APIs, we usually returns API data like bellow format: { "status_code":200, "msg":"success", "data":[the_data] } the_data is the data list like upper snapshot data. So, whether it is necessary to add status_code and msg in response of rest framework APIs? If is , how to do with that? -
Translate Chinese characters to english letter(pinyin) as slug
In Django, I want to convert Chinese characters to pinyin as slug. for instance: 旺顺阁鱼头泡饼 to 'wang-shun-ge-yu-tou-pao-bing'. Is there a shortcut to accomplish it using python? -
is there any way to display contents of .docx files as selected by a visitor on my django webapp?
i am creating a web application using django and i want to display the contents of docx files , edit those files and save it back to the local device. Is django capable of doing this. -
I wanna restrict length of letters in JSON value
I wrote in views.py like def index(request): id = request.POST.get('id', None) print(id) When i wrote index method's url in POSTMAN,and I wrote id in Key & 1000 in Value,so these data can be sent.I wanna restrict length of value's letters 1000 in max.I think widget is good for my ideal system but I did not use html so I cannot understand whether widget is good to my system or not. How should I restrict length of value's letters?