Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send password reset mail from custom Django views?
I have Django 2.0.2 with custom User model. One of feature is give anonymous users way to create order without "register-first" on site. Main idea is: Anonymous user fill order form, enter e-mail address and click Create Order; Django create User with entered e-mail and random generated password; Next, Django (or Celery) send on his e-mail link for reset password (like with reset form); User check e-mail and click to reset link, re-enter his own password. This was killed two functions by one: user register and create first order. And question: how can I send reset password mail from my custom views? I understand to link will generate and send on reset password view, but how to call to them on custom view? -
How to return double string in models django
Helo everyone. I have a little problem. I've create a models: class Cudzoziemiec(models.Model): imie = models.CharField(max_length=80, verbose_name="Imię", unique=False) nazwisko = models.CharField(max_length=150, verbose_name="Nazwisko", unique=False) class Meta: verbose_name = 'Cudzoziemca' verbose_name_plural = 'Cudzoziemcy' def __str__(self): return self.nazwisko class Umowa(models.Model): RODZAJ_UMOWY = ( ('UP', 'Umowa o pracę'), ('UZ', 'Umowa zlecenie'), ('UD', 'Umowa o dzieło'), ) osoba = models.ForeignKey(Cudzoziemiec, on_delete=models.CASCADE, verbose_name="Wybierz cudzoziemca") umowa_rodzaj = models.CharField(max_length=250,choices=RODZAJ_UMOWY, verbose_name="Rodzaj umowy") nr_umowy = models.PositiveIntegerField() umowa_od = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data rozpoczęcia pracy") umowa_do = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data zakończenia pracy") class Meta: verbose_name = 'Umowę' verbose_name_plural = 'Umowy' def __str__(self): return self.nr_umowy In panel admin everything works ok. But how to display "imie"+"nazwisko" in panel admin in case when I want to create a new record in Umowy. Now I have only "nazwisko" if I want to add new record via Umowa class, selected a "osoba" in that class. -
Flask Application for Speaker Identification
I am writing my first flask application code for speaker identification. i am dealing with the voice clip. Basically i want to read multiple voice clips and then print it on browser page. Here is the code of upload function: @app.route('/upload', methods=['GET','POST']) def upload(): query = [] uploaded_files = flask.request.files.getlist("file[]") filenames = [] print(uploaded_files) for file in uploaded_files: if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER '],filename)) filenames.append(filename) return render_template('upload.html', filenames=filenames) @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'],filename) if __name__ == "__main__": app.run() Right now, it works but it is not show my uploaded files on browser, any idea how can i do that? -
Using face as password for chat site
I am new at Django and I'm making a demo chat website through Django 2.0. My motive here is to save people's photos when they sign up, and run a face authentication python script on the backend (which I have already done, through the open source face_recognition library on Python) to recognise user's when they login. My script uses cv2 right now to click a photo and sends it over to the face recognition engine. I have to save the photos of the users in a directory on the server-side, with the name of the image as the Name of the user when they sign up, so I can run a face authenticator to for-loop over the list of faces in my folder to find the matching face. And when it finds that, I can return the name to query over my database and create a session for that particular User. (I know it is time taking and resource intensive, but since it is a demo, I think i can get by it. Also kindly suggest if there can be a faster way for face based authentication) My User Model looks like this User(models.Model): username = models.CharField(max_length=100) name = models.CharField(max_length=100) … -
join queryset using aliasing in django
i have a models class FriendsWith(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) fusername =models.ForeignKey(User,on_delete=models.CASCADE,related_name='fusername') time = models.DateTimeField(auto_now_add=True) confirm_request = models.SmallIntegerField(default=1) blocked_status = models.IntegerField(default=0) i wanted to search all the friends of currently logged in user.So,i am doing like this obj1=FriendsWith.objects.filter(username=request.user).select_related('fusername') obj2=FriendsWith.objects.filter(fusername=request.user).values('username') obj=obj1 | obj2 friendslist=User.objects.filter(username__in=obj) Where User is a django User model I am trying to combine two queryset(obj1 and obj2) set here But it's not working.I can do the same thing in sql by using alias .But here i am not sure what to do. I am getting this error while performing the above code: TypeError: Merging 'QuerySet' classes must involve the same values in each case Please help in achieving this task -
Why I get no results filtering with Django?
I am trying to filter some of data and I use django filter to do it. One of my model fields is a Forerign Key, which automatically ModelChoiceFilter is used.In my case I need to choose more that one option from the specific filter so I use ModelMultipleChoiceFilter. A queyset parameter needs to be passed inModelMultipleChoiceFilter if you manually instantiated it. I am trying to achieve this using the code below, but I get no results using the specific filter. Although I get the proper results from the other filters: filters.py def available_bookies(request): """ Return available bookies for current user """ if request is None: return Bet.objects.none() user = request.user return Bet.objects.filter(user=user).values_list("bookie__name", flat=True).distinct() class BetFilter(django_filters.FilterSet): # Some other filters bookie = django_filters.ModelMultipleChoiceFilter(queryset=available_bookies) class Meta: model = Bet fields = ["date_from", "date_to", "odds_from", "odds_to", "stake_from", "stake_to", "country_multi", "competition_multi", "sport_multi", "status_multi", "home_multi", "visitor_multi", "bookie"] @property def qs(self): parent = super(BetFilter, self).qs return parent.order_by("-timestamp") -
Errno 13 Permission denied: '/home/pep_web/Structure_Descriptor/Input.csv'?
I have posted similar problem few days before but that time it was just solved by replacing manual path with the absolute path this time again i stuck with the similar problem and I have tried many thing but nothing is working. How can I resolve this problem This is my view which is throwing the error: def Pep_Str_Des(request): #return render(request, 'PepStructure/Structure.html', {}) if request.method == 'POST': form = Pep_str_Des(request.POST) if form.is_valid(): val = form.cleaned_data['Input_peptide'] pep_list = [] for v in val.split(','): if len(val.split(',')[0]) <= 17: if len(val.split(',')[0]) == len(v): pep_list.append(v) print v df = pd.DataFrame({'col_1':pep_list}) print df #file_path = os.path.join(os.path.dirname(__file__),'Input.csv') df.to_csv(os.path.join(os.path.dirname(__file__),'Input.csv'), index = False) os.environ['Input_file'] = os.path.join(os.path.dirname(__file__),'Input.csv') os.environ['out_file'] = os.path.join(os.path.dirname(__file__),'Out_file.csv') os.environ['cmds'] = os.path.join(os.path.dirname(__file__),'Structure_bassed_Descriptor_generation.py') os.system("python $cmds -p $Input_file -d $out_file") f_ns = glob.glob(os.path.join(os.path.dirname(__file__),'strs')+"/*.pdb") for f in f_ns: os.remove(f) f_ns = glob.glob(os.path.join(os.path.dirname(__file__),'strs')+"/*.sdf") for f in f_ns: os.remove(f) return render(request, 'Structure_Descriptor/Out.html', {'val':val} ) else: Input_peptide = 'ELIKAHLPDVALLDYRM,RYMKYLTGCAKLFRQGY,TGRVPLDQMSWVTPARW,IVKAVLDCAKGRDVVAP,QTRFANAPIRWLHADIM,GYRPDPATGAVNVPIYA' form = Pep_str_Des(initial={'Input_peptide': Input_peptide}) return render(request, 'Structure_Descriptor/Des.html', {'form':form}) error: IOError at /Pep_Str_Des/ [Errno 13] Permission denied: '/home/pep_web/Structure_Descriptor/Input.csv' Request Method: POST Request URL: http://93.188.167.63:8080/pep_learn/Pep_Str_Des/ Django Version: 1.10.8 Exception Type: IOError Exception Value: [Errno 13] Permission denied: '/home/pep_web/Structure_Descriptor/Input.csv' Exception Location: /usr/lib/python2.7/dist-packages/pandas/io/common.py in _get_handle, line 356 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/pep_web', '/usr/local/lib/python2.7/dist-packages/Django-1.10.8-py2.7.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', … -
Cannot find the GeoManager in module django.contrib.gis.db. models in Django 2.0
I am working on a GeoDjango project(first time working in a web app). Tring to use GeoManager but an error pops out saying module 'django.contrib.gis.db.models' has no attribute 'GeoManager'. After that, I checked the release notes of Django 2.0 and found out that the GeoManagerand GeoQuerySet classes are removed in Django 2.0. Does anyone know which module is it in right now? Or can anyone suggest any better alternative -
AWS, Django, Apache, ALLOWED_HOSTS not working 400 Bad Request
I have two Django applications working on the AWS Lightsail. First one is working great with www.firstapp.com and firstapp.com, but when I try to visit the second app without www in URL, it returns 400 Bad Request. In both apps, DEBUG set to False, and I have necessary hosts in settings.py like this: ALLOWED_HOSTS = [ '.secondapp.com' ] I have tried with '*' and also tried to write down all possible hosts in ALLOWED_HOSTS but it didn't work. I am able to see website with www.secondapp.com but secondapp.com always return Bad Request (400) After any update in settings.py, I always restart Apache (tried to reload also) nothing changes, still getting 400 Bad Request. Any ideas? Maybe I should set up AWS in some way, this is my first experience with Django -
Validate a single field in django without using Form or models
I am using django to fill some forms, I know how to use Forms and use validation but my forms are complicated and it is hard to create Forms object from those forms, I wanted to know is there any way to use validators on a parameter which I get from POST in a view? for example I have a filed which is named user then def login_view(request): # if this is a POST request we need to process the form data if request.method == 'POST': user=request.POST["user"] # check whether it's valid without using forms I know about validators https://docs.djangoproject.com/en/dev/ref/validators/ and it seems they only works on models and forms is it even possible to validate a single field? If not what other options do I have for complex forms? -
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details
my heroku logs: X:\PythonDjango\venv_setup\online_venv\src>heroku logs 2018-02-15T18:19:26.207988+00:00 app[web.1]: application = DjangoWhiteNoise(application) 2018-02-15T18:19:26.207990+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/whitenoise/django.py", line 44, in init 2018-02-15T18:19:26.207992+00:00 app[web.1]: self.add_files(self.static_root, prefix=self.static_prefix) 2018-02-15T18:19:26.207996+00:00 app[web.1]: self.update_files_dictionary(root, prefix) 2018-02-15T18:19:26.207994+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/whitenoise/base.py", line 90, in add_files 2018-02-15T18:19:26.208000+00:00 app[web.1]: for directory, _, filenames in os.walk(root, followlinks=True): 2018-02-15T18:19:26.207998+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/whitenoise/base.py", line 93, in update_files_dictionary 2018-02-15T18:19:26.208001+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/os.py", line 335, in walk 2018-02-15T18:19:26.208003+00:00 app[web.1]: top = fspath(top) 2018-02-15T18:19:26.210257+00:00 app[web.1]: [2018-02-15 18:19:26 +0000] [9] [INFO] Worker exiting (pid: 9) 2018-02-15T18:19:26.209630+00:00 app[web.1]: TypeError: expected str, bytes or os.PathLike object, not tuple 2018-02-15T18:19:26.433218+00:00 app[web.1]: [2018-02-15 18:19:26 +0000] [4] [INFO] Shutting down: Master 2018-02-15T18:19:26.433450+00:00 app[web.1]: [2018-02-15 18:19:26 +0000] [4] [INFO] Reason: Worker failed to boot. 2018-02-15T18:19:26.552341+00:00 heroku[web.1]: Process exited with status 3 2018-02-15T18:19:26.830265+00:00 heroku[web.1]: State changed from up to crashed 2018-02-15T18:19:55.377507+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=shoppingwave.herokuapp.com request_id=551a7986-4cd6-4b43-9b9a-9f1eb46a5bc4 fwd="157.50.221.99" dyno= connect= service= status=503 bytes= protocol=https 2018-02-15T18:19:56.339174+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=shoppingwave.herokuapp.com request_id=f6606c27-b393-4c55-b4ac-2c956c8b32da fwd="157.50.221.99" dyno= connect= service= status=503 bytes= protocol=https 2018-02-15T18:22:48.555479+00:00 app[api]: Starting process with command python manage.py collectstatic by user rahulverma6612@gmail.com 2018-02-15T18:23:00.573440+00:00 heroku[run.1271]: State changed from starting to up 2018-02-15T18:23:00.692267+00:00 heroku[run.1271]: Awaiting client 2018-02-15T18:23:00.752947+00:00 heroku[run.1271]: Starting process with command python manage.py collectstatic 2018-02-15T18:23:10.269796+00:00 heroku[run.1271]: Process exited with status 1 2018-02-15T18:23:10.596849+00:00 heroku[run.1271]: State … -
Not Found: /media/ on form submit
I have a form with a ImageField() in it I've already set the media URL and directory and such in setting.py and url.py and on submit everything works perfectly, but suddenly now everytime I try submit my form it fails and says in python terminal : [17/Feb/2018 14:40:08] "POST /form/ HTTP/1.1" 200 37885 Not Found: /media/ , when I didn't even tempered with the setting.py or the url.py below is my code : setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') url.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model.py class Model_A(models.Model): name = models.CharField(max_length=200, verbose_name="Name (as in NRIC)") def upload_photo_dir(self, filename): path = 'hiring/employees/photo/{}'.format(filename) return path photo = models.ImageField(upload_to=upload_photo_dir) view.py def application_form_view(request): form = Model_AForm(request.POST or None, request.FILES or None) if form.is_valid(): inst = form.save(commit=False) inst.save() context = {'form': form} return render(request, 'form.html', context=context) html <form method="POST" enctype="multipart/form-data" id="application_form" name="application_form"> <label>name :</label> {{ form.name}} <label>Photo:</label> {{ form.photo }} </form> -
Django Channels Invalid Syntax
I am trying to work with Django Channels. Every time I try to run manage.py, I get the following error: File "/usr/local/lib/python2.7/dist-packages/daphne/server.py", line 192 async def handle_reply(self, protocol, message): ^ SyntaxError: invalid syntax I have installed all the necessary components for Channels to work. -
User password reset: Emails not being sent to console
I am currently learning Django, mainly from Andrew Pinkham's book "Django Unleashed", and because the book is prior to Django 2, I cannot use the code in verbatim but adjust the code accordingly. I am currently on Ch. 21 (Extending Authentication). Everything works so far, but I am having trouble with users resetting their passwords. A user can enter the email for resetting the password, and a message appears, stating the email was successfully sent -- but nothing is displayed on the console (the code is still in DEBUG and I have yet to allow emails to be actually sent, other than to the console for testing). Here is an excerpt of my project structure: pysawitweb |_contact |_pysawitweb | |_settings.py | |_urls.py | |_... |_user | |_templates | | |_user | | | |_base_user.html | | | |_logged_out.html | | | |_login.html | | | |_login_form.html | | | |_password_change_done.html | | | |_password_change_form.html | | | |_password_reset_complete.html | | | |_password_reset_confirm.html | | | |_password_reset_email.txt | | | |_password_reset_form.html | | | |_password_reset_sent.html | | | |_password_reset_subject.txt | |_urls.py | |_... |_manage.py In the settings.py file: ... DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ … -
Recursion error caused in django when trying to read from files
I am working on a project for displaying my university's energy data but when I am trying to read from my university's excel sheets that store data, I am getting the following error: RecursionError at /multiplication/ maximum recursion depth exceeded Request Method: GET Request URL: http://127.0.0.1:8000/multiplication/ Here is my views.py class without pandas: from django.shortcuts import render,get_object_or_404 from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic import TemplateView from django import forms #import pandas as pd # Create your views here. # def startPage(request): # return render(request, 'multiplication/detail.html') template_name1 = 'multiplication/detail.html' class myForm(forms.Form): quantity1 = forms.IntegerField(required=False) quantity2 = forms.IntegerField(required=False) #main method def multiply_two_integers(x,y): return x*y def read_excel(ExcelFileName): File = read_excel(ExcelFileName) return File def my_view(request): read_excel("AH1_Hahn_26032017_29032017.xl.xlsx") If I try to import pandas as pd, then I get a different type of error: Traceback (most recent call last): File "/Users/NikolasPapastavrou/firstProject/multiplication/views.py", line 14, in <module> import pandas as pd File "/Users/NikolasPapastavrou/firstProject/pandas/__init__.py", line 19, in <module> "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy'] -
Django Pagination returns entire database on page 2
Trying to get pagination to work in Django, looks fine on page one but when I go to page to I see my entire database. class Advancedenter code hereSearch(ListView): template_name= 'saferdb/AdvancedQuery.html' def get(self, request): c = request.GET.getlist('opeclass') q = Question.objects.all() #Ugly q filtering methods paginator = Paginator(q, 25) page = request.GET.get('page') contacts = paginator.get_page(page) return render(request, 'saferdb/list.html', {'text' : count , 'contacts': contacts}) -
in __init__ super(NeonArgparser, self).__init__(*args, **kwargs) TypeError: __init__() got multiple values for keyword argument 'add_config_file_help'
class NeonArgparser(configargparse.ArgumentParser): """ Setup the command line arg parser and parse the arguments in sys.arg (or from configuration file). Use the parsed options to configure the logging module. Arguments: desc (String) : Docstring from the calling function. This will be used for the description of the command receiving the arguments. """ def __init__(self, *args, **kwargs): self._PARSED = False self.work_dir = os.path.join(os.path.expanduser('~'), 'nervana') if 'default_config_files' not in kwargs: kwargs['default_config_files'] = [os.path.join(self.work_dir, 'neon.cfg')] if 'add_config_file_help' not in kwargs: # turn off the auto-generated config help for config files since it # referenced unsettable config options like --version kwargs['add_config_file_help'] = False self.defaults = kwargs.pop('default_overrides', dict()) **super(NeonArgparser, self).__init__(*args, **kwargs)** # ensure that default values are display via --help self.formatter_class = configargparse.ArgumentDefaultsHelpFormatter self.setup_default_args() -
django rest framework modelserializer is_valid return false when declare custom field with source attribute
I was working on some project which read data from rest API then deserialize data for storing into database. Below are model and deserializer class ExchangeInfo(models.Model): server_time = models.BigIntegerField() timezone = models.CharField(max_length=20) class ExchangeInfoSerializer(serializers.ModelSerializer): server_time = serializers.IntegerField(source='serverTime') timezone = serializers.CharField(max_length=20) class Meta: model = ExchangeInfo fields = '__all__' Below is the code I used to deserialize data def load_exchange_info(): exchange_info = client.get_exchange_info() from common.models import ExchangeInfo from common.serializers import ExchangeInfoSerializer exchange_info_serializer = ExchangeInfoSerializer(data=exchange_info) exchange_info_serializer.is_valid() print(exchange_info_serializer.errors) Some how when I try to store the deserialized data to DB, it reflected successfully, but the is valid always return False as below {'server_time': ['This field is required.']} Any suggestion on what the issue is? -
Every other ajax call has a 300ms delay
I noticed a really weird behavior with my ajax calls. Every other ajax call always have a 300ms delay. Here is what the network section look like. I looked at the details of the call. Here is the fast ajax call, and here is the slow ajax call. The slow ajax call has 2 extra fields - DNS lookup and Initial Connection. Why does this happen every other ajax call? How can I ensure consistent ajax performance? The test code: <body> <input type="button" class="btn" id="testButton" value="Test"/> </body> <script> document.getElementById('testButton').onclick = function() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log('done'); } }; xhttp.open("GET", "{% url 'test_ajax' %}", true); xhttp.send(); } </script> def test_ajax(request): return JsonResponse({'a': 'a'}) -
Autocomplete through a selected external key (Django)
I have a query and I have 2 models, one called Detalleventa and Producto class DetalleVenta(models.Model): producto = models.ForeignKey(Producto,on_delete=models.CASCADE,verbose_name='Producto') cantidad = models.IntegerField(verbose_name='Cantidad') preciounit = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Precio unitario') subtotal = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Subtotal') venta = models.ForeignKey(Venta,on_delete=models.CASCADE, related_name='detalleventa', verbose_name='Venta') def __str__(self): return '{} - {}'.format(self.venta,self.producto) class Producto(models.Model): nombre = models.CharField(max_length=30,unique=True,verbose_name='Nombre de Producto:') precio = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Precio de Producto:') categoria = models.ForeignKey(Categoria,on_delete=models.CASCADE,verbose_name='Categoría:') def __str__(self): return self.nombre And in my Detalle forms.py I have: class DetalleForm(forms.ModelForm): class Meta: model = DetalleVenta fields = [ 'producto', 'cantidad', 'preciounit', 'subtotal', ] labels = { 'producto':'Producto', 'cantidad':'Cantidad', 'preciounit':'Prec.Unit.', 'subtotal':'Subtotal', } widgets = { 'producto':forms.Select(attrs={'class':'form-control'}), 'cantidad':forms.NumberInput(attrs={'class':'form-control cantidad'}), 'preciounit':forms.NumberInput(attrs={'class':'form-control'}), 'subtotal':forms.NumberInput(attrs={'class':'form-control subtotal', 'readonly':True}), } DetalleFormSet = inlineformset_factory(Venta, DetalleVenta, form=DetalleForm, extra=1) As you can see in the details form, I have a priceunit field that refers to the price of the product that is in the product model and my question is: is there any way in my details template when selecting, for example, a product X ? ? (external key product) autocomplete its respective price in the input of preciounit? This is my template: {% extends 'base/base.html' %} {% load static %} {% block titulo%} Registrar venta {%endblock%} {% block contenido %} <div class="col-md-12"> <form method="post">{% csrf_token %} … -
Django: Is it possible to use `method(or property)` for `unique_together` in model?
This is my model structure (I simplified fields of model): class SymbolB(models.Model): type = models.CharField(max_length=50) class SymbolA(models.Model): sector = models.CharField(max_length=50) class DailyPrice(StockDataBaseModel): symbol_a = models.ForeignKey(SymbolA, null=True) symbol_b = models.ForeignKey(SymbolB, null=True) date = models.DateField() @property def symbol(self): if self.symbol_a is not None: return self.etf_symbol if self.symbol_b is not None: return self.stock_symbol def clean(self): if type(self.symbol) is SymbolA and DailyPrice.objects.filter(symbol_a=self.symbol, date=self.date): return False elif type(self.symbol) is SymbolB and DailyPrice.objects.filter(symbol_b=self.symbol, date=self.date): return False return True The reason that DailyPrice model has two symbol fields is that it should be related with either of them. I know I can use GenericForeignKey but this site said that GenericForeignKey makes db table and query process more complex so chose above structure. And what I want to do is to prevent DailyPrice model created with same symbol(either symbol_a or symbol_b) and the date. For example, the one with symbol_a = my_symbol and date="2011-11-11" should be unique. That's why the clean() method is overrided in the model. As a result, every time I create DailyPrice model, I should write a code like below: daily_price = DailyPrice( symbol_a=symbol, date=date, open=open, high=high, low=low, close=close,volume=volume, ) if not daily_price.clean(): return else: daily_price.save() which is kinda bothersome and no idea whether this … -
Fastest way to run many startswith queries in django
I have a list of item numbers which can be thousands of elements long. I need to search my SQL database for records that start with the numbers in my list. I am using the django ORM but raw sql works too. As an example my list could look like this: ['123ab', '234dd', '421ad'] I am trying to find a solution that is better than looping through the list and running a startswith query every time like this: for element in list: Item.objects.filter( item_number__startswith=element ).values( 'item_number', 'manufacturer' ) The problem with the loop above is that it would be very slow for a large list of item numbers. Is there a more efficient way of doing this? -
Multiple Mezzanine projects on same server with Nginx and Gunicorn: "server IP address could not be found"
I'm very new to deployment. I'm trying to deploy two Mezzanine 4.2.3 projects (they use Django 1.10.8 according to requirements.txt) on Ubuntu 16.04. I deployed the first one successfully with this tutorial. I can access it via its domain name, say, example.com. I'm trying to get the other one accessible on either food.example.com or preferably example.com/food but the browser returns: "server IP address could not be found". The nginx config for example.com at /etc/nginx/sites-available/example: server { listen 80; server_name [SERVER IP ADDRESS] example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/example; } location / { include proxy_params; proxy_pass http://unix:/home/example/example.sock; } The nginx config for food.example.com at /etc/nginx/sites-available/food: server { listen 81; server_name food.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/food; } location / { include proxy_params; proxy_pass http://unix:/home/food/food.sock; } } I tried to use example.com/food but nginx kept saying there're suspicious symbols in it. I don't know if that's one of the problems preventing the page from being displayed but I changed it to the subdomain food anyway to try and isolate the issue. The gunicorn config file for example.com at /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] … -
How to add a table in django app models from PostgreSQL?
I have created a django project named Book Store. In my project I have one app named books. I am using PostgreSQL DBMS. I have a database called books. In that database, I have a table named novel. How do I add this table in the models.py file inside books app? I want to register this table under admin site. After successfully adding this table in the models.py file, I believe, I shall be able to register the table in the admin site by writing the following codes in the admin.py file under books app. from django.contrib import admin from . models import novel admin.site.register(novel) I also want to know that if my approach is correct or is there any better way available? As I am new to django, I don't know much about it. I have read django-book but didn't find out my answer. There is an article about SQLite database though. So, can anyone help me out here? Thanks in advance. -
Django logging does not work with django shell
I have logging set up in my Django app to log to both stdout and a file. When I run my django app normally (./manage.py runserver) the logs are updated as expected. However, when I run ./manage.py shell and run the following commands the log is not updated: import logging logger = logging.getLogger('mylogger') logger.error('test') Do I have to do something extra to get logging to work within the shell?