Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Fix File Download From Django App Failure
In my django application, the program creates a document and saves it to the file path defined in settings.py MEDIA_URL. If a file exists, the user should able to click on a link in the template and the file should download. When I do this, I get a .docx download, but it reads "Failed - No File". When I look in the folder defined by the file path in settings.py, I can see that the file is there. Any ideas what I may be doing wrong? I feel this should be working since I can see the .docx is being generated correctly. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... MEDIA_ROOT = os.path.join(BASE_DIR, 'web_unit') MEDIA_URL = '/web_unit/' views.py creating the .docx file and saving it def docjawn(request): reference = request.POST.get('Reference_IDs') manifest = Manifests.objects.all().filter(reference__reference=reference) order = Orders.objects.get(reference=reference) doc = DocxTemplate("template.docx") totalCNF = 0 totalFOB = 0 for item in manifest: totalCNF += item.cases * item.CNF totalFOB += item.cases * item.FOB context = { 'ultimate_consignee' : order.ultimate_consignee, 'reference' : order.reference, 'ship_to' : order.ship_to, 'terms' : order.terms, 'date' : "12", 'ship_date' : "7/4/19", 'vessel' : order.vessel, 'POE' : order.POE, 'ETA' : order.ETA, 'booking_no' : order.booking_no, 'manifest' : manifest, 'totalCNF' : totalCNF, 'totalFOB' : totalFOB, } doc.render(context) … -
Django - Create a drop-down list from database data
There is a model field, city, it is filled manually when creating the object. There is a field in the search form, city. In views.py it looks like this: views.py: if 'city' in request.GET: city = request.GET['city'] if city: queryset_list = queryset_list.filter(city__iexact=city) template.html: <div class="col-md-4 mb-3"> <label class="sr-only">City</label> <input type="text" name="city" class="form-control" placeholder="City"> </div> If you enter the name of the city, objects with that name will be selected. It works correctly, but it’s inconvenient. I want the city not to be entered, but selected from the list. This list should be automatically collected from the fields city. How can this be implemented? Thank! -
How to save an array of text in PostgreSQL using Django model.?
I am trying to save an array of text containing category types for a hotel system which looks something like this ['category-1', category-2', category-3, category-4] . I am using category_type = ArrayField(models.CharField(max_length=200),null=True) in my models.py The error i get is malformed array literal: "" LINE 1: ..., '{category-1, category-2}'::varchar(200)[], ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The error persist even after processing python list from ['category-1', category-2', category-3, category-4] to {category-1', category-2', category-3, category-4}. I have gone through postgresql documentation and have found very limited help, https://pganalyze.com/docs/log-insights/app-errors/U114 this is something similar posted to what i am facing problem with. Could someone please tell me what am i doing wrong? Any help would be appreciated. -
Django with Vue on sub page in history mode
I have been able to render a Vue app in a Django template when the django url is /. But in this case we want the Django url for the Vue page to be /dashboard. / is just a static Django page. The issue is that the Vue page is showing, but the routes do not work. When I disable history mode, the routes work fine, even on /dashboard/#. So in urls.py I added these lines at the end: re_path( "^dashboard.*$", TemplateView.as_view(template_name="dashboard.html"), name="app", ), in router.ts I have the following configuration: import Vue from 'vue'; import Router from 'vue-router'; import Home from './views/Home.vue'; Vue.use(Router); export default new Router({ mode: 'history', base: `${process.env.BASE_URL}`, routes: [ { path: '/', name: 'home', component: Home, }, { path: '/about', name: 'about', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ './views/About.vue'), }, ], }); I also tried to set base: '${process.env.BASE_URL}/dashboard' which didn't work either. And vue.config.js has the following setup: const BundleTracker = require('webpack-bundle-tracker'); module.exports = { baseUrl: 'http://0.0.0.0:8080', outputDir: './dist/', chainWebpack: (config) => { config.optimization .splitChunks(false); config .plugin('BundleTracker') .use(BundleTracker, [{ filename: … -
Set certain filter field
I have one innormal idea to get object through function and set to it certain field for filtering It will look as follows get_course(name='math') # or get_course(id=12) # and so on def get_course(**kwargs): for key, val in kwargs: return Course.objects.get(key=val) So is it possible to make this stuff? -
Object-level permissions in Django
I have a ListView as follows, enabling me to loop over two models (Market and ScenarioMarket) in a template: class MarketListView(LoginRequiredMixin, ListView): context_object_name = 'market_list' template_name = 'market_list.html' queryset = Market.objects.all() login_url = 'login' def get_context_data(self, **kwargs): context = super(MarketListView, self).get_context_data(**kwargs) context['scenariomarkets'] = ScenarioMarket.objects.all() context['markets'] = self.queryset return context But I want different users to see different sets of markets. For example, I want users from company X to only see markets pertaining to X, and same for company Y, Z, and so forth. Four possibilities so far, and their problems: I could hardcode this: If each user has a company feature (in addition to username, etc.), I could add a company feature to each market as well, and then use if tags in the template to ensure that the right users see the right markets. Problem: Ideally I'd want to do this through the Admin app: whenever a new market is created there, it would be specified what company can see it. I could try to use Django's default permissions, which of course would be integrated with Admin. Problem: Setting a view permission (e.g., here) would concern the entire model, not particular instances of it. From googling around, it … -
How to update user profil in django properly
i created a form to update a django profil, i use the default user model, when i submit the form and logout and i tried to login again, the new password is not working, but the old one is. this is my update view : def edit_profil_to_base(request): if not request.user.is_authenticated: return redirect('authentification') else: nom_profil_new = request.POST.get('nom_profil') nom_profil_old = request.user.username old_mdp = request.POST.get('old_mdp') # type: object new_mdp = request.POST.get('new_mdp') final_mdp = request.POST.get('final_mdp') mdp = request.user.set_password(new_mdp) if request.user.check_password(old_mdp) and new_mdp == final_mdp: User.objects.filter(username=nom_profil_old).update(username=nom_profil_new, password=mdp) logout(request) return redirect('authentification') the new_mdp and final_mdp are the new password and the confirmation of the password -
A function updating data and using the updated data again in one trial
I am working on a function that checks who submitted homework and calculate the penalty for those who didn't. Though it finely saves in db who did not submit homework, but a problem happens with the penalty. It is done in the same function (right after checking who handed in), but with old data. It does not get the updated data (+1 if not submitted). I think it is because the update and calculation are done all at once in one function, one trial. But I have no idea how to separate them or getting the updated data right. I made a function outside the original function that only calculates the penalty and applied in the original function, intending to separate two functions (checking submission and calculating penalty) but it resulted in the same. def group_update(request, group_id): group = get_object_or_404(Group, id=group_id) memberships = Membership.objects.filter(group=group) members = [x.person for x in memberships] Checking submission assignments = Assignment.objects.filter(done_checked=False, group=group, due_date__lte=datetime.now()) for assignment in assignments: submission = Done.objects.filter(assignment=assignment) submitters = [x.author for x in submission] assignment.done_checked = True assignment.save(update_fields=['done_checked']) for member in members: if member not in submitters: non_submit = memberships.get(person=member) non_submit.noshow_assign = non_submit.noshow_assign + 1 non_submit.save() Calculating penalty for membership in memberships: … -
I want to see the value when i press particular number button in django
I have a small Django calculator app. I want to display the value in the text box when any number button clicked My- HTML code <form action ="buttonClicked" method="POST"> {% csrf_token %} <div class="calculator"> <input type="text" class="calculator-screen" value="0" disabled name = "text-box"/> <div class="calculator-keys"> <button type="button" class="operator" value="+">+</button> <button type="button" class="operator" value="-">-</button> <button type="button" class="operator" value="*">&times;</button> <button type="button" class="operator" value="/">&divide;</button> <button type="button" value="7">7</button> <button type="button" value="8">8</button> <button type="button" value="9">9</button> <button type="button" value="4">4</button> <button type="button" value="5">5</button> <button type="button" value="6">6</button> <button type="button" value="1" name="b1">1</button> <button type="button" value="2">2</button> <button type="button" value="3">3</button> <button type="button" value="0">0</button> <button type="button" class="decimal" value=".">.</button> <button type="button" class="all-clear" value="all-clear">AC</button> <button type="button" class="equal-sign" value="=">=</button> </div> </div> </form> {% endblock %} My view.py from django.shortcuts import render from django.contrib import messages def calc(request): if request.method == 'POST': #here i want to take the button value and do some operation return render(request, 'Calculator.html') Calc if i press button 1 then it should display 1 in the text box... how can i do that? -
How to create custom user in django shell?
How can I create a custom user and set its password in django shell: I have this model: class CustomUser(AbstractUser): username = None email = EmailField(verbose_name='email address', max_length=255, unique=True, ) first_name = CharField(verbose_name='First Name', max_length=30, null=True, ) middle_name = CharField(verbose_name='Middle Name', max_length=30, null=True, blank=True, ) last_name = CharField(verbose_name='Last Name', max_length=30, null=True, ) phone_number = CharField(verbose_name='Phone Number', max_length=30, null=True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email and I have this: from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of username. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) I can create a superuser by this: python manage.py createsuperuser But I can not do … -
IntegrityError Primary Key Invalid (python-django)
I'm looking at a sentdex lesson and I have this error and why ? I saw a similar question here but couldn't get the answer from django.db import models from datetime import datetime # Create your models here. class tutorialcategory(models.Model): tutorial_category=models.CharField(max_length=200) category_summary=models.CharField(max_length=200) category_slug=models.CharField(max_length=200, default=1) class Meta: verbose_name_plural="Categories" def __str__(self): return self.tutorial_category class tutorialseries(models.Model): tutorial_series=models.CharField(max_length=200) tutorial_category=models.ForeignKey(tutorialcategory, verbose_name="Category", on_delete=models.SET_DEFAULT) series_summary=models.CharField(max_length=200) class Meta: verbose_name_plural="series" def __str__(self): return self.tutorial_series class tutorial(models.Model): tutorial_title=models.CharField(max_length=200) tutorial_content=models.TextField() tutorial_published=models.DateTimeField("date published", default=datetime.now()) tutorial_series=models.ForeignKey(tutorialseries, default=1, verbose_name="series", on_delete=models.SET_DEFAULT) tutorial_slug=models.CharField(max_length=200, default=1) def __str__(self): return self.tutorial_title Below is how the error looks like: django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value '1' that does not have a corresponding value in main_tutorialseries.id. -
django datepicker on datatable
I have to apply datepicker to my datatable to filter the data between two date range. I have applied my things and tried different codes but nothing worked out. My table contains date in the format( example- July 16,2019). I know it can be done by javascript but I am unable to do so. Please help. <table id="table table-mutasi" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true" data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true"> <thead> <tr> <th data-field="state" data-checkbox="true"></th> <th data-field="id">center</th> <th data-field="cabin" >cabin</th> <th data-field="boooked_date">Booked date</th> <th data-field="release_date">Release Date</th> <th data-field="client">Client</th> <th data-field="booked_by">Booked by</th> {% if not request.user.is_superuser %} <th>Actions</th> {% endif %} </tr> </thead> <tbody> {% for object in object_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ object.premises}}</td> <td>{{ object.cabin }}</td> <td>{{ object.booked_date }}</td> <td>{{ object.release_date }}</td> <td>{{ object.client }}</td> <td>{{ object.booked_by }}</td> {% if not request.user.is_superuser %} <td> <a href="{% url 'manager:BookingUpdate' pk=object.id %}" style="color:black; margin-left:8px"><span class="glyphicon glyphicon-edit"></span></a> <input type="hidden" id="cendel" value="{{object.id }}"> <a href="#" style="color:black ;margin_left:8px;" id="delete" ><span class="glyphicon glyphicon-trash"></span></a> </td> {% endif %} </tr> {% endfor %} </tbody> </table> -
I don't know how to display formset in django
I don't know how to display formset individually. I understand how to display all at once. But I tried some model field names, but it didn't work. #views class UserEdit(generic.UpdateView): model = User form_class = forms.UserUpdateForm template_name = 'accounts/accounts_edit.html' success_url = reverse_lazy('accounts:edit') def get_object(self): return get_object_or_404(User, pk=self.request.user.user_id) #forms class ProfileUpdateForm(forms.ModelForm): class Meta: model = profile fields = ('first_name','last_name','birthday') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' ProfileFormSet = inlineformset_factory(User,profile,form=ProfileUpdateForm,extra=0) class UserUpdateForm(mixins.ModelFormWithFormSetMixin,forms.ModelForm): #Userモデルにprofileモデルを入れる formset_class = ProfileFormSet class Meta: model = User fields = ('username','email',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' #template <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.username.label_tag }} {{ form.username }} {{ form.email.label_tag }} {{ form.email }} {{ form.formset }} <button type="submit">Submit</button> </form> I want to specify and display instead of the method of displaying at once with formset. -
xml ParseError using mws with Django Python console but no error using same code/module-versions in system Python Console
I am using python-mws for Amazon. I have mws-4.4.1. It parses the xml documents from the mws api using the Python xml library. I can use the module successfully in a normal python script, but when I make a request through Django python manage.py shell I get the following traceback: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 250, in make_request parsed_response = DictWrapper(data, rootkey) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 108, in __init__ self._mydict = utils.XML2Dict().fromstring(remove_namespace(xml)) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 100, in remove_namespace return regex.sub('', xml) TypeError: cannot use a string pattern on a bytes-like object During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 1624, in feed self.parser.Parse(data, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 0 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/amazon/amazon_mws.py", line 59, in parse_inventory_report report = self.reports.get_report(report_id=report_id) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 422, in get_report return self.make_request(data) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 253, in make_request parsed_response = DictWrapper(response.text, rootkey) File "/app/.heroku/python/lib/python3.6/site-packages/mws/mws.py", line 108, in __init__ self._mydict = utils.XML2Dict().fromstring(remove_namespace(xml)) File "/app/.heroku/python/lib/python3.6/site-packages/mws/utils.py", line 106, in fromstring text = ET.fromstring(str_) File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 1314, in XML parser.feed(text) File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 1626, in feed … -
How can I do search for multiple things (full-text, geolocation etc) in DRF?
I have a model in Django-REST that has name, description etc, plus geolocation using GeoDjango. Now, I would like to have a complicated search, with full-text search in the name and description fields plus geolocation search(the user gives a location point and a maximum distance). I want these to work independently and together if need be. I've seen how to do full-text search (here:https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/search/) and how to search based on distance(here: https://docs.djangoproject.com/en/2.2/ref/contrib/gis/db-api/). My code so far (the models, doesn't matter, just think of the name, description and location point): class SearchAuctions(APIView): permission_classes = [AllowAny] def get(self, request, format=None): """ Return auctions after filtering. """ items = AuctionItem.objects if 'textToSearch' in request.data.keys(): textToSearch = request.data['textToSearch'] items = AuctionItem.objects.annotate( search=SearchVector('name', 'description'), ).filter(search=textToSearch) itemSerializer = AuctionItemSerializer(items, many=True) return Response(itemSerializer.data) Not sure how I can create a chain link between filters. I've though of making multiple requests and finding the common elements, but that is way too slow I guess. -
django templates add html attibute from variable
How do I add dynamic html attribute in django template? For example we have n=5 And have this html markup in index.html: <select tabindex={{n}}> But it doesn't work, generated html looks like this: <select tabindex="{{n}}"> And I need this: <select tabindex="5"> What do I do? -
I am running an app (Django framework). I get error
When I run app in Django - I get the following error (See below). The app's name is runtrack. The error is generated when I click an "ADD" button in the app. I thought it was to do with the Allowed Hosts not being defined. I added ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] in settings.py but no luck Actual Result in IDE: [18/Aug/2019 15:54:01] "GET /api/runtrack/?search= HTTP/1.1" 200 2 [18/Aug/2019 15:54:01] "GET /runtrack HTTP/1.1" 200 13174 [18/Aug/2019 15:54:01] "GET /api/runtrack/?search= HTTP/1.1" 200 2 [18/Aug/2019 15:54:02] "GET /runtrack HTTP/1.1" 200 13174 [18/Aug/2019 15:54:02] "GET /api/runtrack/?search= HTTP/1.1" 200 2 [18/Aug/2019 15:54:02] "GET /api/runtrack/?search= HTTP/1.1" 200 2 Bad Request: /api/runtrack/ [18/Aug/2019 15:54:06] "POST /api/runtrack/ HTTP/1.1" 400 92 -
Unknown issue when deploying a Django app to Heroku with anaconda
I use Django 1.11.20 and Python 2.7. My app is deployed with Heroku. As I need numpy/scipy and Heroku has a slug size limited to 500Mb, I am using anaconda through the three following Heroku packages : https://github.com/kennethreitz/conda-buildpack https://github.com/cyberdelia/heroku-geo-buildpack.git heroku/python The site was working perfectly since 1 year. I had not updated it since a few months. I brought minor changes to the site recently and I got the following error when deploying it to Heroku. I don't understand what is the issue exactly. Any clue ? -----> Deleting 0 files matching .slugignore patterns. -----> Python/Conda app detected added pinned file in /app/.heroku/miniconda/conda-meta/pinned Collecting package metadata: ...working... done Solving environment: ...working... done ## Package Plan ## environment location: /app/.heroku/miniconda added / updated specs: - nomkl The following packages will be downloaded: package | build ---------------------------|----------------- nomkl-3.0 | 0 48 KB ------------------------------------------------------------ Total: 48 KB The following packages will be UPDATED: nomkl 1.0-0 --> 3.0-0 Proceed ([y]/n)? Downloading and Extracting Packages Preparing transaction: ...working... done Verifying transaction: ...working... done Executing transaction: ...working... done -----> Installing dependencies using Conda Collecting package metadata: ...working... done Solving environment: ...working... The environment is inconsistent, please check the package plan carefully The following packages are causing … -
Django urls can't find templates with HTML file
I'm trying to create views in my Django ToDo App. But there is a TemplateDoesNotExist error. I was looking for solve but it still not working. This is my urls.py in main folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('todoapp_api.urls')), ] Then my app folder is "todoapp_api" And there i have urls.py from django.urls import path from . import views urlpatterns = [ path('', views.app, name='app'), ] My views.py looks like this from django.shortcuts import render from django.http import HttpResponse def app(request): return render(request, 'todoapp_api/app.html') -
Manually pass additional data during partial model update
I have to pass user to different fields depending on the requested data. In case the instance was "rejected" I need to pass rejected = True and the user as rejected_by = request.user how to change those values manually since I use partial_update. I have tried to do this by passing additional data to serializer_class but this seems to not work. class AcceptRejectCoreWord(generics.UpdateAPIView): queryset = WordCoreModel.objects.all() serializer_class = AcceptRejectCoreWordSerializer lookup_field = 'id' def patch(self, request, *args, **kwargs): user = get_user_model().objects.get(email=request.user) if not user.groups.filter(name="Moderator").exists(): return Response({ 'error': 'Only moderators have permissions to view this endpoint'}, status=status.HTTP_403_BAD_REQUEST) if request.data['rejected']: reject_reason = request.data['rejection_reason'] if not reject_reason: return Response({ 'error': 'Rejection reason is required'}, status=status.HTTP_400_BAD_REQUEST) self.serializer_class(accepted=False, accepted_dy=None, rejected=True, rejected_by=user, modified_by=user, publishing_status='rejected') if request.data['accepted']: self.serializer_class(rejected=False, rejected_by=None, accepted=True, accepted_dy=user, modified_by=user, publishing_status='published') return self.partial_update(request, *args, **kwargs) My serializer class contains this fields but I don't know how to update them in case of using partial_update method. class AcceptRejectCoreWordSerializer(serializers.ModelSerializer): part_of_speech_type = CoreWordSpeechPartDescriptionSerializer( many=True, required=False) class Meta: model = WordCoreModel fields = ['id', 'word_core', 'word_russian_typed', 'word_english_typed', 'part_of_speech_type', 'uncensored_word', 'modified_by', 'publishing_status', 'accepted', 'accepted_by', 'rejected', 'rejected_by', 'rejection_reason'] extra_kwargs = {'id': {'read_only': False}} def update(self, instance, validated_data): word_descriptions = validated_data.pop('part_of_speech_type') core_word = WordCoreModel.objects.get(id=validated_data['id']) for word_description in word_descriptions: CoreWordSpeechPartDescription.objects.update( word=core_word, **word_description) return core_word … -
ValueError not enough values to unpack (expected 4, got 2) - Django
I have this view: def getData(): response = requests.get("https://path.to/api/") data = response.json() random_data = [MyModel(name=name, street=street, email=email, phone=phone) \ for name, street, email, phone, in data.items()] MyModel.objects.bulk_create(random_data) @require_http_methods(['GET', 'POST']) def index(request): datas = getData() return render(request, 'index.html') When I access the specified url for index method, it throws me this: Traceback (most recent call last): File "/home/user/.virtualenvs/myproj/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/.virtualenvs/myproj/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/.virtualenvs/myproj/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.virtualenvs/myproj/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/home/user/django_projects/myproj/myproj/user/views.py", line 29, in index datas = getData() File "/home/user/django_projects/myproj/myproj/user/views.py", line 18, in getData for name, street, email, phone, in data.items()] File "/home/user/django_projects/myproj/myproj/user/views.py", line 18, in <listcomp> for name, street, email, phone, in data.items()] ValueError: not enough values to unpack (expected 4, got 2) [18/Aug/2019 15:18:05] "GET /api/index/ HTTP/1.1" 500 85435 Method Not Allowed (HEAD): /api/index/ From this error, I think that the resulting json response from the api might be the problem, since some of these items are kind of nested into the resulting json Here's an example response: random Any ideas? -
You may need to add u'127.0.0.1' to ALLOWED_HOSTS
I am getting the following error when I am trying to start my Django server python manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). August 18, 2019 - 20:47:09 Django version 1.11, using settings 'config.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. [18/Aug/2019 20:47:09] "GET /view/stockprice/ HTTP/1.1" 400 16918 [18/Aug/2019 20:47:09] "GET /view/stockprice/ HTTP/1.1" 400 16918 [18/Aug/2019 20:47:09] "GET /view/stockprice/ HTTP/1.1" 400 16918 Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. I have already given 127.0.0.1 in the list of ALLOWED_HOST. SECRET_KEY=BeatTheStreet DEBUG=True ALLOWED_HOSTS=['127.0.0.1', '0.0.0.0'] EVENT_STARTED=True EVENT_ENDED= # Production database details DB_NAME= DB_USER= DB_PASSWORD= DB_HOST= DB_PORT= Pointers to fix this will really help. I am running server with 0.0.0.0:8000 because of issue I had in Django … -
How to change the default Django page to my own one?
I'm learning Django,and I followed a guidebook.I want to change the default Django page into my own one.It has took me 2 hours to solve this,and nothing worked. The project is called learning_log,and the app is called learning_logs. Here's what I'm trying to do: 1.add module learning_logs.urls: """ Definition of urls for learning_log. """ from datetime import datetime from django.urls import path from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView from app import forms, views #added from django.conf.urls import include, url import learning_logs.views from django.urls import path,re_path app_name='learning_logs' urlpatterns =[ path('', views.home, name='home'), path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('login/', LoginView.as_view ( template_name='app/login.html', authentication_form=forms.BootstrapAuthenticationForm, extra_context= { 'title': 'Log in', 'year' : datetime.now().year, } ), name='login'), path('logout/', LogoutView.as_view(next_page='/'), name='logout'), path('admin/', admin.site.urls), #added re_path(r'',include('learning_logs.urls',namespace='learning_logs')) ] To include the module,I've tried: url(r'',include('learning_logs.urls',namespacec='learning_logs')) path('',include('learning_logs.urls',namespacec='learning_logs')) path('',include('learning_logs.urls')) path('',learning_logs.urls) path('',learning_logs.views) But none of them worked. 2.Create urls.py in learning_logs.here's the code: """define learning_logs's url mode""" from django.urls import path,re_path from . import views from django.conf.urls import include,url urlpatterns=[ #homepage: re_path(r'(?P^$)',views.index,name='index')] #path('',include('learning_logs.views.index'))] As you can see,I also tried many times. 3.Write views.py in learning_logs from django.shortcuts import render # Create your views here. def index(request): """homepage of learning logs""" return render(request,'learning_logs/index.html') 4.write HTML document in learning_logs/templates/learning_logs/index.html code … -
Django Tutorial and Sqlite command line
I am going through the Django tutorial at https://docs.djangoproject.com/en/2.2/intro/tutorial02/ It had said previously that if I use sqlite that I don't need to install anything. Now, it says, after I migrate, ," If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created. " Am I supposed to have a command line editor for sqlite already or do I need to go fetch something from the web? If the latter, what do I get? If the former, what is the command to start it up? -
Angular8: Call localhost Rest Api services
I developed my web application with Angular 8. The backend is a rest api that I developed with django rest framework and it's viewed just in the localhost. I tested it and it works fine. For example the service http://127.0.0.1:8000/api/devices gives a list of devices. It gives a good results if I test it with browser or curl command. I'm calling this service from my angular app. I executed the angular app with the command: ng serve --host 0.0.0.0 --port 4201 If I open the web application in the browser with http://127.0.0.1:4201/api/devices the service /api/devices is well called and I get the list of devices in my web page. but if I open the web application with my LAN IP address like that http://192.168.1.59:4201/api/devices, so I get HTTP 400 bad request error in my console. And the same error is shown in django server traces: "GET /api/devices/ HTTP/1.1" 400 26 After some searches in the internet I concluded that this error is frequently coming from angular app especially the proxy: my proxy config file proxy.config.json is: { "/api" : { "target": "http://localhost:8000", "secure": false } } I mad other searches and I found an answer to similar question Angular 6 …