Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to modify the xml file using python?
Actually i have get the xml string and parse the string to get the attributes from it. Now i want my xml file to change, viewing the attributes. Like i want to change the color of the stroke. Is there anyway? How I will change and then again save the file. import requests from xml.dom import minidom response = requests.get('http://localhost:8080/geoserver/rest/styles/pakistan.sld', auth=('admin', 'geoserver')) fo=open("/home/adeel/Desktop/untitled1/yes.xml", "wb") fo.write(response.text) fo.close() xmldoc = minidom.parse('yes.xml') itemlist = xmldoc.getElementsByTagName('CssParameter') print "Len : ", len(itemlist) #print "Attribute Name : ", \ itemlist[0].attributes['name'].value print "Text : ", itemlist[0].firstChild.nodeValue for s in itemlist : print "Attribute Name : ", s.attributes['name'].value print "Text : ", s.firstChild.nodeValue -
Chain lookup through queryset
I have two models: City, and its alias CityAlias. The CityAlias model contains all the names in the City, plus the aliases. What I want is that whenever City is searched by name, the CityAlias model should be queried. This is what I've come up with: class CityQuerySet(models.QuerySet): """ If City is searched by name, search it in CityAlias """ def _search_name_in_alias(self, args, kwargs): for q in args: if not isinstance(q, models.Q): continue for i, child in enumerate(q.children): # q.children is a list of tuples of queries: # [('name__iexact', 'calcutta'), ('state__icontains', 'bengal')] if child[0].startswith('name'): q.children[i] = ('aliases__%s' % child[0], child[1]) for filter_name in kwargs: if filter_name.startswith('name'): kwargs['aliases__%s' % filter_name] = kwargs.pop(filter_name) def _filter_or_exclude(self, negate, *args, **kwargs): # handles 'get', 'filter' and 'exclude' methods self._search_name_in_alias(args=args, kwargs=kwargs) return super(CityQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) class City(models.Model): name = models.CharField(max_length=255, db_index=True) state = models.ForeignKey(State, related_name='cities') objects = CityQuerySet.as_manager() class CityAlias(models.Model): name = models.CharField(max_length=255, db_index=True) city = models.ForeignKey(City, related_name='aliases') Example: Kolkata will have an entry in City model, and it will have two entries in the CityAlias model: Kolkata and Calcutta. The above QuerySet allows to use lookups on the name field. So the following two queries will return the same entry: City.objects.get(name='Kolkata') # <City: Kolkata> … -
Which token based authentication i used with python3.5 and django 1.10.2
I am facing problem in django auth2-provider token authentication package. which is no support django 1.10.2 latest version. Which package is support python / django latest version for authentications. Thanks, Suresh -
Django ORM, accessing the attributes of relationships
I have on my projects two apps: account_app and image_app which have the models below. I am wondering if it is possible to directly access the number of likes of one profile, which has a OneToOne relation with User(django bultin) that in turn has a ManyToMany relation with Images user_like. account_app/models.py class Profile(models.Model): # quando usar a relacao nao colocar o nome User de vez, tem que usar dessa forma # essa relacao nos permite linkar o perfil com o usuario user = models.OneToOneField(settings.AUTH_USER_MODEL) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) image_app/models.py class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked',blank=True) -
i want to redirect from login_view to student_view
i am new to django i want when any user login to my site that will automatically redirected to student_view. i have tried by return student_view(request) but this did not solve my problem Please suggest me how to do this here is views.py file # Create your views here. def index(request): return render(request,'app/index.html') def about_us(request): return render(request,'app/about_us.html') def services(request): return render(request,'app/services.html') def portfolio(request): return render(request,'app/portfolio.html') def blog_item(request): return render(request,'app/blog_item.html') def pricing(request): return render(request,'app/pricing.html') def blog(request): return render(request,'app/blog.html') def error(request): return render(request,'app/404.html') def shortcodes(request): return render(request,'app/shortcodes.html') def contact_us(request): return render(request,'app/contact_us.html') def message(request): return HttpResponse('Sucessufully Logged In') def sucessfull(request): return HttpResponse('Sucessufully Registered') def contactview(request): if request.method=="POST": f=contact(request.POST) if f.is_valid(): f.save() return HttpResponse('Thanks For Contacting With Us') else: f=contact() return render(request,'app/contact_us.html',{'f':f}) def student_view(request): if request.method=='POST': form = Student_Form(request.POST) if form.is_valid(): form.save() return HttpResponse('Sucessfully Done We will Get You Soon') else: form = Student_Form() return render(request, 'student_detail.html', {'form':form}) def login_view(request): print(request.user.is_authenticated()) w="Welcome" title = "Login" form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) login(request, user) return render(request,'app/index1.html',{'username':username,'w':w}) return render(request, "app/login.html", {"form":form, "title":title}) def register_view(request): print(request.user.is_authenticated()) form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username=user.username, password=password) login(request, … -
How can I add twitter-like link preview card to the post using Django?
On websites like twitter/fb/g+, when a user posts a link, a preview card is automatically generated with page title, preview image, and a description. What is the right way to fetch those things and add them to the post using Django? -
How to upload image in Django Rest Framework?
I want to upload user profile photo in my API. But I get this error: { "detail": "FileUpload parse error - none of upload handlers can handle the stream" } views.py class AvatarFileUpload(RetrieveUpdateAPIView): parser_classes = (FileUploadParser, MultiPartParser) lookup_field = 'user_id' serializer_class = AvatarUploadSerializer queryset = UserProfile.objects.only('avatar') def post(self, request, user_id, format=None): file_obj = request.data['avatar'] user = UserProfile.objects.filter(user=request.user) user.file = file_obj user.save() return Response(status=204) def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) serializers.py class AvatarUploadSerializer(ModelSerializer): class Meta: model = UserProfile fields = [ "avatar" ] models.py class UserProfile(TimeStampModel): avatar = models.ImageField( upload_to="avatars", max_length=255, blank=True, default=DEFAULT_USER_AVATAR, verbose_name=_("Avatar") ) Where is wrong in this codes? How to fix it? Thank you. -
Django - distinct rows/objects distinguished by date/day from datetime field
I'v searched quite a while now and know about several answers on sof but none of the solutions does work at my end even if my problem is pretty simple: What I need (using postgres + django 1.10): I have many rows with many duplicate dates (=days) within a datetime field. I want a queryset containing one row/object each date/day. col1 | colX | created (type: datetime) ---------------------------------------------- info | info | 2016-09-03 08:25:52.142617+00:00 <- get it (time does not matter) info | info | 2016-09-03 16:26:52.142617+00:00 info | info | 2016-09-03 11:25:52.142617+00:00 info | info | 2016-09-14 16:26:52.142617+00:00 <- get it (time does not matter) info | info | 2016-09-14 11:25:52.142617+00:00 info | info | 2016-09-25 23:25:52.142617+00:00 <- get it (time does not matter) info | info | 2016-09-25 16:26:52.142617+00:00 info | info | 2016-09-25 11:25:52.142617+00:00 info | info | 2016-09-25 14:27:52.142617+00:00 info | info | 2016-09-25 16:26:52.142617+00:00 info | info | 2016-09-25 11:25:52.142617+00:00 etc. Whats the best (performance + pythionic/django) way to do this. My model/table is going to have many rows (>million). -
How to use transactions with Django REST framework?
I wish to use Django REST framework to create a number of model objects "together" -- i.e. in a single transaction. The objective is that each of the objects will only be visible at the (successful) end of the transaction. How can I do that? -
Django - Is it possible to get selected radio button choice value in forms __init__
I have a field type which is a radio button with value 1 and 2 Normal user Premium user(Have extra field than normal user and mandatory) When normal user is selected then that extra field will disappear, and when premium user is selected then the extra field will appear and it should be become mandatory I have custom allauth form, here is the snippet class CustomSignupForm(forms.ModelForm): first_name = forms.CharField(label=_('Name'),required=True) type = forms.ChoiceField(choices=Profile.TYPE_CHOICES,widget=forms.RadioSelect, required=False) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(CustomSignupForm, self).__init__(*args, **kwargs) self.fields['categories'] = forms.ModelMultipleChoiceField(queryset=CourseCategory.objects.filter(status=True), widget=forms.CheckboxSelectMultiple,required=True) for name, field in self.fields.iteritems(): attr = {'class': 'input-text input-box'} raise Exception(field.choices[1:]) if field.label: attr['placeholder'] = field.label field.widget.attrs.update(attr) class Meta: model = Profile fields = ('user_type','categories') If you see categories is required True it should become false when then use select Normal user any good way to do it? -
Unable to use JSON.parse in my django template
I have a variable data1 in my Django view which has been returned in the following way - def dashboard(request): a = [1,2,3,42] df1 = pd.read_excel("file.xlsx") str1= df1.to_json(orient = 'records') data1 = json.loads(str1) return render(request, 'dashboard/new 1.html',{'data1' : data1}) The variable is then called in the template using javascript <script type = text/javascript> var ob2 = JSON.parse( {{ a }} ); document.write(ob2); </script> This does not show anything on the HTML webpage created. Is there anything wrong in the code? -
CSRF verification failed. Request aborted in django
I am Registering a user in the User_Auth Database, but I got CSRF_tokens error... The data submitted in the in built User database of Django register.html <div class="container-fluid" style="background-color: #f2f2f2;"> <div class="row"> <div class="col-lg-3"></div> <div class="col-lg-6 " align="center" style="margin:50px;"> <h3>Register for an Account</h3> <form class="form-horizontal" action="" method="post"> {{ csrf_input }} {{form.errors}} <table> <tr><td>Username:<input type="text" value=""name="username"></td></tr><br> <tr><td>Password: <input type="password" value=""name="password"></td></tr> <!--Superuser:<select>--> <!--<option value="0" name="is_superuser">0</option>--> <!--<option value="1" name="is_superuser">1</option>--> <!--</select>--> </table> <div align="center"><button type="submit" class="btn btn-success pull-right">Submit</button></div> </form> </div> <div class="col-lg-3"></div> </div> </div> views.py def register(request): if request.method=='POST': form = UserForm(request.POST) if form.is_valid(): user = User.objects.create( username = form.cleaned_data['username'], password = form.cleaned_data['password'], ) user.save() return HttpResponseRedirect('signin') else: form=UserForm() return render(request, 'customer/register.html', {'form': form}) here is my forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] -
Django ORM giving inconsistent response between 'get' and 'filter'
I used Django-softdelete to undelete an entry from table 'QRMapping'(using Django admin panel). Now when I perform 'QRMapping.objects.get(qrid=myqr)' where 'qrid' is a foreign key field of 'QRMapping' and 'myqr' is a variable having entry of another table 'MyQR' the result is correct i.e. << QRMapping: QRMapping object>> But when I perform 'QRMapping.objects.filter(qrid=myqr)' it returns empty list [] If 'get' is returning an entry then why is 'filter' not able to find it. -
backend_cleanup takes no arguments
We are using: celery==3.1.20 django-celery==3.1.17 Whenever the backend_cleanup is invoked (once a day?) we get the following exception: Got exception in task [60b4b41b-b9a6-461a-bfbd-9d40869c06dc] Traceback (most recent call last): File "/var/lacoon_web/mt1/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/var/lacoon_web/mt1/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) TypeError: backend_cleanup() takes no arguments (1 given) This error started when we upgraded django-celery from 3.1.10 to 3.1.17 and django from 1.6.11 to 1.8.14 Appriciate your help Dekel -
Saving Django 400 bad requests for analyzing purposes
I have a Django-based API. Sometimes my customers inform me that some of the their requests return 400 (bad request) even that they're not supposed to. I thought about a good way to handle and debug that exact problem, by saving the failed-requests, with all of the headers (such as the Access Token) and a timestamp, so when I'll see problematic pattern I'll be able to debug it and find the reason. My question regarding to my method is - how can I "trigger" a function that will collect the request with all of its headers everytime that I'm returning a response with 400 status? -
How to use django to upload a .txt file,and then read it,and stored it into Mysql database?
An ip.txt file like this: 192.168.49.132 test 1 192.168.49.133 test 2 Now I can upload it into my django project, def handle_upload(f): path = os.path.join(BASE_DIR, 'upload/').replace('\\', '/') filename=path+f.name with open(filename,'wb+') as desction: for chunk in f.chunks(): desction.write(chunk) read the lists and insert into mysql def mysql_insert(iplist,userlist,passwordlist): try: conn=MySQLdb.connect(host='localhost',user='root',passwd='123',port=3306) cur =conn.cursor() cur.execture('create database if not exists python') conn.select_db('mmot') for ip,user,password in zip(iplist,userlist,passwordlist): cur.execture('insert into ip_iptable(ip,user,password) values(%s,%s,%s) ' %(ip,user,password)) cur.close() conn.close() except MySQLdb.Error,e: print ('Some error!') read the file and stored them into three lists def open_file(filename): iplist=[] userlist=[] passwordlist=[] try: if str(filename).endswith('.txt'): with open(filename) as f: data =f.readlines() for line in data: line=line.replace('\n','').split() iplist.append(line[0]) userlist.append(line[1]) passwordlist.append(line[2]) mysql_insert(iplist,userlist,passwordlist) #insert into databases else: print ("The file is not txt file") except Exception,ex: print ("Sorry,some error!") views.py def upload(req): if req.method=="POST": upfile=UploadFile(req.POST,req.FILES) if upfile.is_valid(): handle_upload(upfile.cleaned_data['file']) #read it and write open_file(upfile.cleaned_data['file']) #open it return HttpResponse('successful!') else: upfile=UploadFile() return render_to_response('ip/ipadd.html',locals()) #But it doesn't work,how can I correct it? Sorry for that if there are some English mistakes. -
Missing Count attribute In Modelviewset
I am using Modelviewsets and everything is working fine expect there is no count parameter in response. I suspect may be pagination not working but I have defined pagination in DRF settings 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', views : class VenueViewSet(viewsets.ModelViewSet): """ Manage CRUD on venues here """ queryset = Venue.objects.all() serializer_class = serializers.VenueSerializer filter_backends = (ModifiedFilterBackend,) paginate_by = settings.VENUES_PAGINATION Response : [ { "id": 54, "name": "v1", "description": "dfqw", "address": { "city": { "name": "abc", "state": { "name": "PO", "code": "MK" }, "country": { "name": "XYZ", "code": "XY" }, "id": 22 }, "address_line_1": "abcd", "address_line_2": "qwert", "zip_code": 123654, "place_id": null }, "is_deleted": false, "parent": null } ] -
Deploying django app using openshift runserver show permission
I cloned my project and use command: python3 manage.py runserver Public_DOMAIN_NAME:8080 but show "Error: You don't have permission to access that port." My env: OPENSHIFT_PYTHON_PORT=8080 OPENSHIFT_PYTHON_VERSION=3.3 Django 1.8.4 ps. if I use command: python3 manage.py runserver LOCAL_IP:8000 it will work fine, but not what I want. wsgi.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoWebProject.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I have no idea and I am new in django. Do I need to modify any settings?? -
Request object's unique identifier - django or django rest framework
Whenever a request goes to a server, I hope there would be a unique identifier for each request object. But I couldn't find how to access that unique identifier. I have already read the docs for django HTTPRequest and django-rest-framework Request Object. Please Explain, How to get request object's unique identifier, If there is one ? -
How to make a realted field mandatory in Django?
Suppose I have the following many-to-one relationship in Django: from django.db import models class Person(models.Model): # ... class Address(models.Model): # ... person = models.ForeignKey(Person, on_delete=models.CASCADE) This allows a person to have multiple addresses. I wish to make it mandatory for a person to have at least one address, so it will be impossible to save a person with no addresses in the DB. How can I achieve this goal? Is it possible to make a related field mandatory (as can be done for "normal" fields using blank=False)? -
Common practice to query from django models
I am planning to build a Django project. I want to make sure that I do things the right way from the beginning. This might be stupid or trivial but I want to know how to do things the right/best way possible. Lets say I have some models: class User(Models.model): ... class Car(Models.model): ... And in my code, I want to query from them such as User.objects.filter(age=25) User.objects.filter(gender='male') Car.objects.filter(user__age=25) Should I just do the above codes (User.objects.filter(age=25)) directly where it's needed or should I have a module to keep all queries organized in one place like # this is queries.py def getUsersByAge(age): return User.objects.filter(age=age) def getCarByUserAge(age): return Car.objects.filter(user__age=age) ... And in my other places, I would call queries.getUserByAge(25) instead of directly calling User.objects.filter(age=age). I think having separate functions to do this stuff isn't necessary because Django already provides us with good abstractions. But having a single place where all related queries are stored might be a good code management? Thanks! -
importing django.db models messes up my datetime
I have a code which look like this:- print datetime.strftime(datetime.now(),'%Y-%m-%d_%H:%M:%S') It prints out 2016-10-13_03:19:48 ... which is correct for me. But somehow, when i import the django.db module, it messes up my time:- from django.db import models print datetime.strftime(datetime.now(),'%Y-%m-%d_%H:%M:%S') ... gives me this:- 2016-10-13_17:19:48 Can someone help me understsand what's the magic behind? And how can I fix this so that whenever i call datetime, it gives me the first result:- 2016-10-13_03:19:48 Thanks in advance. -
Using Django model inheritence to clone a table
i have a user table and want to create a backup table named deleted_users that is a clone of the user table. When a user gets deleted i want to move the record from the user table to the deleted_users table. class LCUser(models.Model): email = models.EmailField(max_length=100,unique=True) password = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name=models.CharField(max_length=100) class Meta: db_table = "user" class LCUserDeleted(LCUser): deleted_at = models.DateTimeField(auto_now_add=True,null=True) class Meta: db_table = "deleted_users" i tried as above but this creates the user table with all the fields and a deleted_users table with 2 feilds ( lcusers_ptr_id and deleted_at ), How can i create the 2nd table with all the fields without typing everything one by one. -
Django - Cant set date in field
I have current code: # ... from django.utils import timezone class Order(models.Model): # ... pay_date = models.DateTimeField(blank=True, null=True) # ... def pay(self): # ... self.pay_date = timezone.now() self.save() And i call pay method in transaction block: # in one view func. with transaction.atomic(): # ... order.pay() And after - nothing happened, pay_date field still None. I tried set pay_date field directly from console, and it worked. Also, i tried set this field without transaction block, and in pre_save signal, and it didn't worked. -
Django filter based on specific item from reverse relation
I have two models that could look something like this: Course(models.Model): pass WeeklyPrice(models.Model): num_weeks = models.IntegerField() price = models.DecimalField() course = models.ForeignKey(Course) is_erased = models.BooleanField() The thing is i have a search form, which needs to be able to filter by minimum number of weeks. On Course creation, a bunch of WeeklyPrices are also created, which can then be deleted (logically by setting is_erased to True), so a good example would be that Course has 13 instances of WeeklyPrice, starting at week 4, because weeks 1, 2 and 3 have been deleted. So how can i retrieve a queryset of Courses with an instance of WeeklyPrice whose num_weeks is less or equal to the duration variable retrieved from the search form?