Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Haystack search does not show result
It seems like when I use haystack in django it went malfunction, every time I search something it does not show any result. When haystack search cannot find the match, the result shows that 'No result found' normally, like I randomly typed some words or numbers. But when I type something that definitely in the database, the result part return nothing. I read the tutorial of haystack carefully, and I am sure I did every single step according to the tutorial and installed haystack correctly. My models: class Genes(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Genes' class Metabolites(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True,unique=True) compartment = models.CharField(max_length=255, blank=True, null=True) charge = models.CharField(max_length=255, blank=True, null=True) formula = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Metabolites' class Reactions(models.Model): id = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) metabolites = models.TextField(blank=True, null=True) lower_bound = models.CharField(max_length=255, blank=True, null=True) upper_bound = models.CharField(max_length=255, blank=True, null=True) gene_reaction_rule = models.TextField(blank=True, null=True) subsystem = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Reactions' search_indexes.py: from haystack … -
Users to only view pages owned in wagtail admin
Is there a way to get a users to only view pages that they own in wagtail admin but superusers can still view all pages? -
Dnsmaq conflicts with regular internet connetion (ethernet)
i have a django server running on a desktop computer(linuxmint 18.3 64 bits), i use hostapd and dnsmasq to serve the django site in a local area via wifi(a room). desktop also have a regular Internet connection over Ethernet cable.(Internet access is NOT shared over wifi.) however while dnsmasq is running, the desktop is unable to connect to the Internet. i need to both serve the django site over wifi and been able to access the Internet at the same time. here are my configurations cat dnsmasq.conf except-interface=enp0s25 except-interface=lo interface=wlp48s0 dhcp-range=10.0.0.10,10.0.0.250,12h dhcp-option=3,10.0.0.1 dhcp-option=6,10.0.0.1 server=8.8.8.8 #log-queries #log-dhcp address=/#/10.0.0.1 listen-address=10.0.0.1 bind-interfaces cat hostapd.conf ap_isolate=1 interface=wlp48s0 #driver=nl80211 ssid=LOCALACCESSPOINT channel=6#0 #1 auth_algs=1 # 1=wpa, 2=wep, 3=both wpa=2 # WPA2 only wpa_key_mgmt=WPA-PSK rsn_pairwise=CCMP wpa_passphrase=123456789 also run a service every boot cat set_ip.service [Unit] Description=asignar ip a la tarjeta wifi After=multi-user.target [Service] Type=idle ExecStart=/bin/bash /home/mint/set_ip.sh [Install] WantedBy=multi-user.target cat set_ip.sh ifconfig wlp48s0 down sleep 2 ifconfig wlp48s0 10.0.0.1 up sleep 4 systemctl restart dnsmasq.service iptables -i wlp48s0 -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000 iptables -i wlp48s0 -A INPUT -p tcp --dport 22 -j DROP as soon as i call sudo systemctl stop dnsmasq.service im able to browse the Internet again. any … -
Following relationships “backward” TastyPie
I'm attempting to follow a relationship "backwards" with TastyPie, however I haven't quite managed to. The documentation doesn't really go into much detail and I've tried searching the web to no avail. I know in Django I could achieve it like this, but how do I achieve the same in TastyPie? My models.py looks like this: from django.db import models from django.contrib.auth.models import User class Gallery(models.Model): name = models.CharField(max_length=50) user = models.ForeignKey(User, on_delete=models.PROTECT) created = models.DateField() def __str__(self): return '%s %s' % (self.name, self.created) class Painting(models.Model): name = models.CharField(max_length=50) url = models.CharField(max_length=250) description = models.CharField(max_length=800) gallery = models.ForeignKey(Gallery, on_delete=models.PROTECT) published = models.DateField() def __str__(self): return '%s %s' % (self.name, self.published) class Comment(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) painting = models.ForeignKey(Painting, on_delete=models.CASCADE) content = models.CharField(max_length=500) published = models.DateField() def __str__(self): return '%s %s' % (self.content, self.published) And my resources.py looks like this: from tastypie.resources import ModelResource from api.models import Gallery, Painting, Comment from tastypie.authorization import Authorization from tastypie import fields from django.contrib.auth.models import User class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' class GalleryResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') #This does not work. paintings = fields.ToManyField( 'self', lambda bundle: bundle.obj.painting_set.all(), full=True) class Meta: queryset = Gallery.objects.all() resource_name = 'gallery' authorization … -
HTML CSS: Adding in new lines
I am following the tutorial/code described here. The specific code in question is this part: <!DOCTYPE html> <html lang="en"> <head> <title>Harrison Kinsley</title> <meta charset="utf-8" /> {% load staticfiles %} <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/> <meta name="viewport" content = "width=device-width, initial-scale=1.0"> <style type="text/css"> html, body { height:100% } </style> </head> <body class="body" style="background-color:#f6f6f6"> <div class="container-fluid" style="min-height:95%; "> <div class="row"> <div class="col-sm-2"> <br> <center> <img src="{% static 'personal/img/profile.jpg' %}" class="responsive-img" style='max-height:100px;' alt="face"> </center> </div> <div class="col-sm-10"> <br> <center> <h3>Programming, Teaching, Entrepreneurship</h3> </center> </div> </div><hr> <div class="row"> <div class="col-sm-2"> <br> <br> <!-- Great, til you resize. --> <!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#fff">--> <div class="well bs-sidebar" id="sidebar" style="background-color:#fff"> <ul class="nav nav-pills nav-stacked"> <li><a href='/'>Home</a></li> <li><a href='/blog/'>Blog</a></li> <li><a href='/contact/'>Contact</a></li> </ul> </div> <!--well bs-sidebar affix--> </div> <!--col-sm-2--> <div class="col-sm-10"> <div class='container-fluid'> <br><br> {% block content %} {% endblock %} </div> </div> </div> </div> <footer> <div class="container-fluid" style='margin-left:15px'> <p><a href="#" target="blank">Contact</a> | <a href="#" target="blank">LinkedIn</a> | <a href="#" target="blank">Twitter</a> | <a href="#" target="blank">Google+</a></p> </div> </footer> </body> </html> When I run this code, the links to 'Home', Blog' and 'Content' pages are all on one line, with no spaces between them (i.e. the links are like this: HomeBlogContent). I want them to look … -
404 Page Not Found: /ckeditor/browse/
In my admin interface (log as superuser) I'm able to write with CKEditor and also print my text on my templates. Unfortunately, I can't add picture, when I tried I get : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ckeditor/browse/?CKEditor=id_content&CKEditorFuncNum=1&langCode=fr Raised by: blog.views.ViewPost I suppose it is a MEDIA issue, because I get the same error message if I tried to access to my media, like so: http://127.0.0.1:8000/media/image/link urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.Index.as_view(), name='Index'), url(r'^about', views.About, name='About'), url(r'^contact', views.Contact, name='Contact'), url(r'^portfolio/', views.Portfolio, name='Portfolio'), url(r'^(?P<category_slug>[\w-]+)/(?P<post_slug>[\w-]+)/', views.ViewPost, name='Post'), url(r'^(?P<category_slug>[\w-]+)/', views.ViewCategory, name='Category'), url(r'^ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "blog/static/ckeditor"), os.path.join(BASE_DIR, "blog/static/admin"), os.path.join(BASE_DIR, "blog/static/web"), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'extraPlugins': ','.join([ 'uploadimage', # the upload image feature # your extra plugins here 'div', 'autolink', 'autoembed', 'embedsemantic', 'autogrow', # 'devtools', 'widget', 'lineutils', 'clipboard', 'dialog', 'dialogui', 'elementspath', 'image' ]), 'height': 900, 'width': 900, "removePlugins": "stylesheetparser", }, } AWS_QUERYSTRING_AUTH = False CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_RESTRICT_BY_DATE = True CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_UPLOAD_PATH = "post_img/" Models.py class Post(models.Model): title = models.CharField(max_length=200, default="") subtitle = models.CharField(max_length=200, default="", null=True) author … -
when I logout the app goes into a loop a 203 http status
I´m doing an exercise that involves user authentication. Everything works smooth, but when I log out the app goes into a loop with this message on the console: [04/Apr/2018 22:44:14] "GET /account/logged_out/ HTTP/1.1" 302 0 [04/Apr/2018 22:44:14] "GET /account/logged_out/ HTTP/1.1" 302 0 [04/Apr/2018 22:44:14] "GET /account/logged_out/ HTTP/1.1" 302 0 Project structure At the end of the settings.py file from django.urls import reverse_lazy LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard') LOGIN_URL = reverse_lazy('account:login') LOGOUT_REDIRECT_URL = reverse_lazy('account:logout') The urls.py file from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'account' urlpatterns = [ # path('login/', views.user_login, name='login'), path('', views.dashboard, name='dashboard'), # login / logout urls path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), The views.py file from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) The base.html template {% load staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{% static "css/base.css" %}"> </head> <body> <div id="header"> <span class="logo">Bookmarks</span> {% if request.user.is_authenticated %} <ul class="menu"> <li> {% if section == "dashboard" %}class="selected"{% endif %}><a href="{% url "account:dashboard" … -
select related and Q objects on already filtered queryset
I have a queryset that I get. Then depending on if certain things are true in my software I further filter the queryset. venuelist = Venue.objects.filter(approved=True, online=True) # intial queryset then if things are true or not I filter further. venuelist = venuelist.filter(venuetype__in=venuetypepklist) by my understanding __in is an OR operator not an AND I have a situation in which if something is true, I need to filter further but I need to filter the related sets of a venue object. I know we can do this with set related. But the thing I am checking could also be true in the actual venue object. example. I have a fullbuyout capacity option in my venue table. I also have a capacity option in each of the rooms a venue has. My filter should work where the venue is not filtered out if either the venues fullbuyout capacity value is greater than or equal to the user input capacity or one of the rooms capacity related to the venue is equal to or greater than the user inputed value. I am using Q objects and select query however it seems I am not doing it right, or really dont know what … -
Django : I am not able to open my virtual host domain on local machine
Below is my virtual host file: ServerAdmin webmaster@localhost DocumentRoot /var/www/html/jang/myblog WSGIScriptAlias /test /var/www/html/jang/myblog/myblog/wsgi.py WSGIDaemonProcess myblog.dev processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/html/jang/myblog/venv/lib/python2.7 WSGIProcessGroup myblog.dev <directory /var/www/html/jang/myblog> AllowOverride all Require all granted Options FollowSymlinks </directory> What is the issue with it? -
Can I sort items ignoring leading space in Django admin?
I'm working on a Django app that has many repeated items, except for a space, so the admin sorts it "wrong". I know the proper solution would be to whack some SQL and remove those spaces, but for the moment I'd like to help our users. Also I can't just yet since the name field is UNIQUE, etc etc. class Meta: get_latest_by = 'date_created' ordering = ['name'] // --> Can I do something with this, like name.strip()? -
Django testing form.is_valid()
My view have optional parameter in url. I pass this parameter (<int:jobNr>/None)to form in get_form_kwargs class AddHoursView(LoginRequiredMixin, generic.CreateView): form_class = AddHoursForm def get_form_kwargs(self): # pass "jobNr" keyword argument from current url to form kwargs = super(AddHoursView, self).get_form_kwargs() kwargs[JOB_PARAM] = self.kwargs.get(JOB_PARAM) return kwargs def form_valid(self, form): self.object = form.save(commit = False) # If url/jobNR take jobNr from URL, if not take from form try: jobNr = self.kwargs[JOB_PARAM] except KeyError: jobNr = form.cleaned_data[JOB_WORKER].jobNr job = models.Job.objects.get(jobNr = jobNr) jobWorker = models.JobWorker.objects.get_or_create(job = job, user = self.request.user) self.object.jobWorker = jobWorker[0] self.object.save() return HttpResponseRedirect(reverse('worktime:myjobs')) In form __init__ If url /foo/jobNr/ create self.jobNr with url parameter. If url /foo/ create new field. class AddHoursForm(forms.ModelForm): def __init__(self, *args, **kwargs): #Add jobworker field to from Worktime model if any jobNr pass in url #When in url will be parameter. Job foreignkey will be set by automat. self.jobNr = kwargs.pop(JOB_PARAM, None) super(AddHoursForm, self).__init__(*args, **kwargs) if not self.jobNr: self.fields[JOB_WORKER] = forms.ModelChoiceField(queryset=Job.objects.all()) def clean(self): cleaned_data = super().clean() date = cleaned_data.get('date') if self.jobNr: jobDate = Job.objects.get(jobNr=self.jobNr).start elif not cleaned_data.get(JOB_WORKER).start: raise forms.ValidationError("Dat work don't start yet") else: jobDate = cleaned_data.get(JOB_WORKER).start if date<jobDate: raise forms.ValidationError("Wrong date") return cleaned_data And now i want to code tests for a form. This is what i tried … -
Is there a way to have a field that only the superuser can add/edit?
Is there a way to have a field that only the superuser can add/edit? class ProductPage(Page): price = models.IntegerField(blank=True) description = RichTextField(blank=True) featured = models.BooleanField(default=False) Above is part of my model but i only want the superuser to access the featured field. -
django class list object and filtering lines
In Django I have a list of phone results. Here is a screenshot below: I am trying to query the list and get the result lines (like in querysets where I can use filter(condition). In my example I want to get phonetype=='Cep' lines. I can do it by a for loop and if condition; however if there is a more decent I want to learn it. Thanks. -
Rest API - token generate using Django and django-auth-toolkit
First of all I want to mention that I have limited knowledge in Django (new in this framework, however, familiar with programming in general). So, I want to create an Rest API (using django-rest-framework) and I want some endpoints (not all) to require authentication. For security reasons and I decided to go with OAuth2. I found a third party framework named django-oauth-toolkit. However, I was not able to make this work. I tried copy paste the example offered in the getting started section but I was not able to make it work. The main thing that its happening its that I'm redirected to 'ocalhost:8000/accounts/login/?next=/auth/o/authorize/'. From what I have read this its some common Django authentication behaviour(caused by @login_required decorator) but this its just retarded, I'm trying to get the token (so basically to login). Code: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'oauth2_provider', 'rest_framework', 'allauth', 'authManager', ] MIDDLEWARE = [ 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'oauth2_provider.backends.OAuth2Backend', ) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ) } urls.py: urlpatterns = [ url(r'^o/', include('oauth2_provider.urls')), ] Other relevant informations: Django version: 2.0.4, Python version 3.6 My obvious question is: How to get rid of /accounts/login … -
Selenium testing through xvfb-run, NoSuchElementException: Message: Unable to locate element
I am building a Django app using headless Selenium testing on a remote VPS to learn TDD. I was previously using pyvirtualdisplay in my functional tests, but this was leaving xvfb processes lying around after each test that ended up causing conflicts, so I removed pyvirtualdisplay from my code and started using xvfb-run for each test instead. This worked for a while, but now I'm encountering the following error: Traceback (most recent call last): File "functional_tests.py", line 39, in test_start_retrievable_list table = self.browser.find_element_by_id('id_list_table') File "/home/user/code/python-tdd-book/virtualenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 351, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/home/user/code/python-tdd-book/virtualenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 955, in find_element 'value': value})['value'] File "/home/user/code/python-tdd-book/virtualenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/home/user/code/python-tdd-book/virtualenv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="id_list_table"] Here's the functional test in question, up to and including the chunk of code where the error occurs: from selenium import webdriver from selenium.webdriver.common.keys import Keys import unittest import time class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_start_retrievable_list(self): self.browser.get('http://localhost:8000') self.assertIn('To-Do', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('To-Do', header_text) inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual( inputbox.get_attribute('placeholder'), 'Enter a to-do item' ) inputbox.send_keys('Buy peacock feathers') inputbox.send_keys(Keys.ENTER) time.sleep(1) table = self.browser.find_element_by_id('id_list_table') # Error here rows = table.find_elements_by_tag_name('tr') self.assertTrue( any(row.text … -
Django save uploaded file to disk
I'm trying to save a file to disk, not in a class or anything just straight to disk but I can't for the life of me figure out how. So far I've got: View: ` def uploadview(request): uploadtestvar='Uploadpage!' request.session['test']='Is this working?' if request.method == 'POST': form=UploadForm(request.POST, request.FILES) if form.is_valid(): forcetitle='test' try: pass except: pass return HttpResponseRedirect('/test/') else: form=UploadForm() return render(request, 'test/uploads.html',{'uploadtestvar':uploadtestvar, 'form':form})` Form stolen directly from Django: from django import forms class UploadForm(forms.Form): title=forms.CharField(max_length=50) file=forms.FileField() I've searched countless threads and found none that gives an example simple enough for me to understand how to get that request.FILES['file'] saved to disk somewhere. The possible filetypes are png, jpg, and pdf. -
nohup on server restart
I am using nohup to keep django running on a dev box. nohup python3.6 manage.py runserver 0.0.0.0:8888 & Is there a way to have this kick off if the server restarts. I have no linux scripting experience so seeking some help on the matter. -
Prepopulate django form leads to 'str' object has no attribute 'get'
I was trying to prefill django 2 form for updating a model def update_profile(request): if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('index') else: form = UpdateProfile(instance=request.user) return render(request, 'update_profile.html', args) But it leads to File "/usr/local/lib/python3.5/dist-packages/django/forms/widgets.py", line 254, in value_from_datadict return data.get(name) AttributeError: 'str' object has no attribute 'get' I have also tried UpdateProfile(initial=model_to_dict(request.user)) instead of UpdateProfile(instance=request.user) Any idea on how to fix this? -
Django 2 migrations AttributeError
I am getting AttributeError: 'NoneType' object has no attribute 'is_relation' issue while running migrate command for the first time. -
I am trying to do a ajax call with two buttons from my form to a django view
I am new ajax and Django and am trying to do a Ajax call with two buttons from my form to a Django view.The 'Add Employees' button will add the employees and 'Delete' will delete the employees, when I try to add/delete operation, the view is adding/deleting the employees from the data base, but the webpage is displaying the json object returned by my view is directly as a raw string. my .html page: <form action="{% url 'supervisor:manageproject' %}" id="my_form" method="post"> {% csrf_token %} <input type="hidden" name="project_id", value={{project.id}}> <div class="form-group row"> <label for="projectName" class="col-sm-2 col-form-label">Project Name</label> <div class="col-sm-10"> <input type="text" name="project" class="form-control-plaintext" id="projectName" value="{{project.project_name}}"> </div> </div> <h6>Manage the employees list:</h6> <p>Check the boxes to remove employees:</p> <div class="container" > <div class="row" > <div class="col-xs-6" > <table class="table" id = "change_form1"> {% for employee in employees_could_add.all %} <tr> <td><input type="checkbox" name="employees_inproject" value="{{employee.id}}"> {{employee}}</td> </tr> {% endfor%} <tr> <td><button class="btn btn-primary" name="Add_emp" value = "Add" type="submit">Add Employees</button></td> </tr> </table> </div> <div class="col-xs-6"> <table class="table" id = "change_form2"> {% for employee in project.employees.all %} <tr> <td><input type="checkbox" name="employees" value="{{employee.id}}"> {{employee}}</td> </tr> {% endfor%} <tr> <td><button class="btn btn-danger" name="Delete_emp" value="delete" type="submit">Delete</button></td> </tr> </table> </div> </div> </div> </form> my .js file with the ajax call: … -
How to hide some fields for response in Django Rest Framework
Another DRF newbie here. I want to hide some fields in response of my REST API. Let's say I have, some basic Exchange Service: serializers.py class ConversionSerializer(serializers.Serializer): value = serializers.FloatField() from_ = serializers.ChoiceField(choices=SOME_CHOICES) to_ = serializers.ChoiceField(choices=SOME_CHOICES) converted_value = serializers.SerializerMethodField(read_only=True) .... views.py class ConversionAPIView(APIView): serializer_class = ConversionSerializer permission_classes = [] def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) .... For my POST request I pass 3 values: value, from, to. And in response I get 4 values: value, from, to, converted_value. { "value": 100, "from_": "foo", "to_": "bar", "converted_value": 200 } Now, I want to get only converted_value in response instead of all fields. How to implement it? Thanks -
Django preventing duplicate records while importing csv
I am uploading csv file to django model, which is working fine with the below code def upload_csv(request): if request.method == 'POST' and request.FILES['csv_file']: myfile = request.FILES['csv_file'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) data = csv.reader(fs.open(filename, mode='r')) for row in data: if row[0] != 'FP_Item': post = FP() post.FP_Item = row[0] post.save() messages.success(request, "FP uploaded to Database") queryset_list = FP.objects.all() context = {'object_list': queryset_list} return render(request, 'index.html', context) What I need is to prevent duplicates entries to database. When I see duplicate field, I need to continue without saving with post.save() so I modified my code as per below but still saving even it's duplicate.What I am doing false ? for row in data: queryset_list = FP.objects.all() if row[0] != 'FP_Item': if row[0] == queryset_list.filter(FP_Item__contains=row[0]): continue post = FP() post.FP_Item = row[0] post.save() -
Django - how to get upload_to directory related to another field
I think the code speaks for itself. I have 2 models - Food and Category and I want to save the food images to a folder that has the same name as the category of the food. I was thinking that I could possibly override the save method but I can't figure out how to make it work. Any ideas? from django.db import models class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: verbose_name_plural = 'Categories' class Food(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete='CASCADE') image = models.ImageField(upload_to='{}'.format(category.name)) def __str__(self): return self.name -
Django not finding command when importing CSV data with Dictreader
I would like to use Python's Dictreader to import a csv file based on my Django model into the database. My post model is: class Post(models.Model): STATUS_CHOICES = ( ("draft", "Draft"), ("published", "Published") ); slug = models.SlugField(max_length=250); wine_id = models.IntegerField(); country = models.CharField(max_length=100); description = models.TextField(); designation = models.TextField(); price = models.FloatField(); province = models.CharField(max_length=100); region_1 = models.CharField(max_length=100); region_2 = models.CharField(max_length=100); variety = models.CharField(max_length=100); winery = models.CharField(max_length=100); objects = models.Manager(); class Meta: ordering = ("id",); def __str__(self): return self.variety; def get_absolute_url(self): return reverse("post_detail", args=[self.id, self.province, self.slug]); My script to read the csv data is: class Command(BaseCommand): # Shows this when the user types help: help = "Loads data from wine_data.csv into our Post model."; def handle(self, *args, **kwargs): if Post.objects.exists(): print("Wine data already loaded... exiting..."); print(ALREADY_LOADED_ERROR_MESSAGE); return; print("Loading wine data for WCC."); for row in DictReader(open("wine_data.csv")): post = Post(); post.wine_id = row["wine_id"]; post.country = row["country"]; post.description = row["description"]; post.designation = row["designation"]; post.price = row["price"]; post.province = row["province"]; post.region_1 = row["region_1"]; post.region_2 = row["region_2"]; post.variety = row["variety"]; post.winery = row["winery"]; post.save(); However, when I use "python manage.py load_wine_data", the cmd says it is an unknown command. What am I doing wrong and how can I solve it? -
Best practice when working with queries that take to long
Currently i'm working in a marketplace that has millions of orders. These orders have an order product, store, city, country, category etc etc. I have been asked display in a web page certain real time statistics on these orders. For example, total sales in the last year, month etc. Orders that include certain brand or products etc etc. The problem is that most Postgres queries are taking as long as 2 minutes to get all of the information necessary for this, so i'm getting timeout when requesting. Most of these queries require joins with other tables, and are inevitable. I've tried using indexes and used explain to make the queries better but I got to the point where it's not possible to optimize anymore. I can't upload the exact query (sorry). I'm trying to find the best solution for this problem, currently we are a startup so we can't afford big softwares. One solution that I have thought of is running queries every night saving the result of a certain indicator per day, and then on the go adding all the days before today with today's result. There must be better ways or practices for doing this, since I can …