Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to import data from csv to models using django-import-export?
I've made some researches about django-import-export, but the most of example I have found are using django admin.. I'm trying to import data to a django model from my template (when clicking on a button a modal appears to choose file location and then submit ), I feel lost and I don't know how to start.. This is the model I have : class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) could someone guide me by giving the steps to follow ? Thanks in advance ! -
Development Django instance clashing with Production one (separate IPs)
I have two django instances set up on two different IP addresses. Independently on the private network each one works fine when going to the url of the IP: 192.29.19.1 production 192.29.19.2 development The problem arises with how the urls are setup: https://thewebsite.com <-- production https://thewebsite.com/development <-- development It seems somehow in my settings I have it where Django cannot sort out the fact that they are two different instances. An example of how it fails is: on the development site I have to add /development to the urls.py and the settings.py (for static url) Fine and dandy, the problem is when I try to do stuff with forms, it is like the development server gets a response from the production one. Another example is: The django-registration app fails on the development server under /develpment and keeps routing back to: https://thewebsite.com instead of https://thewebdsite.com/development after signin is clicked, not sure where to even start to change this behavior or what is causing it. So I guess the issue is if I have the websites running as described above, what do I have to set in the development servers setttings, urls (or anything else) to make sure it goes tso the … -
How to make Django's AppConfig ready() run only when serving?
I have some Django apps that run background processes when they start. I use the ready() hook method in apps.py to trigger them. What I didn't know is: this method gets executed on every usage of manage.py. For example, I don't want that code to run when just doing migrations. What could be a proper solution to this? -
How to pass objects.all information from django to jQuery then append to HTML
I've been trying to access the data in my ajax success function for some quite time now to no avail. I have a list of offers I want to show when a user clicks on a specific post(populate #offersdiv). I have the information retrieved in views.py and sent back to the ajax. My problem is how to access the data I have sent. I at least want to retrieve the name of the users who posted the offers. P.S. Forgive my post method I'm quite new to web development and its the method I'm most familiar with. jQuery function getOffers(key){ dict = { 'key':key// pk value of post sent to retrieve offers to it }; key = "pk";//I actually dont know what to put here generateCSRFToken(); $.ajax({ url: "/retrieve_offers/", method: "POST", data : JSON.stringify(dict), success: function(data){ data = JSON.parse(data); Object.keys(data).forEach(function(key){ $("#offercontainer").html( "<p>" + key + "</p>" ) }); }, error: function(){ } }) views.py def retrieve_offers(request): dict = json.loads(request.body) post_key = Post.objects.get(pk=dict["key"]) offers = Offer.objects.filter(post_id=post_key) data = serializers.serialize('json',offers) return HttpResponse( json.dumps(data), content_type="application/json" ) models.py class Post(models.Model): date_submitted = models.DateField() description = models.CharField(max_length=1024) author = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.ForeignKey(to=Category,on_delete=models.CASCADE) trade_item = models.FileField(null=True,blank=True) trade_item_name = models.CharField(null=True,max_length=100) receive_item = models.FileField(null=True, blank=True) receive_item_name … -
Showing a Picture in Django Action Stream
I want an action stream notifications each time a user uploads a picture. I get the usual "Actor uploaded a photo on datetime", but I can't figure out how to add the actual picture. I think it should be an action_object, but I can't get the right iteration to show the actual picture. Photo.objects.get(pk=target) might work, but I can't render it outside the template. Any ideas? -
Why is this Django QuerySet returning no results?
I have this Class in a project, and I'm trying to get previous and next elements of current one. def get_context(self, request, *args, **kwargs): context = super(GuidePage, self).get_context(request, *args, **kwargs) context = get_article_context(context) all_guides = GuidePage.objects.all().order_by("-date") context['all_guides'] = all_guides context['next_guide'] = all_guides.filter(date__lt=self.date) context['prev_guide'] = all_guides.filter(date__gt=self.date) print context['next_guide'] print context['prev_guide'] return context These two lines: context['prev_guide'] = all_guides.filter(date__lt=self.date) context['next_guide'] = all_guides.filter(date__gt=self.date) are returning empty results as printed in the console: (QuerySet[]) (QuerySet[]) What am I missing? -
add processing images in the model.py using django
I want to create a simple image processing using Django. my tasks is easy I have some user a simple model and that user can upload images in my project using html form or django form and then that images saves to upload_to='mypath' in upload from my model. but I have some questions : I have a simple image processing in my views.py if the processing complete success then create new image and I want that image to add in the upload from my model . how to do that in Django ? models.py class MyModel(models.Model): user = models.ForeignKey(User) upload = models.ImageField(upload_to='mypath/personal/folder/per/user') -
django check if the uploaded file is a zip file
I have a handler for a POST method in Django which receives an uploaded file. What I would like to do is verify that the file is a valid zip file before proceeding. So, I have: @login_required(login_url="login/") def upload(request): if request.method == 'POST' and request.FILES['upload_file']: uploaded_file = request.FILES['upload_file'] print type(uploaded_file) return render(request, 'upload.html', {'context': RequestContext(request)}) Now at this point uploaded_file is of type <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>. My question is what would be the best way to verify that this is a valid archive? Do I need to save it to the disk and then use the zipfile module or is there some way to do it without writing to the disk? -
Ajax Call Not Returning Data Django
I want to write a simple ajax method to fire up whenever the document is ready. I have the following JS: $(document).ready(function() { $.ajax({ type:'GET', url: '/get_alert', sucess: function(data){ data = JSON.parse(data); alert("Hi"); console.log(data); $('#notification_symbol').css('display','inline'); }, error: function(){ console.log("Hello"); } }); } I can confirm that the url is working and that the call is being made on ready. However, it is not returning any data. Here is my function in views.py: def get_alert(request): alert = False events = EventInvite.objects.filter(Invitee_id=request.user.id, Status= InvitationStatus.objects.filter(Status='Pending')[0]).order_by('-date') for event in events: if event.seen: alert = True dict = { 'alert':alert, } print(dict) # Tells me the call is being made on ready... return JsonResponse(dict) Any ideas? -
Get primary key of a deserialized object in Django
I have a list of objects stored in session (to pass the list from one view to another) [okay, there has to be a better way of doing this but this is a question for another time!] I access the list from the session by doing: object_list = request.session.get('object_list', None) But this object_list is actually a serialized django object. What i need is to now get all the pk of this object_list (to then rebuild a clean queryset...) I tried this (deserializing then getting pk) object_list_id=[] for obj in serializers.deserialize("json", object_list): object_list_id.append(obj.pk) but it doesn't seem to work.. any ideas ? 'DeserializedObject' object has no attribute 'pk' PS: if i debug the obj from the loop, this is the object type: {<DeserializedObject: riskass.Rating(pk=7)>} -
Which is a better way to query in Django (Raw query vs ORM)?
I am using MySQL, I have two schemas and I have to perform a join over multiple schemas, which as you might know is not supported with the Django ORM. So, this is most simplified SQL query for this scenario SELECT * FROM db1.a AS a JOIN db2.b AS b ON b.some_id = a.id WHERE a.name = 'localhost' DJANGO ORM Now, if I use Django ORM, I will have to do something like a_obj = ModelA.objects.filter(name='localhost') ModelB.objects.filter(some_id__in=a_obj) DJANGO RAW SQL / CONNECTION from django.db import connection sql = 'SELECT * FROM db1.a AS a JOIN db2.b AS b ON b.some_id = a.id WHERE a.name = %s' cursor = connection.cursor() try: cursor.execute(sql, ['localhost']) row = cursor.fetchall() except Exception as e: cursor.close Now, I understand that both of them are going to give me the required result. But, why use one over the other? From what I see, the Django ORM will have to hit the database twice to get the required info, while the raw query can get it with a single hit, here in my opinion the raw query wins. Again, the raw query prevents from sql injection attacks by using parameterised query, which escapes the variable, thus preventing the … -
How to redirect django-registration-redux registration page payment gateway?
How do redirect my registration page to payment gateway page after registration in django-registration-redux. -
Create template tags with the following function
I have formally constructed the function in my models.py file : from datetime import datetime from django.template.defaultfilters import date as datefilter from django.utils import translation def date_customerprofile(language): now_ = datetime.today() if language == 'English': translation.activate('en') return datefilter(now_, 'l, F j, Y') else: translation.activate('fr') return datefilter(now_, 'l, j F Y') I know Django's template language is NOT Python, so we can't write {{ customer.date_customerprofile('French') }}. The solution here is to create a custom templatetag. Also note that translation.activate will change the active language for the remaining of the request/response cycle - using the translation.override context manager is certainly a better idea. As I am not an expert with templatetags, could anyone be able to show me how could I create it in taking into consideration the above function? I think we could use the following question to do such thing How to format date in different languages? Thanks in advance! -
Correct way to add fields to a model on django
I have a User model and i want to add a new field to the user, in the database and in the user form. i have looked online many differente ways to do this but i want to know what is the "correct" way to do it. Specially the correct way to create migrations. Django Version: (1,10,0,u'final',1) -
Django Like button ajax
I'm been trying to create like button with ajax. In my model strain i have a field call user_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='strains_liked', blank=True) This is my views.py @login_required @require_POST def strain_like(request): strain_id = request.POST.get('id') action = request.POST.get('action') if strain_id and action: try: strain = Strain.objects.get(id=strain_id) if action == 'like': strain.user_like.add(request.user) else: strain.user_like.remove(request.user) return JsonResponse({'status': 'ok'}) except: pass return JsonResponse({'status': 'ok'}) this is urls.py url(r'^like/$', views.strain_like, name='like') and this is my templates {% block content %} {{ strain.name }} {% with total_likes=strain.user_like.count user_like=strain.user_like.all %} <span class="count"> <span class="total">{{ total_likes }}</span> like </span> <a href="#" data-id="{{ strain.id }}" data-action="{% if request.user in user_like %}un{% endif %}like" class="like"> {% if request.user not in user_like %} Like {% else %} Unlike {% endif %} </a> {% endwith %} {% endblock %} <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function () { $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "strains:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); $('a.like').text(previous_action == 'like' ? 'unlike' … -
Automatically create One-To-One relation when using reverse field
When creating two instances of a model and connecting them using a OneToOneField, the connection gets created and saved automatically at object creation: from django.db import models class MyModel(models.Model): name = models.CharField(max_length=255) next = models.OneToOneField('self', on_delete=models.SET_NULL, related_name='prev', null=True, blank=True) >>> m2 = MyModel.objects.create(name="2") >>> m1 = MyModel.objects.create(name="1", next=m2) >>> m2.prev <MyModel: 1> >>> m2.refresh_from_db() >>> m2.prev <MyModel: 2> However, when creating the same connection but using the reverse field, the creation is also done automatically but not the save. >>> m1 = MyModel.objects.create(name="1") >>> m2 = MyModel.objects.create(name="2", prev=m1) >>> m1.next <MyModel: 2> >>> m1.refresh_from_db() >>> m1.next How can I have it always save the relation when created using the reverse field without having to manually use .save() each time? -
django: access elements from another template
project/ |----app1/ |----templates/ app1/ |----home.html |----exchange.html I need to perform calculations on the home.html using javascript, but some data is stored in the table inside exchange.html, and I don't want to put them together under one page. how would I go about that. I am very new to python and django. {% include "exchange.html" %} I tried this on home.html but it loads all the content which i don't need. can anybody help please. <table class="table table-hover"> <caption>Exchange rate</caption> <thead> <tr> <th></th> <th>GBP</th> <th>EUR</th> <th>USD</th> <th>CAD</th> <th>AUD</th> </tr> </thead> <tbody> <tr> <td>GBP</td> <td><input type="number" value="1" readonly></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> </tr> <tr> <td>EUR</td> <td><input class="rate" type="number"></td> <td><input type="number" value="1" readonly></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> </tr> <td>USD</td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input type="number" value="1" readonly></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <tr> <td>CAD</td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input type="number" value="1" readonly></td> <td><input class="rate" type="number"></td> </tr> <tr> <td>AUD</td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input class="rate" type="number"></td> <td><input type="number" value="1" readonly></td> </tr> </tbody> </table> I have this table in exchage.html where users can input the exchange rate, and I … -
Filter bar not displaying the list categories Django
I'm implementing a filter bar to allow users to filter through the various types of aircrafts. Within my aircraft model there are 4 categories: manufacturer, type, body and range. However they're not displaying in the options, rather it's just blank. I'm actually quite confused on how to implement it. Is it similar to a search bar? Html <form method="GET" class="filter"> <select class="form-control "> <optgroup label="This is a group"> <option value="12" selected="">{{ aircraft.manufacturer }}</option> </optgroup> </select> <select class="form-control "> <optgroup label="This is a group"> <option value="12" selected="">{{ aircraft.aircraft_type }}</option>aircraft_type </optgroup> </select> <select class="form-control "> <optgroup label="This is a group"> <option value="12" selected="">{{ aircraft.body }}</option> </optgroup> </select> <select class="form-control "> <optgroup label="This is a group"> <option value="12" selected="">{{ aircraft.range }}</option> </optgroup> </select> <input type="submit" value="Submit"> </form> This is my view. It's only returning the list: def list_aircraft(request): aircraft = Aircraft.objects.all() return render(request, 'aircraft/aircraft_list.html', { 'aircraft': aircraft,}) How do I return the filter posts to the same page? -
Django: choose 'company' from company model, if company not present create one
I have a use case where in UserProfile model, user details are stored. One of the field is user_company_name. class UserProfile(BaseModel): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) user_company_name = models.CharField(max_length=254) Instead of a CharField I want the field to be a ChoiceField, having drop down of the Company (names) currently present in the database. If the current company of the user is not present in the dropdown I plan to give the user an option to add his or her company to the DB. Suppose I have a Company model as such: class Company(BaseModel): name = models.CharField(max_length=100) def __str__(self): return self.name What should be my Field Choice in the UserProfile model for user_company_name field. -
how can i add foreign key to existing class in django
I have simple models of country and town: from django.db import models class country(models.Model): name = models.CharField(max_length=50) class town(models.Model): belongs_to = models.ForeignKey(country, on_delete=models.CASCADE) name = models.CharField(max_length=50) Now, I would like to play around a bit... and I would like to add continent. I guess correct way from the start would be to do this: from django.db import models class continent(models.Model): name = models.CharField(max_length=50) class country(models.Model): belongs_to = models.ForeignKey(continent, on_delete=models.CASCADE) name = models.CharField(max_length=50) class town(models.Model): belongs_to = models.ForeignKey(country, on_delete=models.CASCADE) name = models.CharField(max_length=50) If I do that and save the file, add continents in admin.py to admin.site.register(continent), start with makemigrations... I get this: You are trying to add a non-nullable field 'belongs' to country without a default; we can't do that (the database needs som ething to populate existing rows). Please select a fix: 1.) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2.) Quit, and let me add a default in models.py I get stuck here, because I do not know what to do from here? -
Not able to validate field in django restframeork , How do i overcome of this kind error
serializers.py class UserSerializer(serializers.ModelSerializer): city = CitiesSerializers() state = StatesSerializers() country = CountrySerializes() class Meta: model = User fields = ('url', 'username', 'email', 'groups', 'first_name', 'last_name', 'company_name', 'email2', 'address', 'country', 'state', 'city', 'pincode', 'phone_no1', 'phone_no2', )`class CountrySerializes(serializers.ModelSerializer): class Meta: model = Countries fields = ('__all__') class StatesSerializers(serializers.ModelSerializer): class Meta: model = States fields = ('__all__') class CitiesSerializers(serializers.ModelSerializer): class Meta: model = Cities fields = ('__all__') ` view.py if serialized.is_valid(): User.objects.create_user(company_name=company_name, email2=email2, address=address, country_id=country, state_id=state, city_id=city, pincode=pincode, phone_no1=phone_no1, phone_no2=phone_no2, password=password, username=username, email=email, first_name=first_name, last_name=last_name, is_active=is_active) return Response({'status': 1, "message": "User created with this detail"}, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) response in REST {"city":["This field is required."],"state":["This field is required."],"country":["This field is required."]} Above I have mentioned code for DRF application and i am not able to save user without validation -
How to integrate the Angular Material icon asset path with Django template?
I have use Django as the back-end of my web system and the Angularjs material as the front-end. In the front-end html files, I use the {% load staticfiles %} tag to specify the static files path. such as the angular-material.css file: {% load staticfiles %} <link rel="stylesheet" href="{% static 'node_modules/angular-material/angular-material.css' %}"/> When I put a to the html, it's md-svg-src attribute should be set to be specified as the svg file path. So how to set the svg file path as the value of md-svg-src without use {% load staticfiles %} tag? Because the md-icon is frequently used in the html, put a {% load staticfiles %} tag before every md-icon seems too ugly. PS: my Angularjs script code is stored in a standalone js file index.js, the $mdIconProvider config is in this file too. However, I haven't found that Django could translate its template tag {% load staticfiles %} in js file. -
Django Form Not Validating
I want to implement forgot password functionality. In my verification code function, form is not validating. Here is my Views File: def getVerCode(request): if (request.method == 'POST'): form = VerCodeForm(request.POST) print(form.errors) if (form.is_valid()): print('VALID') code = request.POST.get('verCode', '') print('GETVERCODE : ', verCode) if (code == verCode): pass return HttpResponseRedirect('/custom/GetPassword', {'form': form}) else: form = VerCodeForm() return render_to_response('EmailVerification.html', {'form': form}) Template: {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'FormStyle.css' %}" /> {% block body %} <div class = "formArea"> {% csrf_token %} <label> Enter the verification code sent to your email account: </label> {{ hidden_email }} <div class="formFields"> <form method="POST"> <input type="text" name = "email" size="50"> </input> {{ form.verCode.errors }} <input type="submit" value="Submit"> </form> </div> </div> {% endblock %} Form: class VerCodeForm(forms.Form): verCode = forms.CharField(max_length = 10) I tried to print the form.errors: It says This Field is Required! -
How to override models __str__ method so you would have different presentation in admin panel
What is the clean way to override __str__ method of a model so that admin and super admin see it differently in admin panel. In my model class I want to check if user is is_superuser or not so I could show different things in __str__ method. Point of this is the situation that my super admin can see all objects belonging to everyone but normal admin can only see his objects so if I write: def __str__(self): return "Object: %s , created by: %s"%(self.title,self.created_by) My super admin will be able to see who is the creator of object in panel, and that is fine. But my normal admin will see only his objects and not needed message saying that he is the creator. That is why I would need a different return in __str__ method for normal admins. -
invalid literal for int() with base 10: 'None'
Models - from django.core.validators import RegexValidator from django.db import models from multiselectfield import MultiSelectField from django.shortcuts import render from django.core.urlresolvers import reverse # Create your models here. class Register(models.Model): GENDERS =(('M', 'MALE'), ('F', 'FEMALE') ) AREA =( ('CIVIL','Civil Matters'),('CRIMINAL','Criminal Matters'), ('FAMILY','Family Disputes Matters '), ('LABOUR','Labour Disputes Matters'), ('FOREST','Forest Matters'), ('ROC','Company Matters'),('CONSUMER','Consumer Matters'),('EXCISE','Excise Matters'),('ELECTRICITY','Electricity Board Matters'),('EPF','Employee Provident Fund'),('RAILWAY','railway Matters'), ('PENSION','Pension Matters'),('INCOME','Income Tax Matters'),('WRITS','Writs') ) first_name = models.CharField(max_length=50,blank=False,default=None) last_name = models.CharField(max_length=50,blank=False,default=None ) father_name = models.CharField(max_length=50,blank=False,default=None ) date_of_birth=models.CharField(max_length=50,blank=False,default=None,) gender = models.CharField(choices=GENDERS, default='M', max_length=10,blank=False,) email = models.EmailField(max_length=50,blank=False,default=None) office_address = models.CharField(max_length=10000,blank=False,default=None) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") mobile_number = models.CharField(validators=[phone_regex], max_length=10,blank=False,default=None) # validators should be a list office_landline = models.CharField(validators=[phone_regex], max_length=10,blank=False,default=None ) State_BAR_Registration = models.CharField(max_length=20,blank=False,default=None) local_BAR = models.CharField(max_length=20,blank=False,default=None) Place_Of_Practice = models.CharField(max_length=100,blank=False,default=None) area = MultiSelectField(choices=AREA,max_choices=3,max_length=100,blank=False,default=None) other_area = models.CharField(max_length=100,blank=True,default=None ) def get_absolute_url(self): return reverse('home') def __str__(self): return str(self.pk) + str(self.first_name) class Heads(models.Model): heading=models.CharField(max_length=100) class Service(models.Model): heading = models.ForeignKey(Heads,null=True) services = models.CharField(max_length=100) cost = models.CharField(max_length=100) image = models.ImageField() Forms - from django import forms from .models import Register class RegisterForm(forms.ModelForm): class Meta: model = Register fields =[ "first_name","last_name","father_name","date_of_birth","gender","email","office_address", "mobile_number","office_landline","State_BAR_Registration","local_BAR","Place_Of_Practice", "area","other_area", ] Urls - from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register$', …