Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot import name "ResolveInfo" Error attempting to run after installing Saleor python django CMS
Hi Am Attempting to install the latest version of Saleor Django based ecommerce CMS to a windows VM on AzUre. I followed the Saleor installation instruction steps based on the provided requirement.txt file and the Azure instructions to setup up a web app. I have completed the install twice and each time when I attempt to run Saleor I receive this error below. I have scanned the Internet and found this link : https://github.com/graphql-python/graphene/issues/546 Just wondering if :1) any one can explain the statement "had a folder called graphql in my path" I have no idea what this statement means since I am only a beginner orogrammer. [Replacing the file with "graphql-core>=2.0.dev" makes no difference] 2) any one can give me some diagnostic steps that I could go through to help me find the reason for the error. Any help appreciated. Chris Error message: Traceback (most recent call last): File "run_waitress_server.py", line 9, in application = get_wsgi_application() File "D:\home\python364x64\Lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "D:\home\python364x64\Lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\home\python364x64\Lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "D:\home\python364x64\Lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "E:\A_work\79\b\source_packages\python.3.6.4\tools\Lib\importlib__init__.py", line 126, in import_module File "", line 994, in … -
How to export a csv file in django
I am trying to export a csv file in djnago I want it such that each work sheet in file should have column names as per each entry in the Product Attribute table here is my models.py class ProductType(models.Model): name = models.CharField(max_length=128) product_attributes = models.ManyToManyField( 'ProductAttribute', related_name='product_types', blank=False) is_shipping_required = models.BooleanField(default=False) and my view function is def export(request): import xlsxwriter product_resources = ProductType.objects.values() if(request.GET): product_resource = ProductResource() dataset = product_resource.export() response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="product.xls"' return response and my ProductResource function is from import_export import resources from ami.product.models import ( AttributeChoiceValue, Product, ProductAttribute, ProductImage, ProductType) class ProductResource(resources.ModelResource): class Meta: model = ProductType currently I am getting output on a single work sheet with all attributes of producttype occupying a single cell but I want it such that each product attribute should occupy a new column -
Doing a MySQL REPLACE INTO in Django?
Suppose i have more than 180k user object, and some of them are already present in table, and the table has email Id unique index, So i want to update the existing records and insert the new records, In MySQl i came to know that there is option called REPLACE INTO, Is there any way to run the REPLACE INTO in django ORM object, and also i want run the query as bulk like below Entry.objects.**bulk_replace**([ ... Entry(headline='This is a test'), ... Entry(headline='This is only a test'), ... ]) -
How do I get a random order using Django with Haystack and ElastSearch backend?
Looks like the question mark is not supported in the ElasticSearch backend '?'. What I can do: qs = SearchQuerySet().filter(...).order_by('any field here') What I'd like to do: qs = SearchQuerySet().filter(...).order_by('?') -
Django translation not working for DE language
I created translations .po and .mo files for language de and en. When I lunch my code with German settings, with print(translation.get_language()) >> de it print right language, but translations doesn't work (I get english translation) I have: # Translations # Provide a lists of languages which your site supports. LANGUAGES = ( ('en', _('English')), ('de', _('German')), ) # Set the default language for your site. LANGUAGE_CODE = 'de' # Tell Django where the project's translation files should be. LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) In HTML {% load i18n %} <label class="bmd-label-static" for="date">{% trans 'Date' %}</label> in django.po msgid "Date" msgstr "Datum" My files are arrange like: locale | -> de | -> LC_MESSAGES | -> django.mo -> django.po -> en | -> LC_MESSAGES | -> django.mo -> django.po -
How do I change the exisitng data into a user model in django?
I am building a web app for students record. 100s of students infomartion are already uploaded in database and Student's model have: name, stdID_no and address. Here stdID_no is unique and I want to give login access to every user so that they can login and maintain their profile/information. Here I want to use stdID_no as username and generate password manually if any user ask for their login. How can i achieve that ? I tried searching but could not find anything useful. Note : Students' record are already in database. -
Subquery: negated outerref does not work
I have three models Project, Profile and Company: (using django 2.0 and python 3.5) class Company: pass class Profile: company = models.ForeignKey(Company, on_delete=models.CASCADE) class Project: companies = models.ManyToManyRelatedField(Company, related_name="projects") profiles = models.ManyToManyRelatedField(Profile, related_name="projects") There is an implicit restriction that when a profile is assigned to a project, its company must be assigned to that project as well. However, that restriction is not always met, so i want to find out which objects do not meet it. If I try to find all projects that have such an invalid assignment using the Exists() Subquery: qs = Project.objects.annotate(x=Exists( Profile.objects.filter( # find all profiles assigned to project projects=OuterRef('pk') ).exclude( # exclude profiles where company is assigned to project company__projects=OuterRef('pk') ) )).filter(x=True) Trying to evaluate qs results in: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. If I replace exclude with filter, it works again; similarly, using Q() expressions the queryset only fails when company__projects__in=OuterRef('pk') is negated. Is this a restriction with OuterRef? The documentation does not mention anything like that, nor was I able to find a bug report. EDIT: I did find a workaround using a second Subquery: qs = Project.objects.annotate(x=Exists( Profile.objects.filter( … -
ReverseMatch worked for jsonResponse but not for render
I have a new page with: def person(request, galid): bunch of stuff context = { blah blah } # return JsonResponse(context) return render(request, 'pops/person.html', context) with urls.py urlpatterns = [ path('', views.index, name='index'), path('<slug:galid>' , views.person, name="person") ] while jsonResponse worked perfectly fine, returning the context object at the desired galid string(a hex string). when I used render it throws: NoReverseMatch at /pops/7B909B19F98049948523899280807F9F Reverse for 'person' with arguments '('',)' not found. If there really is no reverse match, how does jsonResponse work fine? What is happening/ going wrong here? Thanks! -
How to show incremented Django model field value in template correctly?
I have a post model and try to achieve properly views counter but this method not work correctly in template when I try to display views counter in a template. class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) title = models.CharField(max_length=160) slug = models.SlugField(null=True, blank=True, max_length=160) content = models.TextField() created = models.DateTimeField(default=datetime.datetime.now, blank=True) updated = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='news/photos/', default='', blank=True) views = models.PositiveIntegerField(default=0) class Meta: verbose_name = 'Post' verbose_name_plural = 'News' ordering = ['id'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(Post, self).save(*args, **kwargs) def count_views(self): self.views = F('views') + 1 self.save() class PostDetail(DetailView): model = Post template_name = 'news/detail.html' def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) self.object.count_views() context['latest_news'] = Post.objects.all().order_by('-created')[0:10] return context <span><i class="icon-eye icons"></i> {{ post.views }}</span> There may be another method to solve this issue, more correct. Can i solve this with .update queryset? -
django with celery: how to set up periodic tasks with admin interface
I have a problem wit setting up periodic tasks with celery. I got the scheduler running by: celery -A myproject beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler It seems as if the scheduler is up and running my task: In the admin interface, I can see/edit the task: But it does nothing. IMHO, the file myproject.backend.tasks.importnewvideo.py should be executed. But it is not. In the celery manual, I could not find any further information how to set up a task with the admin interface. Any ideas? Thanks in advance. -
Django custom model
from django.db import models from django.contrib.auth.models import User this is my models.py # Create your models here. class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) #first_name = models.CharField(max_length=30) #last_name = models.CharField(max_length=40) #username = models.CharField(max_length=30) buisness_name= models.CharField(max_length=30,blank=True) forms.py from django import forms from first_app.models import Person from django.contrib.auth.models import User class LoginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','password') class PersonForm(forms.ModelForm): class Meta(): model = Person fields = ('buisness_name',) i want to create a custom model with field password,username and when i login it should check the username and password from this field,datas are entered manually in the fields.how should i give login authentication -
unable to install several django and python packages and left with the given error [WinError 3]
[WinError 3] The system cannot find the path specified: 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\PlatformSDK\lib' So far as per my research setup build tools are required for installation of some packages like django-rest-swagger pip install simplejson I also checked that Microsoft visual studio 14.0 is not present in program files where as other versions (i.e. 12.0 , 10.0 , 9.0) are present I also tried installing visual c++ redistribution 2015 as suggested in some queries but that also didn't help. if anybody can help me to install Microsoft visual studio 14.0 because i think its installation will solve my issue Microsoft visual studio 2015 is already installer in my system -
Complex Search in a through model for Many to many relationships in Django
We are using Django Rest Framework to expose API's to Add, edit and retrieve data about users and their skill (with levels) We have models for users, skills and the skillmatrix (through model where we need to add additional data about skill level of that user for a given skill.) class Freelancer(models.Model): user = models.UUIDField (primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=30) contactNumber = models.BigIntegerField (default=None,blank=True, null=True) emailAddress = models.EmailField (max_length=50, blank=False, null=True) bachelorsDegree = models.CharField(max_length=50) mastersDegree = models.CharField(max_length=50) userCertificates = models.TextField(max_length=200) IsActive = models.BooleanField (default=True) UserPassword = models.CharField (max_length=50) DeacivateDate = models.DateTimeField (blank=True, null=True) Address = models.TextField(max_length=200) Pincode = models.IntegerField() class Skill(models.Model): name = models.CharField(max_length=100) skilltype = models.CharField(max_length=100,null=True) userSkills = models.ManyToManyField(Freelancer,through='SkillMatrix') class SkillMatrix(models.Model): user = models.ForeignKey(Freelancer,on_delete=models.CASCADE) skill = models.ForeignKey(Skill,on_delete=models.CASCADE) level = models.CharField(max_length=100,null=True) Now my challenge is the following: I want to find the most efficient way to search for users with specific skills and return it in the order of most relevant to least relevant. There are around 10000 users and around 300 skills. So for example if the required skills are ["python", "html", "css", "postgres"] then I should be able to return a list of UserID's so that User1 >> Skills Python, html, css, postgres all advanced User2 >> … -
Froala not working properly in django
I tried to integrate froala in Django as shown in here It worked perfectly in forms but when the content rendered in DetailView it shows this. Is their any workaround. Image as rendered by DetailView -
Dynamic text embedding in django
I am building a CMS for images. Once the images are uploaded along with its attributes, I'm creating an Id for it and embedding the Id into the image using Pillow library. When I goto the file containing the images in the media, the images have the text. But when I display the images in my application, I don't see any text embedding on the image. Why is it so? My views.py is @login_required def uploadphoto(request): context = RequestContext(request) context_dict = {} if request.method == 'POST': form = ImagesForm(request.POST,request.FILES) if form.is_valid(): image = form.save(commit=False) cat = Category.objects.get(name=image.category) fab = Fabric.objects.get(name=image.fabric) manu = Manufacturer.objects.get(name=image.manufacturer) setcat = Group.objects.get(name=image.set_cat) string = cat.abbr + "-" + fab.abbr + "-" + manu.name_abbr + "-" + manu.loc_abbr + "-" + str(int(image.selling_price)) + "-" + setcat.abbr + "-" + str(image.set_cat_no) image.design_id = string image.save() time.sleep(5) image2 = Image.open('media/' + str(image.file)) draw = ImageDraw.Draw(image2) font = ImageFont.truetype('Roboto-Bold.ttf', size = 40) (x,y) = (0,0) d_id = string + "\npowered by ABC Technologies" color = 'rgb(0, 0, 0)' draw.text((x,y), d_id, fill=color, font=font) image2.save('media/' + str(image.file)) return HttpResponseRedirect('/abc/') else: print form.errors else: form = ImagesForm() context_dict = {'upload_image': form} return render_to_response('cms/upload-photo.html',context_dict, context) @login_required def viewall(request): context = RequestContext(request) images = Images.objects.all().order_by('-id') … -
Django: UserCreationForm not showing
I'm trying to create a user sign-up form. It largely works, except that the form does not show in the template. My base template renders, just not the form itself. I get no traceback errors, the page (aside from the "base.html" template) is blank i.e. white space, with not even a button. I'm trying to recreate the tutorial done here: https://wsvincent.com/django-user-authentication-tutorial-signup/ signup.html {% extends 'base.html' %} {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.p }} <button type="submit">Sign up</button> </form> {% endblock %} accounts/urls.py from django.urls import path from . import views app_name = 'accounts' urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), ] myproject/urls.py from django.contrib import admin from django.urls import include, path from django.views.generic import RedirectView from clincher import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('clincher/', include('clincher.urls'), name='clincher'), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls'), name='accounts'), path('', RedirectView.as_view(url='clincher/templates/')), ] views.py from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' -
Django how to show multiple times to user?
I am having a model car and booking . how to show multiole times of availaibility of a car and after selecting the time redirect to booking forms and choose that time on timefield of form . ? Just take me out from this problem -
How to Do pagination in Django REST API in APIView?
How to do pagination in Django REST API in APIView? I gone through following links: http://www.django-rest-framework.org/api-guide/pagination/#limitoffsetpagination https://docs.djangoproject.com/en/dev/topics/pagination/ Django Rest Framework 3.1 breaks pagination.PaginationSerializer My View.Py file as below: from django.shortcuts import render # Create your views here. import json from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import TalentSearchInput, EmployerInput, SearchFilter#, TalentScoring from .serializers import TalentSearchSerializer, EmployerSerializer, FilterSerializer,TalentScoringSerializer #from rest_framework.pagination import PageNumberPagination from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger #from django.shortcuts import render #from base_searchAPP.pagination import CustomPagination #from rest_framework.settings import api_settings #from base_searchAPP.mixin import MyPaginationMixin #Python Code Modules import pandas as pd import numpy as np import MySQLdb import MySQLdb.cursors import json import os from difflib import SequenceMatcher as SM from nltk.util import ngrams import codecs from collections import defaultdict # Talent Search Views @api_view(['GET', 'POST']) #@permission_classes([AllowAny,]) def TalentInputparameters_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': print('GET.call') #print(Snippet) TalentSearch = TalentSearchInput.objects.all() serializer = TalentSearchSerializer(TalentSearch, many=True) print(serializer) d = Response(serializer.data) return d elif request.method == 'POST': print('POST.call') # Input Data d = request.data print(d) #Input Python code Here # Load Json into python #d = json.loads(d) This is part of file I am using this method. I tried … -
Method Not Allowed(405 POST) in Django
This is my index.html: <form action="{% url 'request:my_shipment' %}" method="POST"> {% csrf_token %} <input type="submit" value="My shipment"/> </form> This is my urls.py: app_name = 'request' urlpatterns = [ path('', request_views.IndexView.as_view(), name='index'), path('create_request/', request_views.RequestView.as_view(), name="request"), path('request/<int:pk>', request_views.UpdateReceiveView.as_view(), name='receive'), path('my_shipment/', request_views.ListMyShipment.as_view(), name='my_shipment') ] And this is a respond when I click to My shipmentbutton: Method Not Allowed (POST): /my_shipment/ -
Issue running React App on Django server with webpack
I am building a web-application using Django as the backend and want to implement a ReactJS framework frontend. Each application that I have as of now runs properly, independently of one another. I have also implemented webpack and it appears to configure properly, as it will run my ReactJS application on the localhost. Being new to webpack (and web-development in general) I am unsure how to get React to run on the Django local server (127.0.0.1:8000). I understand from the many forums I've read through that the javascript files need to be bundled and then read into the django app. Below are the relevant files: package.json { "name": "package.json", "version": "1.0.0", "description": "This is the private repository for the USA Baseball analytics team.", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "SET NODE_ENV=development babel src -d lib", "build-prod": "SET NODE_ENV=development babel src -d lib", "start": "webpack-dev-server" }, "repository": { "type": "git", "url": "git+https://github.com/USAB-Analytics/BaldEagle.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/USAB-Analytics/BaldEagle/issues" }, "homepage": "https://github.com/USAB-Analytics/BaldEagle#readme", "dependencies": { "react": "^16.2.0", "express": "^4.16.3", "react-dom": "^16.4.1", "react-sortable-hoc": "^0.8.3", "yarn": "^1.7.0", "react-prop-types": "^0.4.0", "semantic-ui-react": "^0.77.1", "react-router-dom": "^4.2.2" }, "devDependencies": { "babel": "^6.23.0", "babel-core": "^6.26.3", "babel-loader": "^7.1.4", "babel-preset-env": "^1.6.1", … -
Get key of IntegrityError in django bulk_create
I am trying to do a Model.objects.bulk_create(bulk_objects) in django, I am expecting IntegrityError's at times but I would like get the objects details that has caused the exception. try: # bulk_objects contains ~70k items Auction.objects.bulk_create(bulk_objects) except IntegrityError as e: print(str(e.__cause__)) this throws the exception insert or update on table "auction_table" violates foreign key constraint"my_constraint" DETAIL: Key (item_id)=(123865) is not present in table "item_table". This is fine and I expect this, I am wanting to get the item_id that has caused the exception, in this case the item_id of 123865. Is there a way of doing this without doing some regex on the string or iterating over the bulk_objects? -
Unable to Install mysqlclient on dreamhost server
I'm trying to get a mysql database set up on my dreamhost shared server but it seems I can't proceed without mysqlclient. When I try pip install mysqlclient however i get x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,12,'final',0) -D__version__=1.3.12 -I/usr/include/mysql -I/usr/include/python3.4m -I/home/eptaba/aeromembers.com/AeroMembers_env/include/python3.4m -c _mysql.c -o build/temp.linux-x86_64-3.4/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g -DNDEBUG _mysql.c:32:20: fatal error: Python.h: No such file or directory #include "Python.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 I've seen in other answers that these types of problems can be solved with apt-get install python3.4-dev But being on dreamhost's shared server product i'm not able to execute that command. Is there anything else I can do to either get mysqlclient or set up my mysql without it? -
How to Integrate MLab and Django?
Anybody who have used MLab for Mongo Database to their Django site? How can we integrate it? Can I directly use their URI? Is it mandatory to use Mongo shell? -
How to save ModelChoiceField of ForeignKey with empty_lable? - Django
I want to save the value of SelfTaught('自学'as attached picture), but the it reminded to select an item in the list, I have partial code of models and forms as below: class Course(models.Model): teacher = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="+" ) teacher = forms.ModelChoiceField(queryset=User.objects.filter(is_teacher=True), empty_label='SeltTaught',label='Teacher' ) -
IntegrityError: UNIQUE constraint failed: user_userprofile.user_id
I define an extra UserProfile to extend User's attributes as class UserProfile(models.Model): SEX = ( (1, 'male'), (0, 'woman'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.IntegerField(choices=SEX, default=1) location = models.CharField(max_length=30) about_me = models.TextField() When I append UserProfile to existed User in Django shell In[19]: for u in User.objects.all(): ...: profile = UserProfile(user=u) ...: profile.save() It report error: IntegrityError: UNIQUE constraint failed: user_userprofile.user_id I checked the answer Django: Integrity error UNIQUE constraint failed: user_profile.user_id - Stack Overflow, but have no ideas to solve my problem.