Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
api-token-auth takes the password field as username and sends the empty password
The value of password parameter is being sent as username to django backend and the password it receives as empty string when I use django-auth-ldap module which returns "Rejecting empty password for "***password****". Everything works fine with default backend authentication. -
How to get form input using forms.Form into a postgres database?
Here is my code: My forms.py looks like: from django import forms class SimpleForm(forms.Form): website = forms.URLField(required=True, widget=forms.TextInput( attrs={'placeholder': "http://www.example.com"})) email = forms.EmailField(required=True, widget=forms.TextInput( attrs={'type': 'email', 'placeholder': "john.doe@example.com" })) My views.py looks like: from django.shortcuts import render, redirect from django.template import loader from .forms import SimpleForm def simple_form(request): if request.method == 'POST': form = SimpleForm(request.POST) if form.is_valid(): website = form.cleaned_data['website'] email = form.cleaned_data['email'] return render(request, 'some_page.html') else: form = SimpleForm() return render(request, 'some_other_page.html', {'form': form}) As for my HTML form, it looks like the following below: <form method="post"> {% csrf_token %} <div class="some-class"> <label for="website">Enter Your Site:</label> <!-- <input type="text" id="website" placeholder="http://www.example.com" name="website" /> --> {{ form.website }} <label for="email">Enter Your Email:</label> <!-- <input type="text" id="email" placeholder="john.doe@example.com" name="website" /> --> {{ form.email }} </div> <div class="some-other-class"> <div class="another-class"> <button name="submit">Submit</button> </div> </div> </form> My question is, how do I get the input for this form into a table in my postgres database? -
Django user model
I am creating a model for Teachers, who will also be login into the system. I have a group called Teachers. All the teachers are assigned to this group. In my teachers model, I have used the following. from django.contrib.auth.models import User, Group class teacher(models.Model): userid = models.OneToOneField(User.objects.filter(group_name='Teachers' ), on_delete=True) emp_no = models.CharField(max_length=8, unique = True) ... I get the following error. File "/home/irj/src/python3/pas/setup/models.py", line 161, in <module> class teacher(models.Model): File "/home/irj/src/python3/pas/setup/models.py", line 168, in teacher userid = models.OneToOneField(User.objects.filter(group_name='Teachers'), on_delete=True) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/query.py", line 836, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/query.py", line 854, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1253, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1277, in _add_q split_subq=split_subq, File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1153, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1015, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1373, in names_to_path field_names = list(get_field_names_from_opts(opts)) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 44, in get_field_names_from_opts for f in opts.get_fields() File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/options.py", line 735, in get_fields return self._get_fields(include_parents=include_parents, include_hidden=include_hidden) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/options.py", line 797, in _get_fields all_fields = self._relation_tree File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/irj/src/python3/django.env/lib/python3.6/site-packages/django/db/models/options.py", … -
Can I host django project in my bluehost shared hosting plan
I want to host my ecommerce website build in django in bluehost shared hosting plan. How I host ?? -
django - model form performing action post save (form valid?)
I am trying to perform an additional action on a model form post save. From what I understand this is achieved with form_valid? however when I am testing, submitting a form and printing out during form valid I am not getting any output in console. is this the right method? Thanks class AddCircuit(CreateView): form_class = CircuitForm template_name = "circuits/circuit_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('circuits.add_circuit'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(Site, pk=self.site_id) return super(AddCircuit, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("circuits:site_circuit_overview", args=(self.site_id,)) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() kwargs['is_add'] = True return kwargs def form_valid(self, form): self.object = form.save() print('Post Save: {}'.format(self.object.id)) return HttpResponseRedirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.site.location context['FormType']='Add' context['active_circuits']='class="active"' return context -
Django 'locations_extras' is not a registered tag library
I'm trying to write a template tag in an app I created to use in another app's template. Both apps are most definitely in INSTALLED APPS My app is listed before the other in that list I've restarted the server My templatetags folder has an init.py (double underscore, but SO is formatting it) What am I doing wrong? -locations -admin.py -apps.py -models.py ..etc etc --templatetags - __init__.py - extras.py Template file: {% load locations_extras %} -
Django model datetime - weird unix timestamp
I store a datetime in database (SQLite). I save python datetime objects with UTC timezone (so they are aware) in my models. When I check the database I literally see 2018-02-28 00:00:00. When I fetch data from database I see: >>> Price.objects.last().datetime.timetuple() time.struct_time(tm_year=2018, tm_mon=2, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=59, tm_isdst=0) So far so good (time is really a midnight). But once I try to divide UNIX timestamp I get wrong result: >>> time.mktime(Price.objects.last().datetime.timetuple()) / 3600 / 24 17589.958333333332 When I adjust the timestamp with +1 hour it's finally right. >>> (time.mktime(Price.objects.last().datetime.timetuple()) + 3600) / 3600 / 24 17590.0 What do I do wrong? Why struct_time shows hours=0 and minutes=0 but once I call time.mktime it gets wrong? -
'InMemoryUploadedFile' object has no attribute 'temporary_file_path'
I got an error 'InMemoryUploadedFile' object has no attribute 'temporary_file_path' .I wrote codes in index.html <main> <form action="/app/img/" method="POST" enctype="multipart/form-data" role="form"> {% csrf_token %} <h3>Upload Image!!</h3> <div class="input-group"> <label class="input-group-btn"> <span class="btn-lg"> Select image <input id="file1" type="file" name="image" accept="image/*"> </span> </label> </div> <div class="col-xs-offset-2"> <input id="send" type="submit" value="Send" class="form-control"> </div> </form> </main> in views.py @require_POST def img(request): img_form = ImageForm(request.POST,request.FILES) if request.method == "POST" and img_form.is_valid(): image = request.FILES['image'].temporary_file_path() with open(image, 'rb') as image_file: content = base64.b64encode(image_file.read()) content = content.decode('utf-8') I rewrote image = request.POST.get("image", "") in place of image = request.FILES['image'].temporary_file_path(),so No such file or directory: '' error happens in with statement.What is wrong in my code?How should I fix this? -
Django declaring type of subclassing models
I need to make a "portfolio" for a site in Django im working on. I wan't the portfolio to contain both Galleries of pictures and links to sites. I set the models up like this: class PortfolioObject(models.Model): types = ( (0,"gallery"), (1, "link") ) name = models.CharField(max_length=100) oType = models.IntegerField(choices=types, default=0) class Meta(): abstract = False class GalleryObject(PortfolioObject): picture = models.FileField(blank=True) oType = 0 class LinkObject(PortfolioObject): link = models.URLField(blank=True) oType = 1 As you can see i want the PortfolioObject to have a "type" depending on which type it is. However this doesn't work, and the oType property is still 0 on LinkObjects. How can i properly index the types of portfolioobjects while still having the convenience of using PortfolioObject.objects.filter(someField=someFilter)? -
Message Framework - Remove uplicate message
I have the following code: {% for message in messages %} <div class="{{ message.tags }}">{{ message }}</div> {% endfor %} There are situations when the same message is repeated multiple times. How can I make the messages to be unique ? -
Django: Autofill ForeignKey CreateView
Using Django 2.0 Yes, I have searched and tried similar questions/solutions none of them seem to solve my issue though Basically I have this books site which goes:Country->Subject->Grade->Resources (resources represents the things needed to make the book like Images,videos,audios ect..) I having a problem when creating a new resource, since the resource are linked to a Grade by a ForeignKey when I try to autofill the ForeignKey, I dont see to get a way to reference the Grade I'm coming from, I dont want to display a list of grades because it would display all the grades from other books as well. Is there a way to autofill the ForeignKey field with the Grade object I'm comming from? models.py class Country(models.Model): name = CharField [...] class Subject(models.Model): name = ForeignKey(Country) [...] class Grade(models.Model): name = ForeignKey(Subject) [...] class Resource(models.Model): name = ForeignKey(Grade) [...] Views.py # Display both models in the same view #Basically a list of countries containing the available subjects for that country class CountryList(LoginRequiredMixin, ListView): login_url = 'accounts/login/' template_name = 'ListsViews/CountryList.html' model = Subject context_object_name = "Subjects" def get_context_data(self, **kwargs): context = super(CountryList, self).get_context_data(**kwargs) context["Countries"] = Country.objects.all() return context # A list of Grades available for the selected … -
How can i make my videos downloadable using Django?
I have embeded multiable videos in my project, I want to make them downloadable. -
ModelChoiceField Validation Error when Dynamically Disabling Field
Hi all I have the following form defined as below. If it is a form that is being passed a fte_assignment object and if it is not None I then want to disable the user field which seems to be working. The issue is when I submit the form I get the following field error Select a valid choice. That choice is not one of the available choices. I'm wondering what can I change so that the field is still disabled put will pass validation? Below I include the needed form definition information and the call from the view. forms.py class TeacherForm(forms.Form): def __init__(self, *args, **kwargs): self.location = kwargs.pop('location', None) self.end_year = kwargs.pop('end_year', None) # fte_assignment gets passed in if it is an edit this helps # with when to fire off our clean method logic self.fte_assignment = kwargs.pop('fte_assignment', None) super(TeacherForm, self).__init__(*args, **kwargs) # THIS IS WHERE I DISABLE THE FORM if self.fte_assignment: self.fields['user'].disabled = True user = forms.ModelChoiceField( label='Employee', queryset=User.objects.all() ) room = forms.CharField(max_length=6) extension = forms.IntegerField() job = forms.ModelChoiceField( queryset=Job.objects.all() ) views.py fte_assignment = FTEFutureAssignment.objects.get(pk=fte_id) form_kwargs = { 'user': fte_assignment.user, 'room': fte_assignment.room, 'extension': fte_assignment.extension, 'job': fte_assignment.job } form = TeacherForm( request.POST or None, initial=form_kwargs, location=location, end_year=end_year, fte_assignment=fte_assignment ) -
Django : static files are not loaded
i'm trying to test the code mentionned in this page : dynamic-formset.js and i added : <script src="{% static 'js/dynamic-formset.js' %}"></script> <script src="{% static 'js/jquery-3.3.1.js' %}"></script> in order to load static files that contains js. howerver the js doesn't work and i'm getting in the console the following lines : "GET /static/js/dynamic-formset.js HTTP/1.1" 404 1777 "GET /static/js/jquery-3.3.1.js HTTP/1.1" 404 1768 do you have any idea why it doesn't work ? i guess that the static files are not loading. Any help please ? Thank You -
webpack not reflecting changes in js files with react and django
I'm trying to build an app with React Frontend and DRM backend. I use webpack_loader and followed instructions online to set it up. I serve the static files from Amazon CDN, but my local changes on the js files are not reflected when I test locally by python manage.py run server webpack.config.js var debug = process.env.NODE_ENV !== "production"; var webpack = require('webpack'); var path = require('path'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: path.join(__dirname, "src"), devtool: debug ? "inline-sourcemap" : null, entry: { index: ["./js/index.js"], explore: ["./js/explore.js"], post: ["./js/post.js"] }, module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader', query: { presets: ['react', 'es2015', 'stage-0'], plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'], } } ] }, output: { path: __dirname + "/src/bundle", filename: "[name].min.js", publicPath: "/src/bundle/", }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'), new BundleTracker({filename: './webpack-stats.json'}), ], }; What I ran node_modules/.bin/webpack --config webpack.config.js python manage.py collectstatic --noinput -i node_modules which collects the static files onto the CDN. I double checked that both vendors.js and index.min.js are correct on the CDN and doesn't contain the old url that I had changed. Now I'm really confused why it's still able to … -
Creating user with default group django rest framework viewsets
how do I create user with default group? my serializer class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user views.py class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer How do I set user group when creating from this view? -
how to display contents from database into tabular format in django
class Venue( RandomIDMixin, TimeStampedModelMixin, models.Model ): """ Venue model for storing metadata about a place. """ VENUE_TYPES = ( ('shul', 'Shul'), ('hall', 'Hall'), ('residence', 'Residence'), ('other', 'Other'), ) address1 = models.CharField(max_length=256, blank=True, default="") address2 = models.CharField(max_length=256, blank=True, default="") city = models.CharField(max_length=256) country = models.ForeignKey('countries.Country', null=True) description = models.TextField(blank=True, default="") display_address = models.CharField(max_length=256, blank=True, default="") image = models.FileField( blank=True, null=True, upload_to=prefix_venue_images, default='{}{}'.format(settings.MEDIA_URL, settings.VENUE_DEFAULT_IMAGE)) name = models.CharField(max_length=128) postal_code = models.CharField(max_length=12, blank=True, default="") region = models.CharField(max_length=128, blank=True, default="") venue_type = models.CharField(max_length=128, choices=VENUE_TYPES, default='hall') website_url = models.URLField(max_length=512, blank=True, default="") class Meta: unique_together = ('name', 'address1', 'city') def __str__(self): return '{0}, {1}, {2}'.format(self.name, self.city, self.region) I want to show above information in table format on admin site. I am a beginner having zero knowledge of django. -
ValueError when using multi zip in Django view
I have a multi zip value what I want to send to the template. When I tried to send it I got the following error message: ValueError: Need 2 values to unpack in for loop; got 5. My code is: a=[1,2,3,4,5] b=[1,2,3,4,5] c=[1,2,3,4,5] d=[1,2,3,4,5] e=[1,2,3,4,5] data_1=zip(a,b,c,d,e) x=[1,2,3,4,5] y=[1,2,3,4,5] z=[1,2,3,4,5] q=[1,2,3,4,5] w=[1,2,3,4,5] data_2=zip(x,y,z,q,w) send_data = { 'data_1':data_1, 'data_2':data_2, } return render(request, 'project/index.html', send_data) Full error messages: Django version 2.0.2, using settings 'source.settings' Starting development server at http://0.0.0.0:80/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/project/views.py", line 378, in dashboard_data return render(request, 'project/index.html', send_data) File "/usr/local/lib/python3.4/dist-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/usr/local/lib/python3.4/dist-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/usr/local/lib/python3.4/dist-packages/django/template/base.py", line 175, in render return self._render(context) File "/usr/local/lib/python3.4/dist-packages/django/test/utils.py", line 98, in instrumented_test_render return self.nodelist.render(context) File "/usr/local/lib/python3.4/dist-packages/django/template/base.py", line 943, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.4/dist-packages/django/template/base.py", line 910, in render_annotated return self.render(context) File "/usr/local/lib/python3.4/dist-packages/django/template/loader_tags.py", line 155, in render return compiled_parent._render(context) … -
How do I fix the following django error?
So I have a django project Where I trying to pass the following function named locate. I think I have figured the right query set. But I keep facing the following the following error. NoReverseMatch at /incubators/1/ Reverse for 'locate' with no arguments not found. 1 pattern(s) tried: ['locate/(?P\d+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/incubators/1/ Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'locate' with no arguments not found. 1 pattern(s) tried: ['locate/(?P<incubator_id>\\d+)/$'] Exception Location: C:\Users\my dell\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: C:\Users\my dell\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.1 My views.py look something like this: def details(request, incubator_id): inc = get_object_or_404(Incubators, pk = incubator_id) details = Details.objects.get(pk = incubator_id) return render(request, 'main/details.html', {'inc': inc, 'details': details}) def locate(request, incubator_id): pos = Incubators.objects.values_list('latt', 'lonn').filter(pk = incubator_id) return render(request, 'main/locate.html', {'pos': pos}) I am trying to pass the incubator_id as the primary key. Now I am preety sure the error is here below in my urls.py url(r'location/', views.location, name = 'location'), url(r'prediction/', views.prediction, name = 'prediction'), url(r'^locate/(?P<incubator_id>\d+)/$', views.locate, name = 'locate'), Help would be greatly appreciated. -
Image cannot be uploaded
Image cannot be uploaded.form.is_valid() always returned Flase.I wrote in html <main> <form action="/app/img/" method="POST" enctype="multipart/form-data" role="form"> {% csrf_token %} <h3>Upload Image!!</h3> <div class="input-group"> <label class="input-group-btn"> <span class="btn-lg"> Select image <input id="file1" type="file" name="image" accept="image/*"> </span> </label> </div> <div class="col-xs-offset-2"> <input id="send" type="submit" value="Send" class="form-control"> </div> </form> </main> in views.py @require_POST def img(request): img_form = ImageForm(request.POST or None) print(img_form.is_valid()) if request.method == "POST" and img_form.is_valid(): image = request.POST.get("image", "") in forms.py class ImageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = Image fields = ('image',) I really cannot understand why I can't sent images.form.is_valid() returned Flase means Form cannot be gotten images, right? What is wrong in my code?How should I fix this? -
Why can't I access request attribute inside a decorator?
I'm using request.POST.get('...') inside my Django decorator (@save_post_request) whenever my form is submitted, on each tentative I get this same error (error with request.<anything>): AttributeError: 'collectData' object has no attribute 'POST' My decorator is called on top of a post() function inside CollectData classBasedView. #views.py class collectData(View): template_name = 'collect_data.html' context = {...} def get(self, request, *args, **kwargs): ... return render(request, self.template_name, self.context) @save_post_request def post(self, request, *args, **kwargs): ... return redirect(reverse('collectData')) #decorators.py def save_post_request(function): def wrap(request, *args, **kwargs): title = request.POST.get('title') # <--- return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap I'm not sure if a decorator can be called like so using classBasedViews, but I think it should be right, what is my mistake? -
DRF use another model related fields in serializer
i have 3 model Product - peyment - productdiscountcontroll peyment and discountcontroll have relation to column "product" to product table i want to have related productdiscountcontroll data like discount and discount_code_precent in peyment serilizer at get request. i tried def get_product_discount(self, obj): return obj.product.product_discount.discount but sercer say : Field name `product_discount` is not valid for model `Peyment`. i also used product_discount = ProductDiscountControllSerializer(many=True,read_only=True) but product_discount not availibe in resault my view is like this class PeymentAPIView(APIView, mixins.DestroyModelMixin): permission_classes = [IsSafeGuard] def get(self, request): pay = Peyment.objects.filter( email=request.user.email, status=0, ) serializer = PeymentSerializer(instance=pay, many=True) return Response(serializer.data) this is related serilizer for get request: class PeymentSerializer(ModelSerializer): producttitle = serializers.SerializerMethodField() def get_producttitle(self, obj): return obj.product.title productprice = serializers.SerializerMethodField() def get_productprice(self, obj): return obj.product.price def get_discount(self, obj): return obj.product_discount.discount #product_discount = ProductDiscountControllSerializer(many=True,read_only=True) class Meta: model = Peyment fields = [ 'product', 'id', 'producttitle', 'productprice', 'discount', 'status', 'user', 'email', 'transfer_id', 'created_date', 'updated_date', ] read_only_fields = ['email', 'user', 'producttitle', 'productprice'] this is product model: class Product(models.Model): product_id = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) title = models.CharField(max_length=200) video_length = models.CharField(max_length=20, null=True, blank=True) mini_description = models.CharField(max_length=1000, null=True, blank=True) full_description = models.TextField(null=True, blank=True) you_need = models.CharField(max_length=1000, null=True) you_learn = models.CharField(max_length=2000, null=True) price = models.CharField(max_length=50, null=True, blank=True) video_level = … -
Docker + Heroku + Daphne, app deploys, but breaks with little information
I receive no errors other than a code=H10 from Heroku. I can even shell into my docker container within the Heroku registry, look around the environment, run python manage.py migrate for my Django app, it'll migrate successfully, the dyno is scaled to 1, everything seems like it should work. The logs only show this: 2018-03-27T11:14:51.438883+00:00 heroku[web.1]: Starting process with command `/bin/sh -c daphne\ -b\ 0.0.0.0:\51008\ config.asgi:application` 2018-03-27T11:14:55.232101+00:00 heroku[web.1]: Process exited with status 0 2018-03-27T11:14:55.253406+00:00 heroku[web.1]: State changed from starting to crashed 2018-03-27T11:14:54.976190+00:00 app[web.1]: DEBUG 2018-03-27 20:14:54,975 base 6 139663828047616 Configuring Raven for host: https://sentry.io 2018-03-27T11:15:04.477322+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=paira.herokuapp.com request_id=57ed88da-dad1-463f-808f-3a04c129d17c fwd="124.56.195.112" dyno= connect= service= status=503 bytes= protocol=https 2018-03-27T11:15:05.178724+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=paira.herokuapp.com request_id=e8da3a18-9788-4642-af65-9f1621949cc9 fwd="124.56.195.112" dyno= connect= service= status=503 bytes= protocol=https 2018-03-27T11:15:35+00:00 app[heroku-redis]: source=REDIS sample#active-connections=1 sample#load-avg-1m=0 sample#load-avg-5m=0.005 sample#load-avg-15m=0 sample#read-iops=0 sample#write-iops=0 sample#memory-total=15664376kB sample#memory-free=14946172kB sample#memory-cached=369344kB sample#memory-redis=278200bytes sample#hit-rate=1 sample#evicted-keys=0 2018-03-27T11:17:07+00:00 app[heroku-redis]: source=REDIS sample#active-connections=1 sample#load-avg-1m=0 sample#load-avg-5m=0 sample#load-avg-15m=0 sample#read-iops=0 sample#write-iops=0 sample#memory-total=15664376kB sample#memory-free=14946368kB sample#memory-cached=369348kB sample#memory-redis=278200bytes sample#hit-rate=1 sample#evicted-keys=0 I'm not sure how helpful it is, but nothing else seems to indicate any problems. Where should I begin to debug? Here's the Dockerfile command starting the app: CMD daphne -b 0.0.0.0:$PORT config.asgi:application I'm using Daphne as my server, since I'm using … -
Django deploy to Production in Ubuntu 16.04
I'm fairly new to django , i have to deploy the project to production mode in ubuntu 16.04. I have installed wsgi with apache2 and included the system path to the django project and python site-packages. My sites-enabled/000-default.config is <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName myproject.com ServerAlias www.myproject.com Alias /static /var/www/html/TEST/myproject/static <Directory /var/www/html/TEST/myproject.com/static> Require all granted </Directory> <Directory /var/www/html/TEST/myproject.com/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite.com python-home=/var/www/html/TEST/newenv python-path=/var/www/html/TEST/myproject.com:/var/www/html/TEST/newenv/lib/python3.5/site-packages WSGIProcessGroup mysite.com WSGIScriptAlias / /var/www/html/TEST/mysite.com/mysite/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> and my wsgi file import os , sys sys.path.append('/var/www/html/TEST/myproject.com/') sys.path.append('/var/www/html/TEST/newenv/lib/python3.5/dist-packages/') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.com.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() when i run the link i am getting Internal Server Error(505) and i have checked the error in the error log ,it's showing me from django.core.wsgi import get_wsgi_application [wsgi:error] ImportError: No module named django.core.wsgi Can someone please help me with this ? i have googled and checked out all other options and solutions . Thanks in advance -
Unable to query an API using django forms
I'm trying to query an API using django form and running into difficulty querying the API from the form on the frontend. I have a python script with hard coded values that when ran in the terminal, will successfully query the API I'm using. Script import requests import urllib.request as urllib2 import json url = "https://trackapi.nutritionix.com/v2/search/instant?" body = { "query": "query", 'query': "apple", } headers = { 'x-app-id': "ff0ccea8", 'x-app-key': "605660a17994344157a78f518a111eda", 'x-remote-user-id': "7a43c5ba-50e7-44fb-b2b4-bbd1b7d22632", } response = requests.request("GET", url, params=body, headers=headers) print(response.json()['common']) At the moment I'm trying to pass the 'food' variable from the form to the end of the URL, and then query that API using the URL to return the food calories count from 'Nutritionix API.' The problem is that the food variable is going to the end of the URL in the browser but its not querying the API. I'm fairly sure I'm doing it wrong and should be using python request BODY, like in the example above where i hard-code apple into the query, because this returns what i want into my terminal. form.py class NutritionForm(forms.Form): food = forms.CharField(max_length=250) # nf_calories = forms.DecimalField() def search(self): result = {} food = self.cleaned_data['food'] endpoint = 'https://trackapi.nutritionix.com/v2/search?{item_id}' url = endpoint.format(item_id=food) …