Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing Tags using Django rest framework
TDLR : what is the best way to implement tags in django-rest-framework. where the tags has a created_by field which is the currently authenticated user. I am trying to achieve a very simple/common thing, add tags to posts. But apparently its too not a piece of cake. So i have a posts model and a tags models (may to many relation) . I want the user to be able to update and create the posts model. when creating or updating posts he should be able to update the tags of the posts. When a post is tagged with a new tag, that tag should be created if it dosent exist. Also i want to user to be able to specify the tags as a list of strings in the request. Example request { "name": "testpost1", "caption": "test caption", "tags": ["tag1", "tag2"], }, models.py class Tags(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(max_length=50, unique=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created_tags") class Posts(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(max_length=50) caption = models.TextField(max_length=1000) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') tags = models.ManyToManyField('Tags', related_name='posts') serializers.py class TagsSerializerMini(serializers.ModelSerializer): created_by = serializers.PrimaryKeyRelatedField(default=serializers.CurrentUserDefault(), queryset=User.objects.all()) class Meta: model = Tags fields = ('name', 'created_by') extra_kwargs = { … -
HTML in PDF on the server side for the dynamic page (already rendered)
There was a need to send a dynamic page to PDF in Django proj. Can someone give an example in which an already rendered page is sent to print. In this example, the page is native and static. Can I somehow remodel so that the rendered page is sent to the PDF. I tried to do this on the client side, but all the options that I used either do not support Cyrillic (jsPDF and others) or can not convert html (PDFmake and others). So I decided to look in the direction of the server side but all the examples that I found use a static html pointing to it. Can eat any ways through ajax requests, etc. -
How to modify Celery Backend database table celery_taskmeta and add data in new columns
I am using my postgres database as celery backend using this result_backend = 'db+postgresql://scott:tiger@localhost/mydatabase' I wanted to add more columns in the predefined table celery_taskmeta like the task_user which would have info on who created the task from user model in django. I have added this in class Task task_user = sa.Column (sa.String(255), nullable=True) This column is added to the table when I run the task but I don't know how to populate this column and where. right now its populated with null against all tasks. -
How to add inline Models in admin Interface [Django]
I am trying to add an inline model to a Post model. As the docs says, i am trying to do something like: models.py from django.db import models class images(models.Model): image = models.ImageField(upload_to='images/') class Post(models.Model): Title = models.CharField(max_length=60) Images = models.ForeignKey(images) admin.py from django.contrib import admin from . import models class ModelInlinePost(admin.TabularInline): model = models.images class ModelPost(admin.ModelAdmin): view_on_site = False inlines = [PythonInlineAdmin,] Now, whenever i try to execute a command with manage.py. It throws back this error: python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: <class 'home.admin.ModelInlinePost'>: (admin.E202) 'home.Post' has no ForeignKey to 'home.images'. -
Factory Boy - relate two SubFactories
Say I've got a factory that has two SubFactories which need to be related. What hook(s) does FactoryBoy provide either pre/post generation to associate these SubFactories? class AppointmentFactory(factory.DjangoModelFactory): class Meta: model = Appointment team_member = factory.SubFactory(TeamMemberFactory) merchant_location = factory.SubFactory(MerchantLocationFactory) Inspecting what gets created in a shell session yields a theoretically invalid object - a team member from a different location. > appt = AppointmentFactory.create() > > print(appt.merchant_location) > <MerchantLocation: object (3)> > > print(appt.team_member.merchant_location) > <MerchantLocation: object (4)> -
The view blog.views.post_list didn't return an HttpResponse object. It returned None instead (Django)
I'm having some problems with getting my Django based blog to display. When running the Django web server in debug mode I'm getting the following error message: The view blog.views.post_list didn't return an HttpResponse object. It returned None instead (Django) It only happens when I'm trying to access my blog application. Other templates are rendering fine. I would be very much grateful for your assistance. Here's the stack trace below: Environment: Request Method: GET Request URL: http://Some_URL Django Version: 2.0.4 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'blog', 'markdown', 'taggit'] 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/python3.5/dist- packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.5/dist- packages/django/core/handlers/base.py" in _get_response 139. "returned None instead." % (callback.__module__, view_name) Exception Type: ValueError at / Exception Value: The view blog.views.post_list didn't return an HttpResponse object. It returned None instead. Here's a partial extract from my views.py file of the definition which seems to be causing the problem: def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: … -
the right way to post data into api when using a rest framwork api
what is the best method to insert data into database when we use a rest framwork api I have tried the requests.post but it doesnt work because i use session authentification so what is the best method to post data into api using django i've already found some code with jquery but it doesnt work (i wanna use django not jquery) -
How to count using a conditional in Django?
Let's say we have the following simplistic models: class Category(models.Model): name = models.CharField(max_length=264) def __str__(self): return self.name class Meta: verbose_name_plural = "categories" class Status(models.Model): name = models.CharField(max_length=264) def __str__(self): return self.name class Meta: verbose_name_plural = "status" class Product(models.Model): title = models.CharField(max_length=264) description = models.CharField(max_length=264) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10) status = models.ForeignKey(Status, on_delete=models.CASCADE) Status choices would be: Sold, Not Sold, Reserved, Withdrawn. My aim is for each category to get the total amount of products and how many were Sold or Reserved as a percentage of the total per category: qs = Product.objects.all().values("category__name").annotate(total_products=Count("id"), total_available=Cast((Count(Case(When(status__name__in=["Sold", "Reserved"], then=True), output_field=BooleanField())) / Count("id")) * 100., FloatField())) For some categories returns the correct result and for others it does not. -
Viewing ForiegnKey data in Django
I want to create a view that displays data from a foreignkey in Django. I have some barbers that are available on certain dates and I want to see which dates a barber is available on. Later I need to know which barbers are available on which dates. models.py from django.db import models from datetime import time class Barber(models.Model): BARBERS = ( ('KK', 'Kim Kardashian'), ('CJ', 'Caitlin Jenner'), ('KW', 'Kanye West') ) LOCATION = ( ('CL', 'Central Detroit'), ('NL', 'North Detroit'), ('SL', 'South Detroit'), ('EL', 'East Detroit'), ('WL', 'West Detroit'), ) name = models.CharField(max_length=2, choices=BARBERS) location = models.CharField(max_length=2, choices=LOCATION) def __str__(self): return self.name class Date(models.Model): date = models.DateField() name = models.ForeignKey(Barber, on_delete=models.CASCADE) urls.py in my app from django.urls import path from .views import schedule, appointments urlpatterns = [ path('', schedule, name='schedule'), path('/appointments/<int:id>/', appointments, name='appointments') views.py from django.shortcuts import render, redirect from .models import Barber, Date def schedule(request): barber = Barber.objects.all() return render(request, 'schedule.html', {'barber': barber}) def appointments(request, name): dates = Date.objects.filter(name=name) return render(request, 'appointments.html', {'date': dates}) appointments.html <h1>Appointments</h1> <ul> {% for date in dates %} <li> {{ date.name }} {{ date.dates }} </li> {% endfor %} </ul> The error I get is: Reverse for 'appointments' with arguments '('',)' not found. … -
how to combine SearchQuery using & operator in Django postgres for uncertain multiple keywords comming from form field
So basically i have a form that has two fields(title, skills)that takes keywords separated by commas. and we want to provide a search for all the skills using SearchQuery and '&' operator.so if my search_vector is SearchVector('job_title',) and suppose user is looking for Ex. Java,python,.net as skills we can write our query something like.. PostedJobReq.objects.annotate(search=search_vector).filter(SearchQuery('java') & SearchQuery('python') & SearchQuery('.net')) should and does give us result. But my case is that we are getting keywords like Ex. Java,python,.net from Formfield so we don't know how many keywords user is going to search for. and what are those keywords going to be. so how am i suppose to concatenate multiple SearchQueries together when i don't even how many keywords user is going to search for.. I successfully made a list of all the SearchQueries but i am not able to concatenate them using & module in the code. Can someone please suggest me any solution i spent my whole day looking for solution but i got none so far. Please check below for the code that i am using.. views.py- This is how my views.py looking complexadvsearch.html-->Template<--This is how my template looks and holding a search form Models.py --> this is how … -
Print the table from the admin panel
Can anyone know the way to send a page with model records in the Admin panel? Maybe ready-made solutions? I'm trying to do this in a simple way window.print(), but this requires customizing the page styles (I really do not want to dig into the admin template). -
how to get nested list from django
Im working with python django, I have json field in my table, in this field there is some nested lists, when I'm trying to get the data from the table with: Books.objects.all() it returns only the first place of the nested list. for example: json field from my table: { "mean": [ [ [ [ 2.4055 ], "0.0360" ], "0.0568" ], "0.0360" ], "time": [ [ [ 0.0255, 2.7707 ], "0.0464" ], "0.0568" ] } i only get this: mean:2.4055, time: [0.0255,2.7707] how can i get all the data and not only the first element? thanks. -
Django rest auth register user as an admin
I am using Django rest auth and allauth to login and register users. I can register users by sending username, email, pwd1, pwd2. It is successful. I am wondering, how can I register a user as an admin, do I need to send any extra parameter? -
Django/RestFramework: how to get data from model that has on foreign key in it
I have two models as class Shops(models.Model): shopkeeper = models.ForeignKey(Shopkeeper, on_delete=models.CASCADE) name = models.CharField(max_length=250) category = models.CharField(max_length=250) contactNumber = models.IntegerField() address = models.CharField(max_length=500) dateCreated = models.DateTimeField(auto_now_add=True) and class Product(models.Model): productsubcategory = models.ForeignKey(ProductSubCategory, on_delete=models.CASCADE) shop = models.ForeignKey(Shops, on_delete=models.CASCADE) title = models.CharField(max_length=250) price = models.IntegerField() image = models.FileField(null=True) detail = models.TextField() quantity = models.IntegerField() dateCreated = models.DateTimeField(auto_now_add=True) I have made serializer class for product model. And I want to write a View which should return products of a specific shop. My view is as follow, class ShopkeeperProductAPIView(generics.GenericAPIView): def get(self,request,shop_id): products = Product.objects.get(shop=shop_id) products_serializer = ProductSerializer(products, many=True) return Response(products_serializer.data) and my url is as follow, path('shops/products/<int:shop_id>', views.ShopkeeperProductAPIView.as_view()) Please help me out. -
ReactJS & Django : How can I send csrf token with axios in a proper way?
I'm pretty new to using ReactJS with Django. What I want is simple. I want to send a request to make an account. Front-End server and the Back-End server are completely divided. They only communicates with AJAX, and nothing more, they're not even in the same server. I tried several ways to send a request to make an account, and nothing worked. The ways are : on JS : 1. add an option called "withCredentials:true" on axios -> this adds cookie on header, but django says 'csrftoken incorrect or not set." 2. set axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = 'csrftoken'; -> this doesn't make any effects. 3. set axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN' : (document.cookie).replace("csrftoken=", "") }; -> this makes axios to make only "option" method requests. but I don't know why and of course, this doesn't work. on Django's settings.py : CSRF_COOKIE_NAME = "X-CSRFToken" CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_EXPOSE_HEADERS = ( 'Access-Control-Allow-Origin: *', ) Is there any way to fix this? I spend a lot of my time for this. I REALLY need your help. thanks. -
Django Migration, cant find `User` field
class Tld(models.Model): #TODO...resolve `User` table issue for FKtoClient #other fields FKtoClient = models.ForeignKey('User', on_delete=models.PROTECT) When I try to run: python ../manage.py makemigrations Myapp it says : Myapp.Tld.FKtoClient: (fields.E300) Field defines a relation with model 'User', which is either not installed, or is abstract. Myapp.Tld.FKtoClient: (fields.E307) The field Myapp.Tld.FKtoClient was declared with a lazy reference to 'Myapp.user', but app 'Myapp' doesn't provide model 'user'. How can I resolve this? Thank you. -
Adapting Regular Expression in Django URL to match filepath
So I am currently working on a web application that takes as input the location of a malware file for one of the functions. This is passed via the views file. However after some altering of the models section of the application I found it was unable to parse the full filepath. The code below works for the following pcap as input: 8cdddcd3-35fa-468d-8647-816518a9836a435be1c6e904836ad65f97f3eac4cbe19ee7ba0da48178fc7f00206270469165.pcap url(r'^analyse/(?P<pcap>[\w\-]+\.pcap)$', views.analyse, name='analyse'), However this code no longer works when it is a pcap containing the full filepath. /home/freddie/malwarepcaps/8cdddcd3-35fa-468d-8647-816518a9836a435be1c6e904836ad65f97f3eac4cbe19ee7ba0da48178fc7f00206270469165.pcap Any suggestions or pointers on how exactly I would alter the regular expression to accomodate the full filepath in the string being passed to the route would be very much appreciated. -
django reading file from root: FileNotFoundError
Django 1.9: I am trying to open and read a file in a views.py function. I am getting a FileNotFound error, however I think the path is correct. I have put the file in the root: C:. | file1.txt | settings.py | urls.py | wsgi.py | __init__.py | I have the following in my settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) In my views I am trying to open the file with the following line: def post(self, request): file_ = open(os.path.join(settings.BASE_DIR, 'file1.txt')) But this error occurs: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\x\\y\\z\\Year 4\\Semester 2\\cvCleaner\\cvcleaner\\file1.txt' Is it to do with having spaces in my directory names? I'm not sure. -
Use JS library with Django
I have a problem using a js library with django. I am trying to use the particle.js library to generate a particle background for the home page and I have tried following this tutorial. I have created a home.html, particle.json and style.css in my templates folder. home.html <!-- templates/home.html --> {% load socialaccount %} {% load account %} {% load static %} <head> <link rel="stylesheet" href="style.css"> </head> <body> <div id="particles-js"> {% if user.is_authenticated %} <p>Welcome {{ user.username }} !!!</p> <a href="/accounts/logout/" >Logout</a> {% else %} <a href="{% provider_login_url 'github' %}">Log In with Github</a> <a href="{% provider_login_url 'twitter' %}">Log In with Twitter</a> <a href="{% provider_login_url 'facebook' %}">Log In with Facebook</a> <a href="{% provider_login_url 'linkedin' %}">Log In with LinkedIn</a> {% endif %} </div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', 'particles.json', function(){ console.log('particles.json loaded...'); }); </script> </body> When i start the server, all i can see are my log in buttons without the background image. It doesn't show any errors and it never prints the message in the console. I just started learning about django so I realize this might be a stupid question. Any idea what might be going wrong here? -
python djagno: images are not getting visible while accessing html template
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/linkedin_logo.png Using the URLconf defined in BupinderYadav.urls, Django tried these URL patterns, in this order: ^admin/ ^$ The current path, linkedin_logo.png, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Django: foreign key form input
Is it possible to have a form field that allows you to choose from existing instances (I apologize if instance is the wrong word) of a model or add a new one? For example, in an image sharing app, there may be an image upload page. When uploading, you can choose an existing tag to assign to the image or create a new one. The models could be image and tag, with image having a tag attribute that has a foreign key connecting it to tag. -
Django cannot import module after deployment
I transferred my Django project to another server and did the following steps. Took a list with installed python modules on my virtual environment with pip freeze > requirements.txt Transfered my project folder with scp (from one server to another) Created a virtual environment with mkvirtualenv Installed the requirements with pip install -r requirements.txt in my virtual environment Double-checked the modules, one by one, to verify they all are in the same version Tried to ./manage.py runserver and ./manage.py runworker and got "cannot import name patterns" So, I have the same modules installed, at the same version, with the same version of Django and it throws me an import error about "patterns" module, the same time that it is working correctly on the previous server with exactly the same modules installed. I am struggling for three days now, I also did the whole process from the beginning to make sure I don't forget anything. Any direction will be totally appreciated. -
Django 2.0 : Application labels aren't unique, duplicates: auth
I've got this error after I tried to migrate my files PS C:\djangoproject\src> python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management__init__.py", line 347, in execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 93, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth Please help. -
How can i pass a message to a page while submitting a form?
When i submits the form i want to pass message as "form successfully submitted" to the same page "successs.html".How it possible? class SuccessView(FormView): template_name = 'success.html' form_class = QuestForm success_url='success' def form_valid(self, form): ob9=Logs.objects.all() for i in ob9: logids=i.id str(logids) q1= form.cleaned_data['ques'] obj1=Quest.objects.create(logid=logids,status=0,question=q1) return super(SuccessView,self).form_valid(form) -
Django import_export error in exporting with foreignkey
I am trying to import a data set using import_export. There in one column in the data set that is based on the foreignkey (by actual "item_sku" value, rather by its "id") from another model. However, it keeps giving me the following error: "Line number: 1 - Model_Model01 matching query does not exist. " How can I fix this? I have been referring to the following sources: source 01 and source 02, but the issue still persists. Here are my codes: Models.py from django.db import models class Model_Model01(models.Model): item_sku = models.CharField(max_length = 2, null = False, blank = False) def __unicode__(self): return self.item_sku class Model_Model02(models.Model): item_sku = models.ForeignKey(Model_Model01, on_delete = models.CASCADE, null = True, blank = False) def __unicode__(self): return self.item_sku admin.py from import_export import fields from import_export.admin import ImportExportModelAdmin from import_export.widgets import ForeignKeyWidget from .models import (Model_Model01, Model_Model02) class Admin_Model02(ImportExportModelAdmin): item_sku = fields.Field( column_name = "item_sku", attribute = "item_sku", widget = ForeignKeyWidget(Model_Model01, "item_sku") ) class Meta: model = Model_Model02 admin.site.register(Model_Model02, Admin_Model02)