Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable install package from requirements.txt using pip in vagrant development server using virtaul environment
Unable install the packages from requirements.txt in vagrant development server. Error Message: (env) vagrant@ubuntu-bionic:/vagrant$ pip install -r requirements.txt Collecting django==2.2 (from -r requirements.txt (line 1)) Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e748>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e7f0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e4e0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e550>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e908>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Could not find a version that satisfies the requirement django==2.2 (from -r requirements.txt (line 1)) (from versions: ) No matching distribution found for django==2.2 (from -r requirements.txt (line 1)) requirements.txt django==2.2 djangorestframework==3.9.2 after getting error … -
Could not resolve URL for hyperlinked relationship using view name "v1:resources:profiles:profile_detail"
Im getting this error and have been trying to fix it for hours. I think the problem has something to do with the namespaces. I tried multiple solutions I found on but none of them works. This line -> profile = serializers.HyperlinkedRelatedField(read_only=True, view_name="v1:resources:profiles:profile_detail") gives me an error Could not resolve URL for hyperlinked relationship using view name "v1:resources:profiles:profile_detail. I tried so many solutions and ended up with this tedious nested namespace. Project structure looks something like this manage.py src/ wsgi.py asgi.py urls.py apps/ urls.py authentication/ urls.py resources/ urls.py profiles/ urls.py posts/ websocketchat/ filteringrecommender/ src/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('v1/', include('src.apps.urls', namespace='v1'))] src/apps/urls.py app_name = 'v1' urlpatterns = [ path('auth/', include('src.apps.authentication.urls', namespace='auth')), path('resources/', include('src.apps.resources.urls', namespace='resources')),] src/apps/resources/urls.py app_name = 'resources' urlpatterns = [ path('profiles/', include('src.apps.resources.profiles.urls', namespace='profiles')),] src/apps/resources/profiles/urls.py app_name='profiles' urlpatterns = [ path('', views.ProfileListView.as_view(), name='profiles'), path('<str:profile_id>', views.ProfileDetailView.as_view(), name='profile_detail')] src/apps/authentication/serializers.py class UserSerializer(serializers.ModelSerializer): profile = serializers.HyperlinkedRelatedField(read_only=True, view_name="v1:resources:profiles:profile_detail") class Meta: model = User fields = ('id', 'username', 'email', 'profile') -
How to filter my model objects based on Tree QuerySet from MPTT Django?
I was fighting with creating a categories with parent categories. Similar to this: - Category 1 - SubCategory 1.1 - SubCategory 1.2 - Category 2 I managed to do this with django-mptt and MPTTModel and TreeForeignKey: class Category(MPTTModel): title = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') And I am happy with it, I am doing all the magic in templates and in views.py I am getting 'TreeQuerySet' object. And I can see that it is working (I used method get_family()), if I will send Category 1 then in this TreeQuerySet object I have (Category 1, SubCategory 1.1, SubCategory 1.2) so success. But then I have no idea how to do query based on that. I have object model: class Post(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True, default=None) And I want to make a query through my Post objects with this TreeQuerySet to get Post objects that have category - Category 1 OR SubCategory 1.1 OR SubCategory 1.2 attached. And I was trying many things with union, for loops and other stuff, but it all failed most of the time because object TreeQuerySet doesn't have such and such method. I started to think that I should … -
How to fix CSRF foreign key in [django]
I have an error in DJANGO, I have 2 foreign keys in one of my models, and whenever I want to register a new row, it gives a 403 CSRF error. -
How can i retry a django celery task when I click on retry button of my site?
I am using redis and rabbitmq to put the tasks in queue. I want to add a retry button on my on click of which a particular task can be retried. Please tell me if someone can help me with this. -
The email address of participant is added to all meetings, not just the one he joined. Django
Followed the tutorial on creating meetups and allow participants join them. When adding a participant (his email address) using the form, the email address is added to all meetings, not just the one he joined. I am new to Django, but it seems like the problem is in the ManyToMany relationship. Models.py from django.db import models class Location(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=300) def __str__(self): return f'{self.name} ({self.address})' class Participant(models.Model): email = models.EmailField(unique=True) def __str__(self): return self.email class Meetup(models.Model): title = models.CharField(max_length=200) organizer_email = models.EmailField() date = models.DateField() slug = models.SlugField(unique=True) description = models.TextField() image = models.ImageField(upload_to='images') location = models.ForeignKey(Location, on_delete=models.CASCADE) participants = models.ManyToManyField(Participant, blank=True) def __str__(self): return f'{self.title} - {self.slug}' Views.py from django.shortcuts import render, redirect from .models import Meetup, Participant from .forms import RegistrationForm # Create your views here. def index(request): meetups = Meetup.objects.all() return render(request, 'meetups/index.html', { 'meetups': meetups }) def meetup_details(request, meetup_slug): try: selected_meetup = Meetup.objects.get(slug=meetup_slug) if request.method == 'GET': registration_form = RegistrationForm() else: registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): user_email = registration_form.cleaned_data['email'] participant, _ = Participant.objects.get_or_create(email=user_email) selected_meetup.participants.add(participant) return redirect('confirm-registration', meetup_slug=meetup_slug) return render(request, 'meetups/meetup-details.html', { 'meetup_found': True, 'meetup': selected_meetup, 'form': registration_form }) except Exception as exc: return render(request, 'meetups/meetup-details.html', { 'meetup_found': False }) def confirm_registration(request, meetup_slug): … -
How to get the el-date-picker date value and pass it to django view.py
How to get the el-date-picker date value and pass it to django view.py. pickup_date = request.POST.get('pickup_date') is not working how to make el-date-picker a required field that force user to select a date when filling the form html: <!DOCTYPE html> <html lang="en"> <head> <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">--> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> </head> <style> </style> <body> <form> <div id='app'> <el-date-picker v-model="value" type="date" placeholder="select date" value-format="yyyy-MM-dd" :picker-options="pickerOptions"> </el-date-picker> </div> <button type="submit">submit</button> </form> </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script> var Vue = new Vue({ el: '#app', data: { value:'', pickerOptions: { disabledDate(time) { return time.getTime() <= Date.now() } }, }, created() { }, mounted() { }, methods: { } }) </script> </html> -
can't import markdown in Django project file
I'm having issues importing markdown in the blog_tags.py file I created or anywhere else. I installed it with the line "pip install markdown" and it installed successfully. I checked with "pip freeze" and it is there. However, when I try to import markdown in a .py file it says it can't find the module. code sample code: from django import template from ..models import Post from django.db.models import Count from django.utils.safestring import mark_safe import markdown register = template.Library() @register.simple_tag def total_posts(): return Post.published.count() @register.inclusion_tag('blog/post/latest_posts.html') def show_latest_posts(count=5): latest_posts = Post.published.order_by('-publish')[:count] return {'latest_posts': latest_posts} @register.simple_tag def get_most_commented_posts(count=5): return Post.published.annotate( total_comments=Count('comments') ).order_by('-total_comments')[:count] @register.filter(name='markdown') def markdown_format(text): return mark_safe(markdown.markdown(text)) Have a nice day everyone -
Real-time scraping website with Django: stoppable scraping process and loading bar
What I would like to achieve I would like to make a website that allows users to scrape information from other websites. My goal is to achieve something as follows: User presses "scrape" When the scraping process begins, Django renders a view with a loading message and a "stop" button If the user presses the "stop" button, or if the scraping process terminates, a view with the scraping results is shown Current state At the moment, I have a very simple scraping website with a horrible user experience. After the user presses scrape, I render a view similar to the following one: def scraping_view(request, scraper_args): scrape_results = scrape(scraper_args) # Very long function! return render(request, 'scrape_view.html', scrape_results ) This is a bad idea, as the scrape function takes a long time, and the user experience is terrible. My (probably bad) idea My idea was to: launch a celery task and render an intermediary view with the loading message and a "stop" button let the celery task store the scrape results somewhere (where?) find a way to revoke the task if the user presses the "stop" button retrieve the results of the celery task when the task is finished or when "stop" … -
why my pc not able to install pip packages and also shows no command found when run pip commands?
I tried everything thing but no command found comes everytime, uninstall ..reinstall I have the 3.10.1 version in system also, my script folder shows empty please help me as my Django work hinders due to this -
Django Channels does not work inside a DjangoQ jobs or hooks handler
I am trying to trigger a websocket message when a DjangoQ job ends, but it doesn't work. The same code works inside a views.py APIView that queues the job, but does not work inside my jobs.py handler. It does not generate error. It does nothing. views.py # works (calls consumer handler, websocket event emitted and logged on browser console) from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def event_trigger(): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'event_sync', { 'type': 'send_message_to_frontend', 'message': "event_trigered_from_views" } ) Same code called from hooks.py does not work. Does nothing. hooks.py from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def event_trigger(): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'event_sync', { 'type': 'send_message_to_frontend', 'message': "event_trigered_from_hooks" } ) def import_wallet_completed(task): ic(task.result) event_trigger() Invite.objects.update_or_create( emoji_key=task.result['emoji_key'], defaults={ 'job_status': 'wallet_imported' } ) What could be going on? -
Can I insert data from phpmyadmin even after launching the website to the internet?
I am using Django framework, MySQL through xampp and inserting data from phpmyadmin. Can I keep on inserting data from phpmyadmin even after launching the website to the internet or is it necessary to register my models in admin.py and then create a superuser to insert data to a already hosted website? -
Django + Docker: connection to server at "localhost" (127.0.0.1), port 5432 failed
I am trying to run my Django app (Nginx, Gunicorn) in docker. But for request http://167.99.137.32/admin/ I have error: (full log https://pastebin.com/0f8CqCQM) onnection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 5432 failed: Address not available Is the server running on that host and accepting TCP/IP connections? I was trying answers from Can't run the server on Django (connection refused) but didn't solve my problem settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lk_potok_2', 'USER': 'postgres', 'PASSWORD': 'post222', 'HOST': 'localhost', 'PORT': 5432, }, docker-compose.yml version: '3.9' services: django: build: . # path to Dockerfile command: sh -c "gunicorn --bind 0.0.0.0:8000 potok.wsgi:application" volumes: - .:/project - static:/project/static expose: - 8000 environment: - DATABASE_URL=postgres://postgres:post222@localhost:5432/lk_potok_2" - DEBUG=1 db: image: postgres:13-alpine volumes: - pg_data:/var/lib/postgresql/data/ expose: - 5432 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=post222 - POSTGRES_DB=lk_potok_2 nginx: image: nginx:1.19.8-alpine depends_on: - django ports: - "80:80" volumes: - static:/var/www/html/static - ./nginx-conf.d/:/etc/nginx/conf.d volumes: pg_data: static: nginx-conf.nginx upstream app { server django:8000; } server { listen 80; server_name 167.99.137.32; location / { proxy_pass http://django:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /var/www/html/static/; … -
How do I get the actual image instead of getting url when editing the Modelforms in django template?
html <div> {{variant_images_form.display_image|as_crispy_field}} </div> views.py def item_approval(request, pk): if request.method == "GET": product_form = AdminProductForm(request.POST) item = ProductVariants.objects.get(item_num=pk) product_id = item.product_id product = Product.objects.get(product_id=product_id) product_variant_images = ProductVariantsImages.objects.filter(product_variant=item) product_form = AdminProductForm(instance=product) item_form = ProductVariantsForm(instance=item) variant_images_form = ProductVariantsImagesForm(instance=product_variant_images[0]) return render(request, 'loom_admin/product_details.html', {'item_form':item_form, 'product':product, 'item':item, 'product_form':product_form, 'variant_images_form':variant_images_form, }) How to render the model form with the actual image instead of showing the URL path. -
1054, "Unknown column 'work_waterlevel.id' in 'field list'" in django
I am trying to display my mysql data on a HTML page everything is working fine but when i try to display the data from mySQL tohtml page its showing 1054, "Unknown column 'work_waterlevel.id' in 'field list'") this error how to resolve this error my models.py is from django.db import models # Create your models here. class waterlevel(models.Model): time=models.DateTimeField() status=models.CharField(max_length=50) level=models.DecimalField(max_digits=12,decimal_places=6) -
How to mark Oscar Product as Available
I successfully added a product in Django Oscar, I successfully added price to the product but am unable to mark order as available to the public for sales. the product still remain unavailable. I have no clue on how to make the added product available for purchase even after product price is added. this documentations couldn't even help me. https://django-oscar.readthedocs.io/en/3.1/topics/prices_and_availability.html I couldn't find any help after reading this documentation above. the image is the current description of the current product. -
Ajax not returning data to server(Django) on some button clicks
Iam building a webpage that contains auto generated buttons using django,I am using ajax to update table values according to each button click.I have implemented ajax,When i try to print request.POST on server side ,it reutrns the value inconsistencly,sometimes it would,sometimes it wont. I have tried putting alert on success method and each time i click a button alert pops up even though it doesnt return an value. Here's the Code: <button name="date" type="submit" value={{d}} onclick="sendData(event)""> Ajax code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> function sendData(event){ event.preventDefault(); $.ajax({ type : "POST", url: "", data: { date : event.target.value, csrfmiddlewaretoken:'{{ csrf_token }}', }, success: function(data){ }, failure: function() { } }); } -
Cache function or view?
I want to use django-rest-framework with cache. @cache_page(10 * 60) @api_view(['GET']) def get_num(request): if request.method == "GET": res = ["ok"] return Response(res) It works well. So actually I want to cache not view but function @cache_page(10 * 60) def getCalc(num): return num * 10 @api_view(['GET']) def get_num(request): if request.method == "GET": res = getCalc(request.query_params.get('num')) return Response(res) There comes error TypeError: _wrapped_view() missing 1 required positional argument: 'request' Is it possible to use cache for function?? -
Failed to create a seller instance using django signals
I'm building a website with 2 user types and still new to django. And I want to add the functionality to add the seller of the product whenever a product is sold. I'm sorry that I couldn't explain it better. Here's the code of models.py: class Ordered(models.Model): products = models.ForeignKey(Products, on_delete = models.SET_NULL, null = True) seller = models.ForeignKey(SellerProfile, on_delete = models.SET_NULL, null = True) buyer = models.ForeignKey(CustomerProfile, on_delete = models.CASCADE) ordered_on = models.DateTimeField(auto_now_add = True) And this is the signal code: @receiver(post_save, sender = Ordered) def new_order_for_seller(sender, instance, created, *args, **kwargs): seller = Ordered.seller.sellerprofile if created: Ordered.objects.create(seller = seller) Any suggestion or correction of the code will be really helpful. Thank you -
In case of Django model,
In the django code in order to make a model, for example, class Student(models.Model): name = models.CharField(ax_length = 200) Why models.CharField(ax_length = 200). Why can't we write only name=CharField(ax_length = 200) -
How to fix error testing Authentication user?
I'm learning Drf, I'm figuring out to Athuenticate user login Testapi in Drf, it showing error Not valid view function or pattern name. Can Anyone suggest what is wrong with the code? URLS.PY urlpatterns = [ path('admin/', admin.site.urls), path('', include('college.urls')), path('auth',include('rest_framework.urls'), name='rest_framework'), ] TEST.PY USER_URL = reverse('auth') class StudentsDetailsTestCase(APITestCase): def test_login_user(self): self.assertTrue(self.client.login(username='***', password='***')) response = self.client.get(USER_URL) self.assertEqual(response.status_code,status.HTTP_200_OK) traceback error Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Users\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\Users\collegedjango\MYSITE\college\tests.py", line 35, in <module> USER_URL = reverse('auth') File "C:\Users\collegedjango\venv\lib\site-packages\rest_framework\reverse.py", line 47, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra) File "C:\Users\collegedjango\venv\lib\site-packages\rest_framework\reverse.py", line 60, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File "C:\Users\collegedjango\venv\lib\site-packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\collegedjango\venv\lib\site-packages\django\urls\resolvers.py", line 729, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'auth' not found. 'auth' is not a valid view function or pattern name. ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) -
Embedded HTML code in Python string doesn't appear properly in Django
I'm facing a problem when I embed HTML code in my python's view.py Basically, my objective is to customize the color of certain words only (based on the input). I want to do it by modifying the view.py For example (my view.py): def home(request): form = request.POST.get('uncorrected') texts = str(form) + '<span style="color: red">test text but this section is red</span>' return render(request, 'corrector/home.html', {'text': texts}) Inside my index.html: <textarea type="text" id="textarea" name="uncorrected"> {{ text }} </textarea> However, when I type "my text" in the textarea it displays only: my text <span style="color: red">test text but this section is red</span> It doesn't make the text red, it directly displays the code. How can I make it work? -
Why does Django store charfield as a tuple?
Say I have a simple model in django class Customer(models.Model): session_id = models.CharField(max_length=200) nuts3 = models.CharField(max_length=200) To save a model object I will do this Customer.create(session_id = "unique_session_id", nuts3 = "some text") Now say that I need to overwrite the nuts3 in the saved model object with some other text customer = Customer.objects.filter(session_id = "unique_session_id") customer = customer[0] customer.nuts3 = "some new text" customer.save() When viewing the saved customer object in admin, I see a tuple in the nuts3 charfield ('some new text',). I have expected in the field only to have the string without a tuple. How come that Django added the string as a tuple? -
How to Convert This Sql Query TO Django Query
I want Get UID Based on Email Filtering Like "(select Uid From User_master where email = 'xyz.gmail.com')" How to Convert This Sql Query TO Django Query -
"version" key not founded in connect django and elastic-apm
i want to connect my django project with elastic apm but when i run my project, i see this line : No version key found in server response but my elastic server response have this key : { "name" : "something", "cluster_name" : "elasticsearch", "cluster_uuid" : "ikPV-LjKQ2mxKz3Nr0pNTQ", "version" : { "number" : "7.16.2", "build_flavor" : "default", "build_type" : "deb", "build_hash" : "2b937c44140b6559905130a8650c64dbd0879cfb", "build_date" : "2021-12-18T19:42:46.604893745Z", "build_snapshot" : false, "lucene_version" : "8.10.1", "minimum_wire_compatibility_version" : "6.8.0", "minimum_index_compatibility_version" : "6.0.0-beta1" }, "tagline" : "You Know, for Search" } and this is my django settitngs : ELASTIC_APM = { 'SERVICE_NAME': 'apm-inolinx', 'DEBUG': env('DEBUG'), 'SERVER_URL': 'http://127.0.0.1:9200', }