Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csrf error while trying to delete an object with ajax
I have all the objects from my db rendered on my template by an ajax function. Near every object there's a button that should delete it from the db but since I'm working on Django it raise a csrf_token missing or incorrect error. I'm not using a form so I don't know how to include the csrf_token. var $orders = $('#orders') $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/MyApp/list-api/?format=json', success: function(orders) { $.each(orders, function(i, order){ $orders.append('<li>name: '+order.name+', drink: '+order.drink+'</li>') $orders.append("<button data-id=" +(order.pk)+" class='remove'>X</button>") }); }, error: function() { alert('errore caricamento ordini'); } }); $orders.delegate('.remove', 'click', function(){ $.ajax({ type: 'DELETE', url: 'http://127.0.0.1:8000/MyApp/list-api/' + $(this).attr('data-id') }); }); When I press a remove button a new request appears in the network panel of the browser, the response states :detail: "CSRF Failed: CSRF token missing or incorrect." The console gives a 403 forbidden error. Any help or hints are really appreciated. -
MultiValueDictKeyError with Post method python django
I have a form, where the user chose a color and this value returns to me, but whem the user choose the color, returns the MultiValueDictKeyError, and I dont know whye This is my views: def primeira_pergunta(request): trans = Tranfer() my_list = trans.shared[0] respostaum = ['amarelo', 'vermelho', 'roxo', 'cinza'] selecionada = 'amarelo' if request.method == 'POST': respostaum = request.POST['respostaum'] selecionada = request.POST['selecionada'] #if selecionada != 'Escolha uma': f = Cheiro.objects.get(pk=my_list) u = f.pk f.resposta1 = selecionada f.save() else: selecionada = 'Escolha uma' context = {'respostaum': respostaum, 'selecionada': selecionada} return render(request, 'cheiro/primeira_pergunta.html', context) this is my template: <form method="POST"> {% csrf_token %} <label for="respostaum">Selecione unidade</label> <select class="form-control" id="respostaum" name="respostaum"> {% for selecionada in respostaum %} <option value="{{ selecionada }}">{{ selecionada }}</option> {% endfor %} </select> <input type="submit"> </form> I try replace selecionada = request.POST['selecionada'] for this selecionada = request.POST.get('selecionada') and intead return error, returns null. -
why do not enter in form.is_valid ()
Why when I finished filling the fields in django do not enter in form.is_valid (): Although the results are presented correctly I hope to solve this problem When you fill the year field, the validor number does not work and the required fields do not work Thanking your cooperation class Listing(models.Model): #place = models.OneToOneField(Place,on_delete=models.CASCADE,primary_key=True) property_type = models.IntegerField(choices=PROPERTY_TYPE_CHOICES, default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING,blank=True, null=True) price = models.BigIntegerField() roomsTotal = models.PositiveSmallIntegerField(null=True) Bathrooms = models.PositiveSmallIntegerField(default=0) bedrooms = models.PositiveSmallIntegerField(default=0) Receptionrooms = models.PositiveSmallIntegerField(default=0) livingArea = models.DecimalField(max_digits=9, decimal_places=1) lotSize = models.DecimalField(max_digits=9, decimal_places=1) unitType = models.IntegerField(choices=UNIT_TYPE_CHOICES, default=1) yearBuilt = models.PositiveIntegerField(null=True,blank=True, validators=[ MinValueValidator(1900), (datetime.datetime.now().year)], help_text="استخدم الصيغة التالية: <YYYY>") remodelYear = models.PositiveIntegerField(null=True,blank=True, validators=[ MinValueValidator(1900), MaxValueValidator(datetime.datetime.now().year)], help_text="استخدم الصيغة التالية: <YYYY>") hoaPrice = models.BigIntegerField(default=None) groundTankSize = models.DecimalField(max_digits=6, decimal_places=1,default=None) garageSize = models.DecimalField(max_digits=6, decimal_places=1,default=None) homeDescription = models.TextField(blank=True) whatYouLoveDescription = models.TextField(default=None) Dishwasher = models.BooleanField(default=False, blank=True) Dryer = models.BooleanField(default=False, blank=True) Freezer = models.BooleanField(default=False, blank=True) GarbageDisposal = models.BooleanField(default=False, blank=True) Microwave = models.BooleanField(default=False, blank=True) Oven = models.BooleanField(default=False, blank=True) Refrigerator = models.BooleanField(default=False, blank=True) Washer = models.BooleanField(default=False, blank=True) RadioGroup_Rashan = models.CharField(max_length=5,null=True,blank=True) ACarpet = models.BooleanField(default=False, blank=True) AConcrete = models.BooleanField(default=False, blank=True) ATiles = models.BooleanField(default=False, blank=True) ALinoleum = models.BooleanField(default=False, blank=True) ADSoftwood = models.BooleanField(default=False, blank=True) ADOther = models.BooleanField(default=False, blank=True) BreakfastNook = models.BooleanField(default=False, blank=True) DiningRoom = models.BooleanField(default=False, blank=True) FamilyRoom = … -
Automatically find tag names in RichTextField and link them to existing tags
I've created pages in Wagtail using 'MyPage' class and assigned Tags to them using Taggit. These tags appear ok and I can display them without issue. When clicked they load related articles on a listing page. I'm trying to find a way to automatically convert (li) list items (with the same name as my tags) (in RichFieldText) to these tags, so I won't have to manually assign links to each list item. I'm still fairly new to Django and Wagtail and haven't found anything in the documentation so far. Would anyone have a solution? // Where the RichFieldText is mylist_page.html {{ page.my_list|richtext }} // Displays my list If you need more of my code just let me know. Any help will be much appreciated. From models.py class MyPageTag(TaggedItemBase): content_object = ParentalKey( 'MyListingPage', related_name='tagged_items', on_delete=models.CASCADE, ) class MyPage(RoutablePageMixin, Page): my_list = RichTextField(default= 'My list') From mylist_page.html <h2 style="margin-bottom: 15px">My List</h2> {{ page.my_list|richtext }} <br/> -
Is there a way for vscode to recognise python django modules installed/available inside a vagrant vm so that I stop getting errors?
Python Django modules are already installed/imported in a Vagrant dev VM, but VSCode won't see them. How do I make VSCode see the imported Django modules inside a Vagrant VM? I'm working with a team and a complex already built Python/Django backend. We use a Vagrant vm to host the dev environment on our own personal machines for testing/debugging. I use VSCode but it gives me errors on all the imports on Django modules. They're available/installed in the Vagrant vm and the dev environment runs with no issues. It's just that VSCode and pylint are unable to see the modules are installed in the VM and can't import them. It's making debugging and coding difficult. from django.xxxx.xxx.xx import xxxx from django.xxxx.xxx.xx import xxxx I expect it to see that the modules are installed, but instead I get import-error from pylint saying unable to import 'django.xxxxx'. -
Can I change Error Message on Django Auth Form Layout?
is there a way to change the placement of the error message of the package django.contrib.auth standard Authentication? See image below. On the bottom is a plain text where my objective is, basically I have my product logo on the top, it does not look appealing to the eye. Please help. I'm using the incldue(django.contrib.auth.urls) with templates. -
Installing mysqlclient in Ubuntu returns error number 1
I am trying to install mysqlclient in Ubuntu, but the command returns error number 1. I tried the command sudo apt install default-libmysqlclient-dev which worked. However pip install mysqlclient does not. Can you please help me? ERROR: Command errored out with exit status 1: command: /usr/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-VZPWLf/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-VZPWLf/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-2_cjSE/install-record.txt --single-version-externally-managed --compile cwd: /tmp/pip-install-VZPWLf/mysqlclient/ Complete output (31 lines): running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/MySQLdb x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-3hk45v/python2.7-2.7.15~rc1=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,4,4,'final',0) -D__version__=1.4.4 -I/usr/include/mysql -I/usr/include/python2.7 -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-2.7/MySQLdb/_mysql.o MySQLdb/_mysql.c:38:10: 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 ---------------------------------------- ERROR: … -
How to add Wagtail 'admin' menu to custom templates?
On templates that derive from the Wagtail Page model, there is a small Wagtail icon/menu in the lower right corner. This provides a quick way to edit the page and/or jump to the Wagtail Admin. However, this menu does not appear on custom view templates that are not derived from Wagtail Page model. How can I tell Wagtail to display the small menu on my frontend templates, so the pages have consistent navigation? -
I can't update the formset that I had done before
I use an inline form to update user information. And as you can see in the title, it became impossible to update. I'm trying to solve it, but it doesn't work. "Id This field is required. user A Profile with this User already exists. " I get an error. #view class UserEdit(generic.UpdateView): model = User form_class = forms.UserUpdateForm template_name = 'accounts/accounts_edit.html' success_url = reverse_lazy('person:myaccount') def get_object(self): return get_object_or_404(User, pk=self.request.user.user_id) #model class User(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() user_id = models.UUIDField(default=uuid_lib.uuid4, primary_key=True, editable=False) username = models.CharField(_('username'), unique=True, max_length=50,validators=[username_validator],error_messages={ 'unique': _("A user with that username already exists."), },) class profile(models.Model): image = models.ImageField(upload_to='profile/',default='profile/default.jpg') first_name = models.CharField(_('first name'), max_length=30, blank=True,null=True) last_name = models.CharField(_('last name'), max_length=150, blank=True,null=True) birthday = models.DateField(_('birthday',),null=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) #form class ProfileUpdateForm(BaseModelForm): class Meta: model = profile fields = ('first_name','last_name','birthday',) ProfileFormSet = inlineformset_factory(User,profile,form=ProfileUpdateForm,extra=0) class UserUpdateForm(mixins.ModelFormWithFormSetMixin,BaseModelForm): formset_class = ProfileFormSet class Meta: model = User fields = ('username','email',) -
How to cast a model into its parent?
I've made a class that, when you save a User, creates automatically the Person associated with the User like this: class Person(models.Model): user = models.OneToOneField(User, blank=False, null=False, on_delete=models.CASCADE) @receiver(post_save, sender=User) def my_post_save_user_handler(sender, instance, created, **kwargs): if created: # a User = physical -> create the associated person: Person.objects.create(user=instance, is_physical=True) Later I've made a Worker: class Worker(Person): job = models.CharField(unique=True, max_length=200) My problem is that I'd like to create a User associated with a Worker (= not a Person). When I do this: user = User.objects.create(username='test',) Worker.objects.create(user=user) I get this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_person_user_id_key" DETAIL: Key (user_id)=(2230) already exists. This is normal, because post_save is triggered when I create the User, and then a second time when I create the Worker. You might answer "just remove the auto generation of the Person" but I want for security reasons to always have a Person associated with a User. So is there a way to do something like: user = User.objects.create(username='test',) w = Worker(user.person) w.job = "the job" w.save() (I know that the previous code isn't working) or is there a way to "cast" a Person into a Worker? -
How to filter records that are within a given week
I have lesson records, each has a date scheduled, I want to create a filter from a date, returns the lessons of that week, if date none return lessons of current week I had some ideas and started writing something but I don't know how to finish class LessonWeeklyFilter(filters.FilterSet): date = filters.DateTimeFilter(field_name='start_date', method='filter_weekly') class Meta: model = models.Lesson fields = [ 'date', ] def filter_weekly(self, queryset, name, value): if value == None: today = datetime.now().date() dt = datetime.strptime(day, '%d/%b/%Y') start = dt - timedelta(days=dt.weekday()) end = start + timedelta(days=6) -
when i run python manage.py migrate getting ValueError: String input unrecognized as WKT EWKT, and HEXEWKB
when i made manage.py migrations i went sucessfully but when i run manage.py migrate i am new to geodjango pls help me Settings.py import os if os.name=='nt': import platform OSGEO4W=r"C:\OSGeo4w" if '64' in platform.architecture()[0]: OSGEO4W+="64" assert os.path.isdir(OSGEO4W), "Directory does not exist:"+OSGEO4W os.environ['OSGEO4W_ROOT']=OSGEO4W os.environ['GDAL_DATA']=OSGEO4W+r"\share\gdal" os.environ['PROJ_LIB']=OSGEO4W+r"\share\proj" os.environ['PATH']=OSGEO4W+r"\bin;"+os.environ['PATH'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '+2r35-w0_kqcr4ygbt474-!xx9q9izus$-+)g)%(-+=8d*^1pt' DEBUG = False ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'repoter', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'agricon.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'agricon.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'postgis_25_sample', 'USER': 'postgres', 'PASSWORD': 'Shanmukhavarma99@', 'HOST': 'localhost', 'PORT': '5432', } } GEOS_LIBRARY_PATH = r'C:\\OSGeo4W\\bin\\geos_c.dll' GDAL_LIBRARY_PATH = r'C:\OSGeo4W\\bin\\gdal204.dll' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation. UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' LEAFLET_CONFIG={ 'DEFAULT_ZOOM':1, 'MAX_ZOOM':30, 'MIN_ZOOM':10, 'SCALE':'both', } in models.py applied this to get County table python manage.py ogrinspect repoter/data/TM_WORLD_BORDERS-0.3.shp welcome --srid=4326 --multi --mapping from django.db import models from … -
How to fix NoReverseMatch
I am trying to update my menu items to add and edit menu items and I am having trouble moving to the next page. Although the menu Items updates or get added. views.py def addMenu(request, id): if request.method == 'POST': form = menuForm(request.POST) if form.is_valid(): form.save() return redirect('menu') else: form = menuForm() context = {'form': form} return render(request, 'addMenu.html', context) def editMenu(request, id): menu = get_object_or_404(Menu, pk=id) if request.method == 'POST': form = menuForm(request.POST, instance=menu) if form.is_valid(): form.save() return redirect('menu') else: form = menuForm(instance=menu) context = {'form': form} return render(request, 'editMenu.html', context) models.py class Restaurants(models.Model): restaurant_name = models.CharField(max_length=250, null=True, blank=True) def __str__(self): return self.restaurant_name class Menu(models.Model): restaurant_name = models.ForeignKey(Restaurants, on_delete=models.CASCADE, related_name='restaurants', null=True) name = models.CharField(max_length=250, blank=True, null=True) description = models.TextField(max_length=250) price = models.CharField(max_length=8) course = models.CharField(max_length=250) urls.py lpatterns = [ path('', views.showRestaurants, name='restaurants'), path('add/', views.addRestaurants, name='add'), path('edit/<id>', views.editRestaurants, name='edit'), path('<id>/delete/', views.deleteRestaurants, name='delete'), path('menu/<id>', views.showMenu, name='menu'), path('addmenu/<id>/', views.addMenu, name='addmenu'), path('menu/edit/<id>', views.editMenu, name='editmenu'), path('menu/<id>/delete', views.deleteMenu, name='deletemenu'), ] edit.html <form method='POST'> {% csrf_token %} {{ form.as_p }} <button type="submit">Update</button> </form> Each time I click on update it takes me to this error page Exception Type: NoReverseMatch Exception Value: Reverse for 'menu' with no arguments not found. 1 pattern(s) tried: ['menu\\/(?P<id>[^/]+)$'] Although the menu … -
Get data from table and save to database
I am trying to get the data from all rows and save it to database. how to get data from table. Thanks for help. This is my javascript file $(document).ready(function(){ $("input").click(function(){ $(this).next().show(); $(this).next().hide(); }); }); function add_row(){ var order_table = document.getElementById('order_list'); var food_name = document.getElementById('food0') var food_quantity = document.getElementById('quantity') // Insert new row var new_row = order_table.insertRow(0); var nee_cell0 = new_row.insertCell(0); var nee_cell1 = new_row.insertCell(1); var nee_cell2 = new_row.insertCell(2); var nee_cell3 = new_row.insertCell(3); var nee_cell4 = new_row.insertCell(4); nee_cell0.innerHTML = "{{ forloop.counter }}"; nee_cell1.innerHTML = food_name.value; nee_cell2.innerHTML = food_quantity.value; nee_cell3.innerHTML = 'safakat'; nee_cell4.innerHTML = 'safakat'; } This is my Html file. <body> <input list="food_item" name="food0" id="food0" placeholder="Search for food item"><br> <input type="number" name="unit_price"> <input type="number" name="quantity" id="quantity" placeholder="Enter The Quantity"><br> <button onclick="add_row()">ADD ROW</button> <table align="center" name = 'table'> <tr> <th>Sl. No.</th> <th>Item</th> <th name='abc'>Quantity</th> <th>Unit Price</th> <th>Ammount</th> </tr> </table> <table align="center" id="order_list"> </table> <datalist id="food_item"> {% for i in food %} <option value="{{i.name}}"> {% endfor %} </datalist> </body> I am trying request.POST.getlist('table_name'). but i am getting empty list -
Recursion when generating 404 errors
I use standard pagination from Django. The bottom line is that need to generate a 404 error when there are no posts on the page. That is, in the blog section there are only two pages of posts. It is necessary that when opening the page blog/3/ error 404 falls. Here is the code I got from the previous developer. view ITEMS_ON_PAGE = 10 class BlogViewMixin(ListView): queryset = Article.objects.all() context_object_name = 'articles' category = None def get_queryset(self, *args, **kwargs): queryset = super(BlogViewMixin, self).get_queryset(*args, **kwargs) if (self.kwargs.get('page')) == '1': raise Http404 page = self.kwargs.get('page', 1) category = self.kwargs.get('category', None) if category: category = get_object_or_404(Category, url=category) queryset = queryset.filter(category=category) self.category = category paginator = Paginator(queryset, ITEMS_ON_PAGE) try: queryset = paginator.page(page) except EmptyPage: queryset = [] #Here I tried to raise 404 return queryset def get_context_data(self, **kwargs): context = super(BlogViewMixin, self).get_context_data(**kwargs) context['current_page'] = self.kwargs.get('page', None) if context['current_page']: context['current_page'] = int(context['current_page']) context['current_category'] = self.category context['categories'] = Category.objects.exclude(is_green_button=True) context['marked_category'] = Category.objects.filter(is_green_button=True).first() context['SITE_URL'] = settings.SITE_URL context['pages'] = Page.objects.filter(show_on_main_menu=True, is_draft=False).order_by('order') return context class BlogView(BlogViewMixin): template_name = 'blog/index.html' Trying to throw an error in if not queryset: raise Http404 but goes into recursion. I rewrote the middleware for processing 404. Maybe the reason is in it. middleware import … -
How to allow only Admin (or some user) to edit the pages in Django?
In Django webpage(page can view by all), need to allow only certain people to edit the webpage and other people can just view the webpage. In Django-admin page's Users table,I've changed the certain users to "Can view" option and added certain users "Can edit" option. It is not working as per expected. Getting this error, POST "/admin/auth/user/4/change/ HTTP/1.1" 302 Actual result to be is POST "/admin/auth/user/4/change/ HTTP/1.1" 200 And that needs to be changed successfully and reflect -
How can i store NSData(World Map data) to postgresql database using django restframework?
I am trying to store NSData used by iOS i.e World Map data to database using postgresql and django restframework. Getting this error while creating data in postgresql:- ValueError: A string literal cannot contain NUL (0x00) characters django Django rest framework, python 3.x and postgresql. Tried with encoding and decoding of NSData but it does not work class MapArView(APIView): authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated, ) # def post(self, request, format=None): # user = Individual.objects.filter(user=request.user).first() # data = request.data # data['user'] = user.id # serializer = ReportedCommentSerializers(data=request.data) # if serializer.is_valid(): # serializer.save() # return Response(serializer.data) # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def post(self, request, format=None): user = request.user ind = Individual.objects.filter(user_id=user.id).first() image_data = request.data['image_data'] print(type(image_data)) print('iamge', image_data) #encodedBytes = base64.b64encode(image_data.encode("utf-8")) #encodedStr = str(encodedBytes, "utf-8") #print('image', image_data) my_str_as_bytes = str.encode(image_data) print(type(my_str_as_bytes)) latitude = request.data['latitude'] print(type(latitude)) longitude = request.data['longitude'] print(type(longitude)) location = request.data['location'] print(type(location)) location_description = request.data['location_description'] print(type(location_description)) data={} data['image_data'] = image_data #MapAr.objects.create(user_id=ind.id, image_data=my_str_as_bytes, latitude=latitude, longitude=longitude, location=location, location_description = location_description) #map_ar = MapAr.objects.latest('id') #serializer = MapArSerializers(map_ar,) #serializer.data['image_data'] = base64.b64decode(serializer.data['image_data']) #serializer.data['image_data'] = serializer.data['image_data'] #print(type(serializer.data['image_data'])) return Response({"success": True, "result": "created successfully.", "data": data}, status=status.HTTP_200_OK) #except: #return Response({'result': 'Something went wrong, please try again later' 'data':serializer.errors}, status=status.HTTP_400_BAD_REQUEST) ValueError: A string literal cannot contain NUL (0x00) characters … -
How to draw lines between selected options in two vertically placed list items in Django application?
We need to create an mapping tool application in Django. There are two categories, each containing approximately 5-10 items. The first category should be a single select option and second is the multiple select option. After choosing a element from first category, the user will select multiple options from the second category. We should be able to draw line between the selected option from first category to selected options in second category on selection. Please let us know how can we do this with Python and Django? Also let us know if we need to use any additional tool with Python? We tried to do this by using Python and Django. But we are facing problem in drawing that line on selection. -
set up permission ans authorization with graphql-jwt and rest-framework TokenAuthentication
I'm working on a Django project with Graphql API, at some point I needed to throttle mutations so I used graphene-django-extras library to achieve that. In order to take advantage of graphene-django-extras throttling feature, I use AuthenticatedGraphQLView instead of ExtraGraphQLView and I added djangorestframework library and add this to my ins stalled apps : INSTALLED_APPS = [ ... 'rest_framework.authtoken' ] I got a lot of failed tests (pytest), mainly 2 type of errors: status_code=403 You cannot access body after reading from request's data stream to solve status_code=401 error, I think i should add JSON Web Token Authentication here : REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } still doesn't work ------------------------------ Captured log call ------------------------------- log.py 228 ERROR Internal Server Error: /graphql/ Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 497, in dispatch … -
Render the images list inside a ModelChoiceField
I've developed a form, using Bootstrap4, for create a blog post. This form is linked at a model in which there are two ForeignKey: a FileField and an ImageField. If I use the default form rendering method({{ form.as_p }}) I can create a blog post but both the FileField and ImageField are rendered with the name of a single type of upload. I would like to see, instead of the name of the single image, the image. Then I've tried to use this: <div class="form-group mb-4"> <select class="form-control"> {% for img in geoform.image %} <option value="{{ img.pk }}"> <img class="img-fluid" src="{{ img.path }}" alt="{{ img.name }}"> </option> {% endfor %} </select> </div> but I see an empty list. This is the model: class GeoBlogFile(models.Model): name = models.CharField(max_length=70) path = models.FileField(upload_to='geoblog/documents/%Y/%m/%d') def __str__(self): return self.name class GeoBlogImage(models.Model): name = models.CharField(max_length=70) path = models.ImageField(upload_to='geoblog/images/%Y/%m/%d') def __str__(self): return self.name class GeoBlog(models.Model): title = models.CharField(max_length=70, unique=True) slug_title = models.SlugField(max_length=70, unique=True) contents = models.TextField(max_length=200) file = models.ForeignKey(GeoBlogFile, on_delete=models.CASCADE, related_name="related_file", blank=True, null=True) image = models.ForeignKey(GeoBlogImage, on_delete=models.CASCADE, related_name="related_image", blank=True, null=True) publishing_date = models.DateTimeField(default=timezone.now, blank=True) geom = models.PointField(srid=3857) def __str__(self): return self.title def get_absolute_url(self): return reverse("single_geopost", kwargs={"slug_title":self.slug_title}) This is the form: class GeoBlogPostForm(forms.ModelForm): title = forms.CharField( max_length=70, widget=forms.TextInput( … -
Adding a field to the Django User model
I need to add a model field "company" to the Django User model. I followed tutorials on how to do that but for some reason when I hit submit the browser just loops (keeps buffering) Not getting any errors in the terminal. It's hard to tell what's wrong if it just loops. this is what I've got: models: from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(max_length=50, blank=True) def __str__(self): return self.user.username forms: from .models import UserProfile class CompanyFieldForm(forms.ModelForm): company = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'autofocus': 'autofocus', 'placeholder': 'Company Name'}), label='') class Meta: model = UserProfile fields = ('company',) views: from django.contrib.auth import logout, login, authenticate from .forms import CompanyFieldForm def register(request): # KEEPS BUFFERING WHEN SUBMITTED ... WHY ? if request.method == 'POST': form = CreateUserForm(request.POST) company_form = CompanyFieldForm(request.POST) if form.is_valid() and company_form.is_valid(): user = form.save() profile = company_form.save(commit=False) profile.user = user profile.save() email = form.cleaned_data.get('email') plain_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=plain_password) login(request, user) return redirect('/list') else: form = CreateUserForm() company_form = CompanyFieldForm() context = {'form': form, 'company_form': company_form, 'is_reg_page': True} return render(request, 'registration/register.html', context) -
Using Multiple Databases with django
I have to use multiple databases in my project but there is a problem. Model can't see my database. when i go localhost:port/admin/app/accounts it says me no such table: accounts. model looking default database. not accounts.db how can i do that? I tried multiple thins in what i saw in internet but nothing happend. settings.py : ..... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'accounts': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'accounts.db') } } ..... models.py: ..... class Accounts(models.Model): email = models.TextField(blank=True, null=True) phone = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) password = models.TextField(blank=True, null=True) verify = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'accounts' .... Environment: Request Method: GET Request URL: http://localhost:port/admin/hede/accounts/ Django Version: 1.11.23 Python Version: 2.7.15 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hede'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper 552. return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" … -
How do I embed django forms into my css design?
I am creating a website and already finished the frontend. Now I want to handle a form submit post request using python to I am trying to do this using django but I can't figure out how I would attach CSS classes, onchange eventhandlers and IDs to the django forms insert divs and other html elements in between the django input elements within a single form This is my current frontend: <form method="post" autocomplete="off"> <p class="sub-header">Or just leave Us a Message:</p> <div> <div id="contact-layout"> <div class="input-container"> <input type="text" name="name" placeholder="Name"> <div class="input-bar"></div> </div> <div class="input-container"> <input type="text" name="email" placeholder="Email"> <div class="input-bar"></div> </div> <div class="input-container"> <input type="text" name="subject" placeholder="Subject"> <div class="input-bar"></div> </div> </div> <div class="input-container"> <textarea name="message" placeholder="Type your message here..." id="message-input"></textarea> <div class="input-bar"></div> </div> </div> <div> <p class="sub-header" id="user-image-header">Attach some images:</p> <div id="file-upload"> <span class="form-button">Choose Files</span> <input id="upload" type="file" onchange="LoadImage(this)" name="image" accept="image/*" multiple> </div> </div> <div class="delimiter"></div> <input class="form-button" type="submit" id="contact-submit" value="Submit"> <p id="submit-thanks">Thanks for submitting!</p> as you can see I have a few "normal" html text inputs, a text area and an input for multiple image files. In django I linked my static css files and setup my html frontend as a django template. My django form looks like … -
How should i store multiple values of a model field in the database?
i am creating a stocks website using django. i want to display prices of different stocks in the webpage. i want store the prices of stocks at different dates. there are 100 stocks with 20 different prices for them. i want to display them at different intervals i want store these 20 different prices of these stocks in the database. so that i can select which price to display manually. i want to store the 20 different prices of the stock and display any one of them using querysets One solution i tried is i listed all the different prices in an excel file and whenever i wanted to display a different price i import it using python shell another solution was create a price1,price2....price20 field in the model. this is a very poor solution though i guess another solution i thought was i could create different databases for the different values and use the 'using' method to query them whichever is required from django.db import models # Create your models here. class Stocks(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length = 10,null='true',blank='true') ticker = models.CharField(max_length = 10) currentprice = models.FloatField() change = models.FloatField() lastprice = models.FloatField() updated = models.BooleanField(default='False',null='true') percent … -
Docker can't find file (and it exists)
I am doing a project in Django, I use PyCharm in Windows 8.1. To start the web server and the database I use Docker installed on Debian (Linux) through a virtual machine (do not install Windows Docker for compatibility problems). Upon entering the virtual machine, I mount the window folder on that machine: mount.vboxsf csuperior /tmp/csuperior I start the web container and db from the virtual machine and when I want to insert a breakpoint in the IDE, I get the following warning: pydev debugger: warning: trying to add breakpoint to file that does not exist: /tmp/csuperior/reunion/views.py (will have no effect) The strange thing is that the file exists and the path is correct. In fact I can modify it and the changes take effect. To configure the debug I followed the following tutorial: https://www.jetbrains.com/help/pycharm/remote-debugging-with-product.html#remote-debug-config (without the SFTP part, since the files are copy when I load the folder). In the "path mapping" I use the same folders as in the mount.vboxsf.