Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Insert data in new Mysql table using Django
I am using Mysql as my Database. Currently, I have one table in the database that has the list of user and their details. The second table will contains the all the data related to the monthly bill payment. The admin to enter data related to the payment and I want it to be saved in the new table. After that I want to join both the tables so that I can display all data of a user when the admin enters either id or name. How can I do this? -
Server selection over Angular 2?
I need few suggestions on choosing server over Angular 2. Like if i choose Django as server side, why should i choose and what are its advantages. If i choose Node Js as server, what are its advantages over Django. My requirement goes like: I have developed a website using Angular 2 which basically involves booking system- like order processing, send notification to customers once order status changes via API calls etc. Im bit confused over which server to choose in my scenario since im a newbie in both Django and node js. -
Detect field change in Django model
Is it possible to detect that field in Django model has been changed? class Product(models.Model): my_current_price = MoneyField(max_digits=20, decimal_places=2, null=True, blank=True, verbose_name=_('My original price')) my_eur_price = MoneyField(max_digits=20, decimal_places=2, null=True, blank=True, verbose_name=_('My price in EUR')) my_usd_price = MoneyField(max_digits=20, decimal_places=2, null=True, blank=True, verbose_name=_('My price in USD')) The thing is that I need to recalculate EUR and USD price anytime when my_current_price is changed. I have two ideas: Somehow override MoneyField and send signal when the field is changed. Override save method and create a new attribute __my_current_price like here - this works but it makes code very unclear for me. EDIT: I store the price in different currencies because of faster database lookups. -
Why my Django view return None as HttpResponse?
This is a function I used in Django view to accept post request, however it returns None sometimes, any idea about this problem? def acceptpost(request): try: print "request.method:", request.method print "content_type:", request.content_type print "request.body:",request.body time.sleep(0.1) except Exception as e: log.error(e) return HttpResponse("error") return HttpResponse("OK") The function I used to post data is: try: req = requests.post(url=url, data=data, verify=False, timeout=15) response = req.status_code content = req.content except RequestException as e: response = e.response log_debug.error("HttpResponse: %s" % response) continue In most of time, I could get the right HttpResponse, which is "ok" in this case, and some time I could only get None, both of the two function runs on localhost, the web server is the Django web server with the address http://127.0.0.1/acceptpost/. I have not catch any log in function acceptpost, however there are HttpResponse None occasionally, is any idea about this problem? -
link individual user's profile to user in comment section - Django
I need to link respective user's profile to the comments. Currently all my links are taking me to the logged in user's profile itself. My user model @ user_profile/models.py: class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) ....... ....... objects = manager.CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_absolute_url(self): return "/users/%s/" % urlquote(self.email) My profile model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name="profile", on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True, default='') ..... ..... objects = manager.CustomProfileManager() def get_absolute_url(self): return reverse("user_profile:commenters_profile") Comments/models.py: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comment_by', default=1) .... View: @login_required def commenters_profile(request): instance = get_object_or_404(Profile) context = { "title": instance.title, "instance": instance.get_profile(), } return render(request, "profile.html", context) user_profile/urls.py: urlpatterns = [ url(r'^$', myProfile, name='myProfile'), url(r'^$', commenters_profile, name='commenters_profile'), ] template: <p><a href="{{ comment.user.profile.get_absolute_url }}"> {{ comment.user.get_full_name }}</a></p> Please help. -
Django 301 and 403 forbidden errors on my static files in production
I'm trying to deploy a django website on a ubuntu 14.04 vps using nginx and gunicorn but my css files and js files are not getting loaded.i developed it on the default django development server and it worked very well, but when i deploy my site and collectstatic and try to access it through the browser only the HTML text gets loaded and on checking on my browser console i find 301 and 403 forbidden errors on my static folder. i a newbie to ubuntu and django as well and all the threads and forums i've found online simply point to permissions and ownership of files and haven't had any luck when i correct my permissions. screenshot of my browser error when i try to access django admin here is my 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__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/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 = ['mysite.com','www.mysite.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Django: `create()` did not return an object instance
I am trying to create a comment in a restful API, using Django 1.11.2. Currently i am fallowing the tutorial "Blog API with Django Rest Framework" from "CodingEntrepreneurs". I don't know what the problem is. This the serializer code: def create_comment_serializer(model_type='post', slug=None, parent_id=None, user=None): class CommentCreateSerializer(ModelSerializer): class Meta: model = Comment fields = [ 'id', 'content', 'timestamp', ] def __init__(self, *args, **kwargs): self.model_type = model_type self.slug = slug self.parent_obj = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() ==1: self.parent_obj = parent_qs.first() return super(CommentCreateSerializer, self).__init__(*args, **kwargs) def validate(self, data): model_type = self.model_type model_qs = ContentType.objects.filter(model=model_type) if not model_qs.exists() or model_qs.count() != 1: raise ValidationError("This is not a valid content type") SomeModel = model_qs.first().model_class() obj_qs = SomeModel.objects.filter(slug=self.slug) if not obj_qs.exists() or obj_qs.count() != 1: raise ValidationError("This is not a slug for this content type") return data def create(self, validated_data): content = validated_data.get("content") if user: main_user = user else: main_user = User.objects.all().first() model_type = self.model_type slug = self.slug parent_obj = self.parent_obj comment = Comment.objects.create_by_model_type( model_type, slug, content, main_user, parent_obj=parent_obj ) return comment return CommentCreateSerializer this is the view code: class CommentCreateAPIView(CreateAPIView): queryset = Comment.objects.all() #serializer_class = PostCreateUpdateSerializer permission_classes = [IsAuthenticated] def get_serializer_class(self): model_type = self.request.GET.get("type") slug = self.request.GET.get("slug") parent_id = … -
want to build web site by django for take a value by Temperature sensor on particle-Photon
i want to build an web site by djnago. this site could be able to take values from Temperature sensor which is connection with my particle-Photon. i checked the net but i do not found an compatible libary Which could be connect my Photon and django framwork. is there any helpful libary to do this . my "Temperature.ino" code: #include <OneWire.h> OneWire ds = OneWire(D4); // 1-wire signal on pin D4 unsigned long lastUpdate = 0; float lastTemp; void setup() { Serial.begin(9600); // Set up 'power' pins, comment out if not used! pinMode(D3, OUTPUT); pinMode(D5, OUTPUT); digitalWrite(D3, LOW); digitalWrite(D5, HIGH); } // up to here, it is the same as the address acanner // we need a few more variables for this example void loop(void) { byte i; byte present = 0; byte type_s; byte data[12]; byte addr[8]; float celsius, fahrenheit; if ( !ds.search(addr)) { Serial.println("No more addresses."); Serial.println(); ds.reset_search(); delay(250); return; } // The order is changed a bit in this example // first the returned address is printed Serial.print("ROM ="); for( i = 0; i < 8; i++) { Serial.write(' '); Serial.print(addr[i], HEX); } // second the CRC is checked, on fail, // print error and just return … -
django models filefield upload
hey i want to create a song list for eg ''movie name Titanic and it contains all its songs'' but i don't know to add more than one song in a movie, can some one help me here? here is what i am doing views.py from django.shortcuts import render_to_response from .models import Songs def Songs(request): songs = Songs.objects.all() return render_to_response('profile_page.html',{'songs':songs}) models.py from django.db import models class Songs(models.Model): song_title = models.CharField(max_length=20) song_poster = models.FileField() song_list = models.FileField() urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^',views.Songs), ] -
Regex Expression, that picks value/values within inverted double quotes only
I am trying to make a form validator using a javascript; Value is itself a specific format it can be present 1 or more times, now when the value is tested I need to make sure if the value entered is enclosed within inverted double quotes. Eg. one value :- "C:GSMXXXX&T:GSMXXXX;" more than one, here its 3.. "C:GSMXXXX&T:GSMXXXX; C:GSMXXXX&T:GSMXXXX; C:GSMXXXX&T:GSMXXXX;" -
Django uploaded files not displaying in template page
I am trying to display the top 5 recently posted files but doesnt seem to show up. When i get all the objects by using Model.objects.all(), it gives me all the objects from Db but when i am trying to get the top 5, it does not display. Kindly help and suggest me. Thanks my views.py is def about_experiment(request, ex_link_name): researcher = None study = None posts = None exp = get_object_or_404(Experiment,link_name = ex_link_name) high_scores = ScoreItem.objects.filter(experiment=exp,active=True) context = { 'request': request, 'exp':exp, 'high_scores': high_scores, 'awards':AwardItem.objects.filter(experiment=exp,visible=True), 'posts':Help.objects.filter().order_by('-date')[0], 'documents':Help.objects.filter().order_by('-document')[:5] } if exp.about_file: context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path() if request.method == 'POST': form = AboutHelp(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit = False) obj.save() return HttpResponseRedirect('/about/%s/' %ex_link_name) #return redirect(reverse('lazer.views.about_experiment', kwargs={ 'ex_link_name':obj.link_name })) else: form = AboutHelp() return render(request, 'about_experiment.html', context) destination template page <div class="tab-pane" id="irb"> <h4> List of file(s) uploaded:</h4> <!--File upload--> {% if documents %} <ul> <li><a href="#"> {{ documents.document }} </a></li> </ul> {% else %} <p>No such documents available.</p> {% endif %} <!--File upload ends--> -
Django - using geopy to populate google maps template
I am trying to use geopy and the Google api. I am querying through models to pull address city,state address detail that will feed into geopy's locator and give me lat/lng for the Google Maps api. I would like to: a.) Get a unique set of lat/lng coordinates b.) Pull into template c.) Loop through list and post multiple pins on a map. Here is what i currently have in views. Not sure how to get the loop in the context for rendering into the template. def maps_multi(request): address_list = CustomerOrder.objects.filter(city__icontains = 'CA').distinct() # pulls all unique addresses in California address_list1 = address_list[0:2] # temporarily select first three addresses from list to test geolocator = GoogleV3() for x in address_list1: add_list = [] add_city = x.city location = geolocator.geocode(add_city) add_list.append(location) print(add_list) context = {} return render(request, 'orderdisplay/maps_multi.html', context) -
Django monthly payment app
I am trying to make a Django monthly payment application. From the list of the subscribers, the admin selects the subscriber who is going to pay the monthly charge. Form the subscriber detail page, the admin will continue with the payment. I am using Mysql database. Currently there are two tables in the database. First Table: For Subscribers (id(pK), name, area, subscriberNumber, phoneNumber) Second Table: For Monthly Payment (id(pk), subscriberNumber, month, year, amount, discount, fine, billNumber) What is the idea behind going through the payment system. What should I do to add the data that tells the Subscriber has payed the amount. -
Yet another: Cannot assign "u'3'": "City.state" must be a "State" instance
I'm trying to customize the admin to chain 2 select boxes with ajax and a custom form, everything works great until I try to save the data and i get this error. My models look like this: class State(TimeStampModel): name = models.CharField( max_length=200, verbose_name=u'State', blank=False, null=False, ) code = models.CharField( max_length=20, verbose_name=u'State Code', blank=True, ) coat_of_arms = models.ImageField( upload_to=file_rename('coat_of_arms'), verbose_name='Coat of Arms', null=True, blank=True, ) country = models.ForeignKey( 'Country', blank=False, null=False, ) def __unicode__(self): return self.name class Meta: verbose_name = u'State' verbose_name_plural = u'States' class City(TimeStampModel): name = models.CharField( max_length=200, verbose_name=u'City', blank=False, null=False, ) code = models.CharField( max_length=20, verbose_name=u'City Code', blank=True, ) coat_of_arms = models.ImageField( upload_to=file_rename('coat_of_arms'), verbose_name='Coat of Arms', null=True, blank=True, ) state = models.ForeignKey( 'State', blank=False, null=False, ) def __unicode__(self): return self.name class Meta: verbose_name = u'City' verbose_name_plural = u'Cities' The forms.py: class CityAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CityAdminForm, self).__init__(*args, **kwargs) country_list = self.get_country_choices() state_list = self.get_state_choices() instance = getattr(self, 'instance', None) if instance.pk: self.fields['state'].widget.choices = state_list self.fields['country'].widget.choices = country_list state = forms.CharField(label=u'State', required=True, widget=forms.Select) country = forms.CharField(label=u'Country', required=True, widget=forms.Select) @staticmethod def get_country_choices(): country_list = Country.objects.all() choices_list = [(country.id, country.name) for country in country_list] choices_list.insert(0, ("", "----------")) return choices_list @staticmethod def get_state_choices(country_id=None): if country_id: state_list = State.objects.filter(country_id=country_id) else: state_list … -
How do I use nginx to forward to a docker container running apache2?
I have a Wordpress docker container, which includes apache2. I linked this container to a mysql container. I'd like to also run python/django using nginx and Gunicorn. So, I just have the docker container with apache2 and Wordpress (along with mysql ). I know I need to use the proxy_pass directive, but I'm not sure about a few details. This is on an Ubuntu 16 server. 1) If I run apache2 on port 8080, which I expose by setting -p 80:8080 on the docker run command, does the browser display the port 8080 and do I need to use that in all links? 2) Currently I am using the 192.168.1.x IP range, can I setup the docker containers on a different internal IP range, such as 10.0.0.x and then run apache on port 80 without conflict with nginx server on the same port on the same computer ( not using a container for nginx currently)? 3) Would it be better to just assign my docker containers an IP within the same range of 192.168.1.y and still run apache2 (inside a docker container) and nginx server on port 80? 4) Would you recommend using a subdomain for this WordPress application and … -
JSONP Response from Python Django
I am trying to return a JSONP object from a django view by appending the callback to the response as below: def complete(request): prefix = request.GET.get('q','') mode = request.GET.get('mode','') callback = request.GET.get('callback', '') response = completer_func(prefix, inv_indices, trie) if callback != None: response = '{0}({1})'.format(callback, response) return JsonResponse(response, safe=False) which returns something like "jQuery11110037170758636331014_1499222434194([u'information technology', u'interior design', u'international', u'industrial design', u'information technology services'])" when I check the response under inspect/network in chrome. However, at the client side, it is throwing an error, which I logged to the console and shows that readyState: 4 demo.html:91 responseText: undefined demo.html:92 status: 200 demo.html:93 text status: parsererror demo.html:94 error: Error: jQuery11110037170758636331014_1499222434194 was not called I saw a couple of other posts like this explaining how one should add the callback to the response (which I did). But somehow it doesn't seem to work. I have included the jquery ajax call below $('#ajax-demo').autoComplete({ minChars: 1, source: function(term, response){ $.ajax({ dataType: "jsonp", type: "GET", url: 'http://localhost:8000/complete/', data: { q: term }, success: function (data) { }, error: function(xhr,textStatus,err){ console.log("readyState: " + xhr.readyState); console.log("responseText: "+ xhr.responseText); console.log("status: " + xhr.status); console.log("text status: " + textStatus); console.log("error: " + err); } }); } }); -
Number of online user's in django
I have a website and I want to know number of online user in my website?(login is not required) How can I find number of it? **note : ** just number of online people. -
Looping a certain amount of times in Django Templates
I downloaded a free bootstrap template that I want to use to load in "Show" items. This would be fairly simple, however each set of rows are using the <div class="row">property. For example: <div class="row"> <div class="col-md-4"> //code here </div> </div> <div class="row"> <div class="col-md-4"> //code here </div> </div> I wanted to be able to loop 3 times within a row then after 3 loops, generate another row div tag. How can I achieve this using Django tempaltes? -
Bash script to serve downloads from website
I am attempting to develop a website in which a user inputs a YouTube URL and and can download an Mp4 version of the video on that URL, using the Python program youtube-dl. I was thinking that the easiest way to go about this might be to create a Bash shell file through which the Mp4 may be downloaded to the client. Is this a good method? If so, where should I point the file to have it downloadable? The rest of the website is written in Django, if that would provide a better solution to the above query. Any help would be greatly appreciated. -
How to pass a form value to another view
How to get a form value form one view to another. for example i would like to get the 'web_input' value from InputWebView() and pass it into DisplayWebView() <form method="POST" action=""> {% csrf_token %} {{ form.non_field_errors }} {{ form.web_input }} <input type="submit"> </form/> def InputWebView(requests) form = WebInputForm(request.POST or None) if request.method == 'POST': if form.is_valid(): return redirect('add_web', web_url=request.POST['web_input']) def DisplayWebView(request, web_url): url = web_url -
Django-registration unique email with hmac backend
I use django-registration package in my app. Is it possible to use unique email while using the (proposed by the documentation) hmac backend? I have found many posts that answer for the model backend, not the hmac. -
Django Url direct error
My Django urlpatterns: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^login', views.login_page, name='login'), url(r'^logout', views.logout_page, name='logout'), url(r'^register', views.register_page, name='register'), url(r'^create_book', views.create_book, name='create_book'), url(r'^^(?P<book_id>[0-9]+)/$', views.book_details, name='book_details'), url(r'^^(?P<book_id>[0-9]+)/create_entry$', views.create_entry, name='create_entry'), ] I am trying to do this: {% url 'book:book_details' book.pk %} It gives this error: NoReverseMatch at / Reverse for 'book_details' with keyword arguments '{'book_id': 1}' not found. 1 pattern(s) tried: ['^(?P<book_id>[0-9]+)/$'] But going to localhost:8000/ <some id> directly in the browser works How do I write the {% url %} part so that it goes to /(some id) -
Django REST Framework Filter Queryset Based On URL
When user visits "baseurl/companies/6/inquiry/", I know that the company_id is 6. Then user then has the option to create an inquiry with specific products, but should only see the products that belong to company 6. Here's my viewset: class InquiryViewSet(viewsets.ModelViewSet): queryset = Inquiry.objects.all() serializer_class = InquirySerializer def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() context = self.get_serializer_context() return serializer_class(*args, company_id=self.kwargs['company_id'], context=context, **kwargs) Here's my serializer: class InquirySerializer(serializers.ModelSerializer): def __init__(self, *args, company_id=None, **kwargs): super(InquirySerializer, self).__init__(*args, **kwargs) company_set = Company.objects.filter(pk=company_id) self.fields['company'].queryset = company_set company = serializers.HyperlinkedRelatedField(many=False, view_name='company-detail', queryset=Company.objects.all()) inquirer = UserPKField(many=False) is_anonymous = serializers.BooleanField product_rows = CompanyProductField(many=True, company_id= 'Want to access company_id in __init__') class Meta: model = Inquiry fields = ('pk', 'company', 'inquirer_email', 'inquirer', 'is_anonymous', 'inquiry_date', 'product_rows') read_only_fields = ('inquirer', 'inquiry_date') And here's the CompanyProductField class CompanyProductField(serializers.PrimaryKeyRelatedField): def __init__(self, *args, company_id=None, **kwargs): super(CompanyProductField, self).__init__(*args, **kwargs) self.company_id = company_id def get_queryset(self): product_query = Q(company__pk=self.company_id) return Product.objects.filter(product_query) There has to be a simple way I can access the company_id that's already in InquirySerializer's init method and just pass that on, but I'm stumped. -
Django file now showing in the template
My file is being uploaded in the correct path but I have two issues with it 1) Whenever I refresh my HTML page the file gets uploaded again and again. How do I solve this? Also 2) The file is being uploaded correctly in the path but it is not showing up in the template. Please help me with the code or suggest me. Thanks in advance:) My views.py def about_experiment(request, ex_link_name): researcher = None study = None posts = None exp = get_object_or_404(Experiment,link_name = ex_link_name) high_scores = ScoreItem.objects.filter(experiment=exp,active=True) context = { 'request': request, 'exp':exp, 'high_scores': high_scores, 'awards':AwardItem.objects.filter(experiment=exp,visible=True), } if exp.about_file: context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path() return render(request, 'about_experiment.html', context) if request.method == 'POST': form = AboutHelp(request.POST, request.FILES) posts = Help.objects.filter().order_by('-date')[0] documents = Help.objects.all() if form.is_valid(): obj = form.save(commit = False) obj.save() researcher = form.cleaned_data['researcher'] study = form.cleaned_data['study'] document = form.cleaned_data['document'] else: form = AboutHelp() posts = Help.objects.filter().order_by('-date')[0] documents = Help.objects.all() return render(request, 'about_experiment.html', {'posts': posts}) return render(request, 'about_experiment.html', {'posts': posts}) Source page <form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form" enctype="multipart/form-data"> {% csrf_token %} <label>Researcher Name(s): <input type="text" name="researcher"><br> <lable>Study Summary <textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study"></textarea> <br> <label>Upload your IRB approval letter: <input type ="file" id="irb-file" class="file_input" name="document"></label> … -
Install mod_wsgi on Ubuntu with Python 3.6, Apache 2.4, and Django 1.11
How do I get mod_wsgi for Apache2 that was compiled for Python 3.6.1? (or any future Python version) I am using a Python 3.6.1 virtual environment with Django 1.11 and Everything is working according to the Apache error log except that mod_wsgi for Apache 2.4 was compiled for Python/3.5.1+ and is using Python/3.5.2 so my Python 3.6.1 code is failing because I'm using new features not available in 3.5.2 All of the other configurations and installs involved in setting my system up seem to be fine (Running in daemon mode) though mod_wsgi doesn't seem to be using my Python 3.6.1 virtual environment (though it is trying to use it for Django according to the error log)... I used: sudo apt-get install libapache2-mod-wsgi-py3 to install mod_wsgi for Apache 2.4 I used: ./configure --with-python=/usr/local/bin/python3.6 and make with make install to install mod_wsgi for Python 3.6 I must be doing something wrong - please correct me! Here is my Apache Error Log (cleaned a bit) - and yes I know it fails on the f"" string line (python 3.6 feature not in 3.5) [wsgi:warn] mod_wsgi: Compiled for Python/3.5.1+. [wsgi:warn] mod_wsgi: Runtime using Python/3.5.2. [wsgi:warn] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal …