Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reduce selecting field for database performance when calling instance dot field in django orm?
When need to check a field value of an instance when use dot(.) for accessing the field as follows. class store(models.Model): ........ is_open = models.BooleanField(defrault=False) ........ class User(AbstractBaseUser): ........ store = models.ForeignKey(Store) ........ I need to check the value of is_open in some API I do as follows, request.user.store.is_open In this case, django performs a select query with all fields but I only need the is_open field. How can I only select only a single field (is_open in this case) instead of selecting all fields? -
Django get possible recipes from table of ingredients
at the moment I have a project where I need to get possible recipes from a database. There is one table which contains ingredients each with an id of the recipe the model looks like this: class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipes', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True) amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' And the database looks like this (You can ignore the amount and unit columns). And there is another table which contains the ingredients which the user has and each with an id of the user. The model looks like this: class UserIngredient(models.Model): _id = models.AutoField(primary_key=True) user_id= models.IntegerField() ingredient = models.CharField(max_length=255, null=False) class Meta: managed = True db_table = 'UserIngredients' And my question is how can I get the id for all the recipes the user has the ingredients for? -
How can I render Foreignkey Data or fields in Vuejs with django rest framework?
I'm learning to use Vuejs with Django rest framework so don't mind me if you find this question ignorant. Let's say I have 2 models Class Department(models.Model): name = models.CharField(..) Class Subject(models.Model): subject = model.CharField(..) department = models.ForeignKey(Department, ...) and forms like these Class DepartmentForm(models.Model): Class Meta: model = Department fields = ['name',] Class SubjectForm(models.Model): Class Meta: model = Subject fields = ['subject', 'department'] So If we render SubjectForm in regular django template the department field within SubjectForm will be rendered as CharField with choices and that choices are the data that we input into DepartmentForm. My question is how can we do that in Vuejs? How can we get the data from the foreinkey and display it inside the form as choices as we do in regular django template? I have been trying to google it and haven't find any example for that yet. -
Replace Null value of django objects with default value
I would like to replace null value in my django objects with the default value : Example : class Buy(models.Model): created = models.DateTimeField(null=True, blank=True, editable=False,default=timezone.now) modified = models.DateTimeField(null=True, blank=True,default=timezone.now) name = models.CharField(null=True,blank=True, max_length=200,default='') Here is my script : for buy in Buy.objects.all(): for f in Buy._meta.get_fields(): field = eval("buy." + f.name+" is None") if field: field = Buy._meta.get_field(f.name).get_default() buy.save() but when i make a json export with dumpdata i still have "name" : null, in my json for a lot of objects instead of "name": "" . I don't understand my script for migrating the null value of my object to "" seems to be correct. Regards -
How to save and retrieve a file on Heroku server for a Django App?
I have an application which is supposed to overlay name and date on an image Certificate_0001.jpg stored locally to output a pdf certificate using the function download (response, name, date). The application is deployed on Heroku, works fine locally, but once deployed, the location of Certificate_0001.jpg changes which is why the function is unable to overlay text and generate a pdf. How can I find the location of files stored in heroku server so I can access them? I have more than 300 student objects in my models for whom this app will generate graduation certificates, which is why storing the image for each object is not sustainable. Rather, retreving their names and graduation dates, and superimposing them on one image is more doable and takes less space. Views.py def download (request, date, name): x = date.split(" ") date = f"29 {x[3]} {x[4]}" try: image = Image.open("certificates\static\certificates\Certificate_0001.jpg") except: return HttpResponse ("image did not load") font_type = ImageFont.truetype('arial.ttf', 70) font_type_2 = ImageFont.truetype('arial.ttf', 35) draw = ImageDraw.Draw(image) draw.text(xy=(600, 740), text=name, fill=(0,102,0), font=font_type) draw.text (xy=(330, 1230), text=date, fill=(0,102,0), font=font_type_2) try: image.save(f'certificates\static\certificates\{name}.pdf', "PDF", resolution=100.0) except: return HttpResponse("pdf did not save") try: with open(f'certificates\static\certificates\{name}.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = f'inline;filename=NFDP-{name}.pdf' return … -
how can I change alowed host to mysite.com:8000
I want to open mysite.com:8000 but I cant!!!! what should I do? settings.py DEBUG = True ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1'] -
Django/React Deployment only works if I set DEBUG=True & STATICFILES_DIRS not a list
Trying to deploy my react frontend with django backend to pythonanywhere (PA) but get the following outcomes with the below 3 settings: DEBUG=True, STATICFILES_DIRS=[os.path.join(BASE_DIR, 'build/static')] - (Blank white screen) PA server log: File "/home/coot3/.virtualenvs/venv/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not list Chrome console: Refused to execute script from 'http://mysite.pythonanywhere.com/static/js/main.446b4eaa.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. DEBUG=True, STATICFILES_DIRS=os.path.join(BASE_DIR, 'build/static') - (Website works as intended) DEBUG=False, STATICFILES_DIRS=os.path.join(BASE_DIR, 'build/static') - (Blank white screen) No issues in PA Server log Chrome console: Refused to execute script from 'http://mysite.pythonanywhere.com/static/js/main.446b4eaa.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I have the react app build folder in my django root folder and link to reacts index.html as a template view in urls.py. Here is my settings.py: from pathlib import Path import os import environ env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() DEBUG = False SECRET_KEY = env('SECRET_KEY') BASE_DIR = Path(__file__).resolve(strict=True).parent.parent HOSTS = ['coot3.pythonanywhere.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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 = 'mysite.urls' TEMPLATES … -
Proper way to make advanced search in django
After reading and testing many posts, answers and tips, I decided to write down the way I made my search in my Django project to help others. It's in hungarian. models.py First thing fist, I have a model (called Igeny)with multiple attributes: class Igeny(models.Model): Cim = models.CharField(max_length=150, verbose_name="Igény címe") Igenylo = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Igénylő", blank=True, null=True) Igenyles_tartalom = models.TextField(verbose_name="Igénylés leírása") Status = models.IntegerField(default=0, verbose_name="Igénylés status") Allapot = models.CharField(default="Piszkozat", max_length=255, verbose_name="Igénylés állapota") UID = models.CharField(max_length=150, default="") Email = models.EmailField(default="xyz@xyz.hu") Phone = models.CharField(max_length=50, default="", null=True, verbose_name="Telefonos elérhetőség") Indoklas = models.TextField(default="", verbose_name="Igény indoklása") views.py In the views.py, fist I filtered the list of results with the Q object, then passed the results to a self created filter called IgenyFilter: def search_results(request): igeny_list = Igeny.objects.filter(Q(Ugyvezeto=request.user.profile) | Q(BeszerzesVezeto=request.user.profile) | Q(Igazgato=request.user.profile) | Q(EgysegVezeto=request.user.profile) | Q(Igenylo=request.user)).order_by('Status') igeny_filter = IgenyFilter(request.POST, queryset=igeny_list) igeny_lista = igeny_filter.qs.order_by('-Cim') return render(request, 'catalog/search_results.html', {'filter': igeny_filter, 'igeny': igeny_lista}) For this IgenyFilter, I made a filter.py: filter.py class IgenyFilter(django_filters.FilterSet): Cim = django_filters.CharFilter(field_name="Cim", lookup_expr='icontains', label='Igény címe (tartalmazza)') # Mindet listázza, amiben benne van a beírt szó Igenyles_tartalom = django_filters.CharFilter(field_name="Igenyles_tartalom", lookup_expr='icontains', label='Igénylés tartalma (tartalmazza)') # Mindet listázza, amiben benne van a beírt szó Igenylo = django_filters.CharFilter(field_name="Igenylo__first_name", lookup_expr='icontains', label='Igénylő neve') # Mindet listázza, amiben benne van a beírt szó … -
Displaying docker image tag/version inside Django frontend
I want to display the latest tag of my app's docker image on the frontend of my django application so that the users see the same app version as tagged in the docker image. Any ideas on how to achieve this? -
how to rewind or forward video on html
<!DOCTYPE html> <html> <body> <video width="1000" height="500" poster = "/media/4x3.jpg" autoplay muted loop playsinline controls> <source src="/media/11.mp4" type="video/mp4"> Your browser does not support HTML video. </video> <a href="/media/test.pptx" download><p>Download</p></a> </body> </html> i use this code but cannot rewind or forward the video. -
In django, login page content is not displaying only navbar is visible
Screenshots: Login Page screenshot Login Page html code Project level url file base.html page which contains the login link in navbar -
Cannot assign content_type" must be a "ContentType" instance
I am trying to implement a comment system to my blog, but have been getting an error when tying to assign content_type to the initial data thats going with the comment.. i have my sample code below #Comment app model class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE) content = RichTextField() #Blog app model class Song(models.Model): ... ... @property def get_content_type(self): content_type = ContentType.objects.get_for_model(self.__class__) return content_type #Blog Views class SongDetail(ModelFormMixin, DetailView): model = Song form_class = CommentsForm def get_initial(self): obj = self.get_object() return { 'content_type': obj.get_content_type, 'object_id': obj.object_id } def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('music:obj.get_absolute_url()') form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) -
Django: How to access session data from views.py created outside of views.py
I need to pass a jwt token generated in backend.py to views.py. In backend.py i save it like this: s = SessionStore() s['id_token'] = id_token s.create() key1 = s.session_key in views.py i try to get the session_key from that session like key2 = request.session.session_key But the two keys differ. What am i doing wrong and how can i access s['id_token'] in views.py? -
How to store data from YAML file in django model
I know it is possible to store YAML data in the Django model using the JSON field. However, I would prefer to use the Django model instead of a JSON field. The reason being that when I store as JSON blob, I can query it although it might be harder to do considering I don't have a schema making it a bit messy when I need to change something later e.g when I add a new field to the YAML files, with normal Django model, this is easy to do with migration. But with JSON, it can be a bit harder. So I need help on how I can use a Django model with different fields instead of a JSON field -
The view acc_app.views.merchant_messages didn't return an HttpResponse object. It returned None instead
Here I'm creating a chat system between merchants and admin, but every time I send a message via form it's showing this error. Request Method: POST Request URL: http://127.0.0.1:8000/merchant-dashboard/messages/ Django Version: 3.1 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'acc_app', # app 'widget_tweaks', 'rest_framework'] Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 186, in _get_response self.check_response(response, callback) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 307, in check_response raise ValueError( Exception Type: ValueError at /merchant-dashboard/messages/ Exception Value: The view acc_app.views.merchant_messages didn't return an HttpResponse object. It returned None instead. MyCode views.py @csrf_exempt def message_list(request, receiver=None): .... elif request.method == 'POST': # message = request.POST['message'] # admin = UserAccount.objects.get(is_superuser=True) # send_message = Message.objects.create(sender=request.user, receiver=admin, message=message) # send_message.save() serializer = MessageSerializer(data=request) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @login_required(login_url='login-user') def merchant_messages(request): if request.method == "GET": message_list(request, receiver=request.user) admin = UserAccount.objects.get(is_superuser=True) all_messages = { 'receiver': UserAccount.objects.get(email=admin), 'messages': Message.objects.filter(sender=admin, receiver=request.user) | Message.objects.filter(sender=request.user, receiver=admin) } return render(request, 'dashboard/merchant/message-task.html', all_messages) HTML file <form method="POST" id="chat-box"> {% csrf_token %} <div class="input-group"> <input name="message" typetype="text" class="form-control" placeholder="Enter Message"/> <span class="input-group-btn"> <button class="btn btn-success" type="submit">SEND</button> </span> </div> </form> It works fine to show the received messages, but can't … -
Model assignment in Django
I have a question regarding Model-Assignment in Django. I have a Model Field where i can add an amount of pieces of a product. I want to be able to assign for example 100 pieces of the product to diffrent locations in the warehouse. For example: Product A = 100 pieces. 30 pieces are linked to warehouse 1 30 pieces are linked to warehouse 2 40 pieces are linked to warehouse 3 how would you solve this problem? I'm kinda new in python & django. Best Regards, Marcel -
Python/Django loop optimization
i am currently working on a Django website and at a certain point need to generate a dataset for a graph out of model data. Over the last days i have been trying to optimize the code to generate that data, but its still relatively slow with a dataset which will definetely get a lot larger when the website is up. The model i am working with looks like this: class Prices(models.Model): name = models.CharField(max_length=200, blank=False) website = models.CharField(max_length=200, blank=False, choices=WEBSITES) date= models.DateField('date', default=date.today(), blank=False, null=False) price = models.IntegerField(default=0, blank=False, null=False) class Meta: indexes = [ models.Index(fields=['website']), models.Index(fields=['date']) ] It stores prices for different items(defined by the name) on different websites. For the graph representation of the model I need two arrays, one with all the dates as the y-Axis and one with the prices of the item at that date(which might not be available, not every item has a date entry for every day on every website). And all of that for every website. My code for generating that data looks like this atm: for website in websites: iterator = Prices.objects.filter(website=website).iterator() data = [] entry = next(iterator) for date in labels: if entry is not None and date == … -
Django ckeditor paste images without text
I am using django-ckeditor with the Image plugin. I wish to copy-paste some equations from MS-Word into the ckeditor as an image. The issue is that the equation related text also appears beside the image. Is there any way to only show the image? Please note that I am not using the Paste from Word plugin nor am I interested in Mathjax plugin. I tried using the Paste from Word plugin along with this workaround but it had no effect. The image part only appears when I'm using the Image plugin. -
ReactJS form submit this.props.history.push('/downloads') not linking through to the new page
I am trying to Push to a new page once a user has filled out a form using this.props.history.push inside the function below. handleSubmit = async event => { event.preventDefault() try { const res = await newEnquiry(this.state.formData) this.props.history.push('/downloads') console.log(res) } catch (err) { console.log(err.response.data) } } The ReactJS form is working fine on the /contacts page, and submits information to my Django back-end so I know it's working OK, however I cannot get the redirect to work and it's giving me this error message. <form onSubmit={this.handleSubmit}> is inside my form tag and that's working fine so I am pretty sure it's not a problem with my form. -
How I can count values in Django?
I am trying to count data from the table, I have a relation between 2 tables and I want to display records after the count in the Django template, Please let me know how I can display count values in Django. here is my Html file code. {% for a in product.GetRelatedname.all %} {{a.test_data_id.count}} {% endfor %} but its counting nothing ` -
Publishing my Djangoapp on pythonanywhere.com
The error im getting in my wsgi.py: Error running WSGI application ImportError: cannot import name 'application' File "/var/www/ufuck7_pythonanywhere_com_wsgi.py", line 43, in from todo import application # noqa -
django ForeignKey relation how to get data other tables
I have 3 models class product(models.Model): name = models.CharField(max_length=30) class order(models.Model): order_number = models.CharField(max_length=30) class order_products(models.Model): order_id = models.ForeignKey(order,null=True) product_id = models.ForeignKey(product,null=True) One order has multiple products is this relation is correct and if it is correct then if i get all the order then how can i get it related product data? -
Pass initial argument from django to django dash app
I want to pass a variable from django view to DjangoDash application. In details, I want to use the id that I receive from get method in Django view to the DjangoDash in order to make some plots with filtered data based on that id. I followed this approach https://github.com/GibbsConsulting/django-plotly-dash/issues/173 which was very helpful, but still can't have access of the variable in the DjangoDash. views.py def getID(request): queryid= request.GET['queryid'] context = {'data':{"query_id":queryid}} template_name="djangoDash.html" return render(request, template_name, context) In order to use the DjangoDash Plotly I used this with initial argument the content data from the view. djangoDash.html ..... {% plotly_app name='djangoDash' ratio=0.45 initial_arguments=data %} .... When I define the djangoDash app I use this app = DjangoDash('djangoDash', id='query_id', serve_locally=False, suppress_callback_exceptions=True) And I use this id as an input over my layout to use it for the queries with the bellow callback. layout = html.Dic([ dcc.Input(id='query_id'), html.Div(id='result'), ]) @app.expanded_callback(dash.dependencies.Output('result', 'children'), [dash.dependencies.Input('query_id', 'value')]) def display_output(query_id): result= query_id return result The error I get when I load the page is File "/home/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", … -
Django Ajax Dynamic variable Uncaught ReferenceError
I am trying to send some variable from textarea to django view via Ajax. I am getting this error. Uncaught ReferenceError: saveLinks is not defined at HTMLButtonElement.onclick ((index):794) Also, I could return variables in for loop my Spider.id variable keep sending "1". View.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt def saveLinks(request): if request.is_ajax(): id = request.GET.get('spider_id') p1 = get_object_or_404(Spiders,id = id) files = request.GET.get('text') files = files.replace("https://"+p1.spider_url+"/","") files = files.split(";") for file in files: new_data = Urls(spider_id=int(p1.id),url_tag=file) new_data.save() return redirect(request.META['HTTP_REFERER']) index.html {% for spider in spiders%} <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Yeni Linkler</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="recipient-name" class="col-form-label">Market : {{spider.spider_name}}</label> </div> <div class="form-group"> <label for="message-text" class="col-form-label">Linkler</label> <textarea rows=15 class="form-control" name="id_amount" id="id_amount"></textarea> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Kapat</button> <button type="button" class="btn btn-primary" value="id_amount Links" onclick="saveLinks({{spider.id}})">Save</button> </div> </div> </div> {% endfor %} Ajax - script function saveLinks(output) { var text = document.getElementById('id_amount').value; jquery.ajax({ method: 'GET', url: '{% url ' Bot: saveLink ' %}', type: 'GET', data: { 'text': text, 'spider_id': parseInt(output) }, dataType: 'text', success: function () { location.reload(); } }).done(function (data) { console.log('SUCCESS') }).fail(function (xhr, text, error) { console.log(text, error) }); } … -
Automatically search all fields for all models in django admin
I want to be able to search all models for all fields in Django admin, without having to setup ModelAdmin and searchfields individually. example: I have all my models in model.py: # This is an auto-generated Django model module. from django.db import models class Diagnosis(models.Model): id = models.BigAutoField(primary_key=True) code = models.CharField(max_length=255) starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis' def __str__(self): return 'Diag #' + str(self.id) + ' - ' + self.code class DiagnosisHistory(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) id_user = models.TextField(blank=True, null=True) report = models.TextField(blank=True, null=True) json_report = models.TextField(blank=True, null=True) vin = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'diagnosis_history' # and so on and the admin.py where I register the models: from django.contrib import admin from . import models # Do not care. Register everything for cls in [cls for name, cls in models.__dict__.items() if isinstance(cls, type)]: admin.site.register(cls) I don't want to run through each Model and manually create a ModelAdmin with each field