Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set Index Name in Django with db_index=True
Can I set my own index name when setting index using db_index=True in Django models? -
Adding pagination on searched data in django using ajax call
I am trying to do pagination on the searched data but when clicked on the pagination option like on clicking second page i am not able to recieve the value of q and it throws error. -
How do you install Django & PIP?
I am having a nightmare tonight, I want to start learning some Django but I am running into quite a few problems while installing it. I am following these tutorials - https://www.youtube.com/watch?v=UmljXZIypDc / https://www.youtube.com/watch?v=MEcWRk9w0t0 I installed Python 3.7.2 and confirmed the installation by typing 'python --version' into Terminal/Command Prompt. I typed 'pip --version' into CMD and got this message in return "'pip' is not recognized as an internal or external command, operable program or batch file." this is where I am stuck, I cannot continue any longer without completing this step, could anyone tell me where I am going wrong? Thank you -
Console log of AJAX data is my html code?
I am trying to transfer data through an ajax request. I want to transfer the contents of the input field. But output of console.log("ok" + data) is "ok" + all my html code, although output of console.log("ok" + formData) is that value i need. respectively, in the Django view variable q = None <input id="search" name="q" type="text" class="form-control" placeholder="Поиск"> <input name='submit_s' id='search_btn' type='button' value='poisk' /> jQuery(document).ready(function($){ $("#search_btn").click(function () { var formData = $('#search').val(); $.ajax({ type: "GET", url: "search/", data: { q: formData, }, processData: false, dataType: "text", cache: false, success: function (data) { if (data != ''){ console.log("ok" + data); } else { console.log("no"); } }, failure: function(data){ console.log("FAIL"); console.log(data); }, }); }); }); -
Django circularDependencyError
from django.db import migrations import xlrd def load_gm_options(apps, schema_editor): GMOptions = apps.get_model('sendmails','GMOptions') gm_filename = "../GMOptions.xlsx" gm_workbook = xlrd.open_workbook(gm_filename) for row in range(1,gm_workbook.sheet_by_index(0).nrows): GMOptions.objects.create(GMOptionText = gm_workbook.sheet_by_index(0).cell_value(row,0),GMOptionTextTranslation = gm_workbook.sheet_by_index(0).cell_value(row,1)) class Migration(migrations.Migration): dependencies = [ ('sendmails','0001_initial'), ] operations = [ migrations.RunPython(load_gm_options), # migrations.RunPython(load_item_list) ] I'm trying to pre-populate my models with some data but when I run python manage.py migrate. I got an error saying circularDependencyError, I tried removing the ('sendmails','0001_initial') but I will get an error saying no installed app with label. Below are all the tracebacks Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 275, in build_graph self.graph.ensure_not_cyclic() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\graph.py", line 274, in ensure_not_cyclic raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle)) django.db.migrations.exceptions.CircularDependencyError: sendmails.0001_initial -
Django request method always return GET
@csrf_exempt def get_request(request): return JsonResponse({"method":request.method}) Postman POST result { "method": "GET" } I try to detect request method, but no matter what request I used, It always return GET anyone know where is the problem? -
payment status last page displaying -Django
working on payments to my web application and i m facing problem in displaying in the last page after the transaction happens i m able to re-direct to my local page (after transaction) but i m trying to display some of the response in the last page like his/her name, transaction status,and transaction id,and orderid but i couldn't retrieve data from views.py in "postdict"(list of items) below is my source code plz i need some suggestions what i need to do i have tried jinja code etc but couldn't get the data in the final page transaction {"status": 1, "url": "http://localhost:8000/response/", "data": {"name_on_card": "NA", "bank_ref_num": "499.0", "udf3": "", "hash": "8a6277714805380124ddd954797e009fb579be9a5900c645ce015ea61c3acd0acae0c22e37357e823b3f272b5eeb2563e1d253f34d57afe516cfa45a52918361", "firstname": "sai", "net_amount_debit": "499.0", "payment_source": "Easebuzz", "surl": "http://localhost:8000/response/", "error_Message": "PGS10001-Success", "issuing_bank": "NA", "cardCategory": "NA", "phone": "1234567890", "easepayid": "TFJ9DQGI15", "cardnum": "NA", "key": "TOXNUO0ICS", "udf8": "", "unmappedstatus": "NA", "PG_TYPE": "NA", "addedon": "2019-11-26 05:12:59", "cash_back_percentage": "50.0", "status": "success", "udf1": "", "merchant_logo": "NA", "udf6": "", "udf10": "", "txnid": "6b2058x9a", "productinfo": "web integration", "furl": "http://localhost:8000/response/", "card_type": "INR", "amount": "499.0", "udf2": "", "udf5": "", "mode": "NA", "udf7": "", "error": "NA", "udf9": "", "bankcode": "NA", "deduction_percentage": "2.00", "email": "sai2@gmail.com", "udf4": ""}} name: views.py -
Django: Extract not working with DateTimeField
The Extract function of Django ORM returns None after annotation if I use DateTimeField. Why?? models.py class SimpleModel(models.Model): date = models.DateField() datetime = models.DateTimeField() settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testdb', 'USER': 'root', 'PASSWORD': 'password', } } Django shell output [connected to MYSQL] In [5]: from django.db.models.functions import Extract In [6]: annotate_kwargs = dict(month_from_datetime_field=Extract('datetime','month'),month_from_date_field=Extract('date','month')) In [7]: SimpleModel.objects.annotate(**annotate_kwargs)[0].__dict__ Out[7]: {'_state': <django.db.models.base.ModelState at 0x7fbb8ffb3eb8>, 'id': 1, 'date': datetime.date(2019, 11, 26), 'datetime': datetime.datetime(2019, 11, 26, 6, 9, 14, tzinfo=<UTC>), 'month_from_datetime_field': None, 'month_from_date_field': 11} -
django core.mail.send_mail works fine but EmailMessage.send fails
Trying to send email with a 'reply-to' option as below. msg = EmailMessage( subject='title/subject', body='<h1>h1 text</h1><h2>h2 text</h2>', from_email='FROM-ADDR', to=['TO-ADDRESS',], reply_to=['RE-TO-ADDR',], ) msg.content_subtype='html' msg.send() It gives SMTPDataError at /send_mail (550, b'Request failed; Mailbox unavailable') However, if I just use django.core.mail.send_mail, it works fine as below. to = ['TO-ADDRESS',] from_email = 'FROM-ADDR' subject= 'subject' text = 'SOME TEXT' html_message = '<h1>abc</h1>' mail.send_mail(subject, text, from_email, to, html_message=html_message) -
can I generate a circular qr-code like a messenger or a kik code in python
can i generate QR-code in circular shape on python like Facebook messenger or kik code used.i am visit many site but i am didn't get that type of Qr-code. -
Pass URL parameter to form value Django
I'm trying to set the value of a form input to the url, then redirecting to another page with another form using the information in the url parameter and passing another value of another input to the url. Let's say that my url is page1/value1/page2/value2 Where value1 comes from the first form and value2 from the second form in the second page. Using this code I can get the first value in the url, but somehow I can't save the form information to the database and set the other value in the url. class Acceso(FormView): template_name = 'codigo_zona.html' form_class = AccesoForm def form_valid(self, form): zona_code = form.cleaned_data.get('codigo_acceso') return redirect('registro', zona_code) class AccesoDetails(View): def get(self, request, zona_code): zona = Zona.objects.filter(codigo_acceso=zona_code).first() if request.method == 'POST': zona_id = zona.pk range_start = 10 ** (6 - 1) range_end = (10 ** 6) - 1 access_code = randint(range_start, range_end) form = RegistroResidenteForm(request.POST) if form.is_valid(): registro_residente = form.save(commit=False) registro_residente.zona_residencial.pk = zona_id registro_residente.codigo_acceso = access_code registro_residente.status_activacion = False registro_residente.save() else: form = RegistroResidenteForm() context = { 'zona': zona, 'form': form } return render(request, 'registro_residentes.html', context) I get the error Method not allowed (Post): HTTP/1.1 405 0 when submiting the second form, so I never see the second … -
'workon' is not recognized as an internal or external command, operable program or batch file
I had created a virtual environment named test on cmd and then tried to call it on vscode terminal then it is showing: 'workon' is not recognized as an internal or external command, operable program or batch file. What should I do? Thanks in advance -
How to support STRING_AGG in django queryset for sql server 2017
I tried to return the queryset with one field which is the list string in django, for example, like this: Name Ids Chicken Wing 2529,2695,10829,10995,12129,12295 I only know how to get the queryset by GROUP_CONCAT which support mysql database, when I migrated to sql server 2017 database. It doesn't work, I checked SQL SERVER 2017 support STRING_AGG, but I don't know how to use it in django.(I am using django rest framework) Anyone can help me? Thanks -
Django ORM - Fetch Multiple select_related having OneToOneField
My models structure is similar to this. class Block(models.Model): TYPE_CHOICES = ( ('text', "TEXT"), ('image', "IMAGE"), ) // I have around 10 types type = models.CharField(max_length=8, choices=) class User(models.Model): current_block = models.ForeignKey(Block, on_delete=models.CASCADE) class TextBlock(models.Model): block = models.OneToOneField(Block, on_delete=models.CASCADE, related_name='text', primary_key=True) class ImageBlock(models.Model): block = models.OneToOneField(Block, on_delete=models.CASCADE, related_name='image', primary_key=True) So, if I wanted to get the current_block of customer in a select related phrase, I use Customer.objects.select_related('block', 'block__text', 'block__image'). I have 10 block types similar to text and image, so my select_related clause is pretty big. Is there any way to get all the blocks? -
Django redirect user after successful registration not working
I am new to django and building a registration system. When user registers successfully, it redirects to thesame registration page instead of home. views.py def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') saved_user = form.save() saved_user.set_password(password) user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("home") else: for msg in form.error_messages: print(form.error_messages[msg]) return render(request=request, template_name="registration/register.html", context={"form": form}) form = UserCreationForm return render(request=request, template_name="registration/register.html", context={"form": form}) register.html {% extends 'base.html' %} {% block title %}Register{% endblock %} {% block content %} <div style="text-align:center"><h2>Register</h2></div> <div style="text-align:center"> <form method="post" action="{% url 'register' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Register"> </form> <p> If you already have an account <a href="/login" target="blank"><strong>login</strong></a> </p> </div> {% endblock %} urls.py urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('register', views.register, name='register'), ] -
How to deploy my python image recognition project to a cloud web server?
Hello stack overflow i am a bit new to cloud based webapps, my apologies if this question is very noobish. I have built a facial recognition in python Using Open CV and for UI i used tinkler. I know for web apps i need to use any framework like Django,but i I would like to know if i would be able to deploy this app directly into any cloud server like Microsoft Azure or AWS or Google Cloud and access my webapp from the browser. If yes then please let me know briefly how can i achieve that. Thanks in advance. -
What is the correct way of generating authorization token in django?
I'm trying to generate auth token in my django project.When i inspect source code of django-rest framework, they seem to generate auth_token using:- binascii.hexlify(os.urandom(20)).decode() but auth_token should be unique so that i can find corresponding user from auth_token.What is the best possible way of generating auth token, uuid or same as that of drf framework? -
Gunicorn fails to start after installing Memcached on Django project
I've had a django project working perfectly for several months, and then I decided to install memcached so I could store store my session information in there, and now everything is broken... what I did... sudo apt install memcached ... pipenv install python-memcached ... settings.py ... CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' ... I've since removed these from my settings.py sudo systemctl restart gunicorn.myproj memcached and after that. I started getting a 502 Bad Gateway I tried a reboot, no luck. Tried removing the changes to settings.py no luck nginx.error ubuntu@ip-xxx-xx-x-xxx:/var/log/nginx$ tail error.log 2019/11/26 02:43:11 [error] 829#829: *249140 connect() to unix:/run/gunicorn.myproj.sock failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: myproj.com, request: "GET /album/random/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.myproj.sock:/album/random/", host: "www.myproj.com", referrer: "https://www.myproj.com/album/upload/" 2019/11/26 02:43:12 [error] 829#829: *249140 connect() to unix:/run/gunicorn.myproj.sock failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: myproj.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.myproj.sock:/", host: "www.myproj.com" 2019/11/26 02:43:13 [error] 829#829: *249140 connect() to unix:/run/gunicorn.myproj.sock failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: myproj.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.myproj.sock:/", host: "www.myproj.com" 2019/11/26 02:43:13 [error] 829#829: *249140 connect() to unix:/run/gunicorn.myproj.sock failed (111: Connection refused) while … -
Django control looping
How do I control the loop? for example if the user choose the "13" in Number Of Grades, it will show 13 search result , just like in the picture below and if the user choose for example, "2" Number of grades it will show like this and if the user choose "3" Number Of Grades it will show like this this is my views.py def gradescales(request): grade = gradeScalesSetting.objects.all() return render(request, 'Homepage/gradescale.html',{"gradeScalesSetting":grade}) def gradescaleview(request): id = request.GET.get('gradescale') grade = gradescale.objects.all().filter(Grade_Scales_Setting__id=id) return render(request, 'Homepage/gradescaleview.html', {'gradescale': grade}) this is my models.py class gradeScalesSetting(models.Model): Configuration = models.CharField(max_length=500, null=True) NumberOfGrades = models.IntegerField(blank=True, null=True) Rounding = models.CharField(max_length=500, null=True) Precision = models.FloatField() class gradescale(models.Model): Grade_Scales_Setting = models.ForeignKey(gradeScalesSetting, related_name='+', on_delete=models.CASCADE, null=True) Display_Sequence = models.IntegerField() Symbol = models.CharField(max_length=500, null=True) LowerLimit = models.FloatField() GPAValue = models.FloatField() Description = models.CharField(max_length=500, blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) please help me, tomorrow is the deadline for this assignment. -
I have two data to render
Now I have two data to render: one is in 'base.html', and the other is in 'index.html'.I tried the following two methods, but none of them worked. views.py def everyday_cs(request): r = Content.objects.filter(is_check=True) everyday_cs = random.choice(r) return render(request, 'base.html', locals()) def index(request): everyday_cs(request) articles = LifeArticle.objects.all() return render(request, 'index.html', locals()) url.py urlpatterns = [ url(r'^$', views.index,), ] and testurl.py urlpatterns = [ url(r'^$', views.index,), url(r'^$', views.everyday_cs,), ] base.html {{everyday_cs}} index.html {% extends "base.html" %} {% if articles %} {% for article in articles %} {{article.title}} {% endfor %} {% endif %} I want to run the 'everyday_cs' function first when I run 'index' and 'url.py' write two 'url(r'^$', )' to run them, but they don't work. -
My Django Nginx Gunicorn Supervisor Only Serve 1 Request At A Time
I publish my django website using gunicorn nginx and supervisor. as i read everywhere, this was the best setup for publishing django. everything is working fine. but then in my website i have this long requested script where it takes around 10 secs to finish. i noticed that while this script is loading, another request either its from the same computer or another computer, a simple html page of my website wont load until that other 10 secs request finish. is it just me or this setup was suppose to serve multipe request as my webserver became busy. My Computer Specs: CPU(s) : 4 Core(s) Per Socket : 4 CPU max MHz: 1512.0000 Socket(s): 1 Gunicorn Service: NAME="web" # Name of the application DJANGODIR=/home/webserver/django/ # Django project directory SOCKFILE=localhost:8000 # we will communicte using this unix socket USER=root # the user to run as GROUP=root # the group to run as NUM_WORKERS=15 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=web.settings # which settings file should Django use DJANGO_WSGI_MODULE=web.wsgi # WSGI module name TIMEOUT=30 Nginx Service: location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_connect_timeout 300s; proxy_read_timeout 300s; # Try to serve static files from nginx, no … -
Docker-compose django nginx doesnt find static files
I'm trying to dockerize my application and i'm almost done. The only issue I have is that nginx doesn't find my static files. I've searched all over the web, but I havent found a solution yet. I made a volume that's shared between the Django application and the Nginx server, and in my settings.py I pointed the settings to that, but no luck. I'm not sure how many of the files you need to inspect, so I uploaded the whole project to Github. https://github.com/temp3020102/django_project When the image has been built and you navigate to the admin page one can see that the CSS is missing. I'm aware that posting the secret_key and such to the internet is not a good idea, and i'm of course changing that once I have a fix for the issue. It's just there for the sake of your convenience. -
Save removed FileField image from existing object in S3
I accidentally removed images from my FileField but I use s3 using django-storage and these media files are still in the bucket. How can I save these images as FileField? I have path to the image from the backup. for example: i = Item.objects.get(pk=1) i.image = '/home/project/media/images/2019/11/09/IMG.JPG' i.save() but how to save here image from s3? On s3 there is media/images/2019/11/09/IMG.JPG folder with file -
Objects with the lowest value 0 at the end
The 0 in my query set represent 'unknown' values, but when ordered, they start the list and I want them at the end. table.objects.filter(object=pk).order_by('decimal_coln') This is what I'm getting Object decimal_coln Object_kdlsdl 0 Object_nksljj 0 Object_njsdlk 0 Object_jdnskl 1 Object_ldskll 1 Object_nlsdkl 12 Object_sjslkl 15 This is what I want (ordered, but zeros at the end): Object decimal_coln Object_jdnskl 1 Object_ldskll 1 Object_nlsdkl 12 Object_sjslkl 15 Object_kdlsdl 0 Object_nksljj 0 Object_njsdlk 0 -
cannot import name 'HTMLField' from 'tinymce'
I am getting below error message at the time of makemigrations. Can anybody please suggest. from tinymce import HTMLField ImportError: cannot import name 'HTMLField' from 'tinymce' (F:\Blog\bootstrap-blog-1-2-1\distribution\env\lib\site-packages\tinymce__init__.py)]