Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Open link in new internal windows django, python
I need create web site with some links to another resources and I would like when visitor click in one of this links the new windows(pop up) is opened in the same page, and then visitor can close this window and open another link ... in python and django its possible? -
How can you query distinct values with Graphql?
I'm using django as back-end with a mongoDB and i'm trying to get distinct values with Graphql but i keep getting this error : "message": "Received incompatible instance \"{'subreddit': 'politics', 'score': 75799}\"." Here is my schema.py : class TopicType(DjangoObjectType): class Meta: model = Topic class Query(graphene.ObjectType): all_topics = graphene.List(TopicType) topic = graphene.Field(lambda: graphene.List(TopicType),subreddit=graphene.String(),score=graphene.String()) def resolve_all_topics(self, info,**kwargs): return Topic.objects.all() def resolve_topic(self,info,**kwargs): return Topic.objects.values("subreddit").order_by().annotate(score =Sum("score")) schema = graphene.Schema(query=Query) And here is my query query getTopics{ topic { subreddit }} -
how to serialize ArrayField on Django rest framework?
I'm trying to create some ArrayField on my model but when i try to send a POST request i get this error: File "path-to-env/lib/python3.8/site-packages/rest_framework/serializers.py", line 1072, in get_fields fields[field_name] = field_class(**field_kwargs) File "path-to-env/lib/python3.8/site-packages/rest_framework/fields.py", line 1442, in init super().init(**kwargs) TypeError: init() got an unexpected keyword argument 'child' The serializer class: (i've also tried with "all") class BenefitSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.id') class Meta: model = Benefit fields = ( 'name', 'description', 'is_active', 'is_cumulative', 'max_usage', 'start_at', 'end_at', 'active_days_week', 'discount_type', 'categories', 'categories_are_inclusive', 'brands', 'brands_are_inclusive', 'zip_code_ranges', 'user' ) The model: class Benefit(models.Model): user = models.ForeignKey(to='auth.User', on_delete=models.CASCADE) code = models.UUIDField(default=uuid.uuid4) name = models.CharField(max_length=255) description = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_cumulative = models.BooleanField(default=False) max_usage = models.IntegerField(default=0) start_at = models.DateTimeField(auto_now=True) end_at = models.DateTimeField(auto_now=True) active_days_week = ArrayField( base_field=models.CharField(max_length=3), choices=DAYS_OF_WEEK, default=list, verbose_name='active_days' ) discount_type = models.CharField( choices=DISCOUNT_TYPES, max_length=10, default='percent', verbose_name='discount_type' ) categories = ArrayField( base_field=models.CharField(max_length=50), default=list, verbose_name='categories' ) categories_are_inclusive = models.BooleanField(default=False) brands = ArrayField( base_field=models.CharField(max_length=50), default=list, verbose_name='brands' ) brands_are_inclusive = models.BooleanField(default=False) zip_code_ranges = ArrayField( base_field=models.IntegerField(), default=list, verbose_name='zip_code_ranges' ) -
Optimal Platform (Django, Rails, etc.) for Developing a Web Application With Plans for Native Mobile Applications?
I understand that this question may have several "correct" answers based on personal preferences, but I have spent a fair bit of time trying to find a setup that will work but have yet to come across a direct answer. I have a fair bit of experience with Ruby on Rails framework, some with Python based applications, and am more than willing to learn any web architecture needed. I have laid our the requirement of the application below. Application Requirements: + Connect to a single database (for both the web and mobile application) + Allow Authentication + Allow for the execution of python scraping script I -
Django - Insert data from uploaded excel file in the database model
I am trying to populate the database with data from uploaded xlsx file. I have followed the steps from this tutorial: https://buildmedia.readthedocs.org/media/pdf/django-excel/latest/django-excel.pdf In my case after upload the 404 error page occurs while the web server error log file only shows: [Sun Mar 15 20:31:11.075408 2020] [wsgi:error] [pid 6756] [remote 192.168.1.7:53883] Bad Request: /Project/store/ I am somehow stuck at this point ... I u/stand that thew form is not valid, but why? extract from models.py class Store(models.Model): code = models.CharField(max_length=100, unique=True) name = models.TextField() address = models.TextField() city = models.CharField(max_length=100) zip = models.IntegerField() def __str__(self): return self.cod+" "+self.nume class Meta: ordering = ["cod"] verbose_name_plural = "Stores" extract from view.py class UploadFileForm(forms.Form): file = forms.FileField() def store(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): request.FILES['file'].save_to_database( model=Store, mapdict=['code', 'name', 'address', 'city', 'zip']) return HttpResponse("OK") else: return HttpResponseBadRequest() else: return render(request, 'store.html', {}) extract from template - store.html <form action="{% url "store" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group mb-4 mt-3"> <label for="exampleFormControlFile1">Excel file ONLY !</label> <input type="file" title="Upload excel file" name="excel_file" class="form-control-file" id="exampleFormControlFile1" required="required"> </div> <input type="submit" value="Upload" name="time" class="mt-4 mb-4 btn btn-primary"> </form> -
Django REST Framework ApiView not allowing DELETE
I am new to Django and I am having a issue sending a DELETE request to a class based view which inherits from APIView. Here is my class: class PageDetail(APIView): def get(self, request, pk): page = get_object_or_404(Page, pk=pk) data = PageSerializer(page).data return Response(data) def put(self, request, pk): stream = io.BytesIO(request.body) response = JSONParser().parse(stream) page = Page.objects.get(pk=pk) page.title = response.get('title', page.title) page.content = response.get('content', page.content) user = User.objects.get(pk=response.get('author', page.author)) page.author = user page.save() return HttpResponseRedirect(reverse('pages_detail', args=(page.id,))) def delete(self, request, pk): page = Page.objects.get(pk=pk) page.delete() return HttpResponseRedirect(reverse('pages_list')) When I make the DELETE request, the resource is deleted, but the page responds with the message: {'detail':'Method 'DELETE' not allowed.'} Although in the header I have: Allow: GET, PUT, DELETE, HEAD, OPTIONS Anyone have any ideas? -
Django REST Framework - Saving phone with country prefix to database
Using my creating user endpoint, I want to take 'phone' value from request, and add it with country calling code before. Request data provides me country code, which is foreign key to Country model. Example request body: { ... 'phone':'000111222', 'country':'616', } In this case, '616' is Poland country code. I do following to implement all my logic in my UserViewSet create() method: class UserViewSet(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() def create(self, request, format=None): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # collecting country country_code = request.data['country'] country = Country.objects.get(code=country_code) # setting dial code before phone dial_code = country.calling_code #'48' phone = dial_code + request.data['phone'] #'48000111222' # checking if final phone number already exists in database if User.objects.filter(phone=phone).exists(): return Response({'phone': 'Phone number already exists.'}, status=status.HTTP_400_BAD_REQUEST) serializer.save(country=country, phone=phone) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Code works for now, but I have few issues. UserSerializer actually validate my fields before my create function does. It use raw phone value to validate uniqueness in database - in this case 000111222 instead of 48000111222, what can cause an unwanted error. My solution seems a bit too complicated for me, could any of the built-in functionalities help? If not, would it be a good idea to … -
Django framework, crud in grid row
I’ve been developing an app in djanog 3.0 for my wife. Got a nice modal ajax crud up and running for the grid, but she does not like the modal effect, she just wants to edit inside the row and always have an empty row at the bottom for new entries. I’ve looked at table2 and jqgrid but have not been able to find something that works like that. I’ve now been playing around with editablegrid.net js grid and I can display data and edit, but not save the edited data. Editablegrid is a good example of what my wife would like to do, without the empty new row, but should be able to hack that in. Obviously I’ll not be able to make a row a from, so I need to figure out how to make my data serial in something like json. I then also need the CSRF token as part of the json right? I’m way out of my depth as I develop embedded c for a living and this all is self taught as we go. Questions are: What is the best grid for something like this? Is it even possible? Is django even suited for … -
How can I implement this in? I want a employeee to enter a code that connect to the employer table on registration?
I want to create a company and employee relationship. So there going to be two table. The company won't be adding the employee to their list. A employee, on register will enter a company code(like the company primary key) on the form and it will link to the company. I am using django, postgresql -
Django load an imageField in a template
Essentially what I'm trying to do is load the thumbnail image from my Post model in my template. models.py class Post(models.Model): objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') thumbnail = models.ImageField(name="photo", upload_to='thumbnails/', null=True, default='default.png') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def get_context_data(self, **kwargs): obj = Settings.objects.get(pk=1) context = super().get_context_data(**kwargs) context["blog_name"] = getattr(obj, "blog_name") context["footer"] = getattr(obj, "footer") context["description"] = getattr(obj, "description") context["keywords"] = getattr(obj, "keywords") return context I added <img src="{{post.thumbnail.url}}" alt="{{ post.title }}"> to my template to try and load the image but no luck. I can access the image if I load the path manually and i already added MEDIA_URL and MEDIA_ROOT to my settings.py If this question can be improved please let me know as I am knew to django. -
I try to add data from Admin pannel but it fails Django
I try to add data as admin. I go to the url /admin/festival/festival/add and it shows me the form.I complete it, but when i click on save it shows me the IntegrityError, saying that Foreign Key constraint failed. But i have no foreign key in the model. How can i fix this? IntegrityError at /admin/festival/festival/add/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://127.0.0.1:8000/admin/festival/festival/add/ Django Version: 3.0.4 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: /home/anamaria/workspace/AllFest2/venv/lib/python3.6/site-packages/django/db/backends/base/base.py in _commit, line 243 Python Executable: /home/anamaria/workspace/AllFest2/venv/bin/python Python Version: 3.6.9 Python Path: ['/home/anamaria/workspace/AllFest2/festivals', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/anamaria/workspace/AllFest2/venv/lib/python3.6/site-packages'] here is the models.py: from django.db import models from jsonfield import JSONField class Festival(models.Model): name = models.CharField(max_length=100) start_date = models.DateTimeField(blank=True, null=True, default=None) end_date = models.DateTimeField(blank=True, null=True, default=None) number_of_tickets = models.IntegerField() location = JSONField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name in views.py i have: from .serializers import FestivalSerializer from .permissions import FestivalPermission from rest_framework import mixins, status from festival.models import Festival from rest_framework.viewsets import GenericViewSet class FestivalViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,GenericViewSet): serializer_class = FestivalSerializer permission_classes = [FestivalPermission] queryset = Festival.objects.all() serializer in serializers.py: from rest_framework import serializers from festival.models import Festival class FestivalSerializer(serializers.BaseSerializer): class Meta: model = Festival fields = '__all__' … -
how to save a model that contains self-referential ForeignKey from form
I'm new in django ... I have a model with a self-referential field and i want to get this model from a form. but this self-referential have no value! what should i do?! models.py class agents(models.Model): name = models.CharField(max_length=100) address = models.TextField(blank=True, null=True) phone = models.CharField(max_length=20) is_producer = models.BooleanField(default=False) serial = models.TextField(default='') users = models.ManyToManyField(user_models.users, through='user_agent') def __str__(self): return self.name def get_absolute_url(self): return reverse('agent_detail', args=[str(self.id)]) class user_agent(models.Model): user = models.ForeignKey(user_models.users, on_delete=models.CASCADE) agent = models.ForeignKey(agents, on_delete=models.CASCADE) parent = models.ForeignKey("self", on_delete=models.CASCADE) forms.py class AgentSignUpForm(forms.ModelForm): class Meta: model = models.agents fields = ('name', 'address', 'phone', 'is_producer', 'serial', 'users', ) views.py @login_required def agent_register(request): if request.method == 'POST': form = forms.AgentSignUpForm(request.POST) if form.is_valid(): agent = form.save(commit=False) agent.save() form.save_m2m() return redirect('agent_list') else: form = forms.AgentSignUpForm() return render(request, 'agent/signup.html', {'form': form}) -
ctypes init fails using local app engine, django and virtualenv with python 2.7
I'm facing an issue with the init of ctypes if int(_os.uname()[2].split('.')[0]) < 8: ValueError: invalid literal for int() with base 10: ' My app is written in Python 2.7 and based on Django, running locally using App Engine SDK and virtualenv. It's been in production for a long time and is running successfully locally on other machines. Meaning this is a local issue for my machine. I'm on Mac OSX 10.15.3 Catalina. The issues arises when I'm loading any page of my app, after starting the app engine local development server. The App Engine server is starting successfully (I can access the app engine admin webpag), but the above exception is being raised (see callstack below), as it seems os.uname() is returning an invalid value. When running os.uname() myself, the result seems legit. Both when the virtualenv is activated or using the os/pyenv python interpeter. Python 2.7.15 (default, Mar 15 2020, 22:00:51) [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.17)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.uname()[2].split('.')[0] '19' Solutions I've tried: Calling os.uname() inside and outside of the virtualenv, it works correctly. Creating a virtualenv using the system Python 2.7.17 installation Creating … -
DRF reverse cannot find view name
I am working of django rest framework api_root. It cannot find view even though I name it. # board/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from .views import BoardList, BoardDetail, api_root app_name = 'board' urlpatterns = [ path('boards/', BoardList.as_view(), name='board-list'), # board-list path('boards/<int:pk>', BoardDetail.as_view(), name='board-detail'), path('', api_root), ] urlpatterns = format_suffix_patterns(urlpatterns) # board/views.py from django.contrib.auth.models import User from django.shortcuts import render from rest_framework import generics, permissions, serializers from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from .models import Board from .serializers import BoardSerializer from .permissions import IsAuthorOrReadOnly @api_view(['GET']) def api_root(request, format=None): return Response({ 'boards': reverse('board-list', request=request, format=format) # board-list }) class BoardList(generics.ListCreateAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(author=self.request.user) It throws error, Reverse for 'board-list' not found. 'board-list' is not a valid view function or pattern name. Why it cannot find view name? -
Manager isn't available; 'auth.User' has been swapped for 'users.CustomUser'
I am new to Django and I am trying to implement custom user authentication for my website. When I try to create a new user for the signup view, I get the error 'Manager isn't available; 'auth.User' has been swapped for 'users.CustomUser'. Creation of new users from Admin page works fine. I googled the error, but none of the advised solution is working for me. See the code below. The django app I created to manage users is "users". models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): birth_date = models.DateField(null=True, blank=True) forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): first_name = forms.CharField(max_length=30, help_text='Required`.') last_name = forms.CharField(max_length=30, help_text='Required.') email = forms.EmailField(max_length=254, help_text='Required. Please input a valid email address.') birth_date = forms.DateField() class meta(UserCreationForm.Meta): model = CustomUser fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email', 'birth_date',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields views.py: from .forms import CustomUserCreationForm from django.urls import reverse_lazy from django.views.generic import CreateView class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = … -
Django. If-statement in template doesnt register when variable changes from False to True
When someone likes a post I want the button to change to 'dislike' instead of 'like'. The action to remove the like is working, but the button doesn't change. In template: <form action="{%url 'like_post' %}" method='post'> {% csrf_token %} {% if is_liked %} <button type='submit' name="post_id" value = "{{ post.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type='submit' name="post_id" value = "{{ post.id }}" class="btn btn-primary">Like</button> {% endif %} In views: def like_post(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user.id) is_liked = True return HttpResponseRedirect(post.get_absolute_url()) -
How can I load a fixture so that it appends data to existing records in a model?
I want to load a fixture into my model, but have it add additional rows rather than overwrite the existing ones. Per this answer, I have manually set "pk": null, however when I load this data it still overwrites the existing data in the model. [ { "model": "myapp.mymodel", "pk": null, "fields": { "name": "foo", } }, { "model": "myapp.mymodel", "pk": null, "fields": { "name": "bar", } } ] How can I load a fixture so that it appends data to existing records in a model? -
Linking Django - Postgresql with Standalone Docker
Following the thread of this question, I am trying to run Django in one container, Postgres in another container, and connect them "manually" via user-defined networks. This is my network after launching both containers: [ { "Name": "django-network", "Id": "bbae9d656ea9ccc56c2c0f4db310d53fa135275358b16bc08636cf0c1a56127f", "Created": "2020-03-15T17:21:48.405473202Z", ... "Containers": { "79c7a66a5f4a892486d3c1d3089ff5850e2753af66cc694798015f80021297f3": { "Name": "postgres-10", "EndpointID": "d5fb80edfdf19678890da858e25e8bafd3e56113f82a5c1e39de5ca16f1caf5a", "MacAddress": "02:42:ac:12:00:02", "IPv4Address": "172.18.0.2/16", "IPv6Address": "" }, "8873f054b23bb888b91deb64c819c1bf370db6ddc7b9f638ee60d850ee082da6": { "Name": "betcomm-django", "EndpointID": "e60640ec4dfbc1dd86b3464260ed73446846b8dd33b6e4b173befe26d5ee0738", "MacAddress": "02:42:ac:12:00:03", "IPv4Address": "172.18.0.3/16", "IPv6Address": "" } },... ] And this is the error on the Django container: root@8873f054b23b:/app/backend# python manage.py runserver 0.0.0.0:8000 Running Docker locally, setting env variables... DB: betcomm-dev User: postgres Pass: postgres Host: docker-db Port: 5432 Running Docker locally, setting env variables... DB: betcomm-dev User: postgres Pass: postgres Host: docker-db Port: 5432 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection ... ... connection = Database.connect(**conn_params) File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "docker-db" (172.18.0.2) and accepting TCP/IP connections on port 5432? But docker-db on that IP is indeed connected. These are the … -
Python / Django: Dynamically Changing Function Based on Instance
I have a class where each instance needs to call a separately defined method depending on the configuration. So imagine: class MyClass(models.Model): ... a = MyClass(someData) b.fireFunction() <-- needs to fire some specific function b = MyClass(someData2) b.fireFunction() <-- needs to fire a different function The best example I can think of is a consumables system in a game– they all inherit from some base consumable class, but using the consumable item performs an entirely different action for each item. I know with packages like Celery I can register a set of tasks with a decorator. What's the way to accomplish this? Here is what I'm thinking: Register a set of actions with some kind of ConsumableActions model. For celery these do not appear to be saved in the db. What's a good way to do this? Somehow call that saved action. Perhaps something like this? import foo method_to_call = getattr(foo, 'bar') result = method_to_call() -
model usage history with class diagram
I am modeling a web application for managing depot's materials my question is divided into 02 parts: part 1: I did a 1st modeling of 'use of articles' by the employees. class diagram the article type can be: gloves, hat, boots, etc ... each article has multiple units.(gloves: 50 units, hat: 100units .....) _ an employee can use several articles, but only one unit at a time,, for example: an employee X use (1 gloves, 1 hat, 1 boot, etc.) _ a unit can be used by a single employee. am i in the right way? if not, how can i improve it? part 2: I want to have the history of use of materials by employees. _ an employee can use several articles for a given period (date_deb, date_end) _ an article can be used by a single employee for a given period (date_deb, date_end) -if I ask these two questions: for such an employee, what items have he used over time (usage history)? for such a unit, who are the employees that used this unit? for example the use of unit1: [unit1, (employee1,, date_deb, date_end), (employee2, date_deb, date_end), (), ........] how to do the modeling to answer these … -
How to update two forms in a single view where one form is userform(djangoform) and one is modelform (with model being userextension model)?
This is the user function model. this is the edit profile view where I need to use both forms to save in the database from html template These are the two forms which I need to use in one single view This is the html template on which I need to show the contact number and be able to edit it I apologize if I am not able to present my question properly. I want to be able to show and edit the contact number on the same page as other details like username, last name, and first name. I have tried different methods like using query to call from database and save both form and query on the same function but it was not updating the contact number. Can this be done or do I have to take some different approach if this can be done, please let me know? If I missed some details please let me know in case if there are question as this is my first time asking here at stack -
Visual Studio 2017/Django(v1.11.29) Trouble Installing Python Packages into ENV
I am trying to install(Python 3.6.6) packages into a Django Project env with Visual Studio 2017. I have no trouble installing these packages when the project has been newly initiated. The trouble begins when I try and install packages within a clone from the master in GitHub; I then get errors and the packages are not installed. I have tried cmd into the env, but they still do not want to install: ----- Installing 'django-phone-field==1.8.0' ----- Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\__main__.py", line 16, in <module> from pip._internal import main as _main # noqa File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\_internal\__init__.py", line 20, in <module> from pip._vendor.urllib3.exceptions import DependencyWarning File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\_vendor\urllib3\__init__.py", line 8, in <module> from .connectionpool import ( File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\_vendor\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import ( ModuleNotFoundError: No module named 'pip._vendor.urllib3.packages' ----- Failed to install 'django-phone-field==1.8.0' ----- Any suggestions would be appreciated. -
.values() function breaks datetime field in django queryset
I am trying to import some data from my DDBB in a django3 project. I have been able to retrieve properly some instances of my Order objects but it looks like in some cases the provided timestamps get a delay of whole hours. When I query DateTimeField like this in my view: orders_list = Order.objects.filter(client_id=client_idf) And after that, y pass this as context to my template I get the correct date which is 01-march-2009 00:00. When I query like this: orders_list = Order.objects.filter(client_id=client_idf).values() data = pandas.DataFrame(orders_list) And I ask for the "datetime" it displays 28-February-2009 at 23:00. -
cannot get menu url from database Django
I have one big problem. I created my own menu navigation for Django. simple models which contain menu name, URL,image, and slug. so when I iterate through the database I can get name and everything is fine. but when I want to get URL nothing happening I'm getting no error but when I'm inspecting via browser getting empty space on HTML site version but there is Django code. views.py from django.shortcuts import render from .models import BlogPost from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from slider.models import HomePageSlider from blogmenu.models import Menu def index(request): Post_list = BlogPost.objects.all()[:5] Slider_item = HomePageSlider.objects.all() menu_item = Menu.objects.all() template_name = 'front/index.html' return render(request, template_name, {"Post_list":Post_list, "data_item":Slider_item, "menu_item":menu_item, }) def post_list(request): postlist = BlogPost.objects.all().order_by('-Post_created_on')[:5] menu_item = Menu.objects.all() template_name = 'front/postlist.html' paginate_by = 3 return render(request, template_name, {"postlist":postlist, "menu_item":menu_item, }) def post_detail(request,Post_slug): template_name = 'front/post_detail.html' post_content = BlogPost.objects.all() left_post = BlogPost.objects.all()[:5] menu_item = Menu.objects.all() try: Post = BlogPost.objects.get( Post_slug = Post_slug) except : return render(request,'front/404.html') return render(request, template_name, {'blogpost':Post, 'post_content':post_content, 'left_post':left_post, "menu_item":menu_item, }) # Create your views here. My urls.py from django.urls import path from .import views from django.conf import settings from django.contrib.sitemaps.views import sitemap from blog.sitemaps import PostSitemap from .feeds import LatestPostsFeed sitemaps = { "post": PostSitemap, … -
Trying to reload a python function from within Java using Django?
I am trying to call this python class from within Java class Testing(models.Model): hello = random.choice([3, 4, 11, 66, 34, 22, 33]) def __str__(self): return hello I call it within my html page using Java var Testing = "{{Testing}}"; document.write(Testing); I made the script to test if random.choice is ran again when calling the function in Java, it's not (it produces the same number if you refresh the page). How would I go about re-running random.choice when java calls for Testing.hello?