Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
$.ajax({}) is not a function in django
Such related question I have seen so many but none solved my problem. There is other reason why this is not working but I am feeling difficult to figure out the issue. Here is the code base.html <div class="sections-wrapper"> {% block pagecontent %} {% endblock pagecontent %} </div> {% block js %} {% include 'includes/js.html' %} <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-company").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "Unlike") } else { updateText(this_, removeLike, "Like") } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> {% endblock js %} includes/nav.html {% load static %} <script src="{% static 'js/jquery.slim.min.js'%}"></script> <script src="{% static 'js/tether.min.js' %}"></script> <script src="{% static 'js/bootstrap4.min.js'%}"></script> home.html {% extends 'base.html' %} {% block pagecontent %} <div class="container"> {% if companies %} <h3 class="text-center bold categories">COMPANIES</h3> {% for company in companies %} {% if forloop.first %}<div class="row">{% endif %} <a href="{{ company.get_like_url }}" class="btn btn-link like-company" data-href="{{ company.get_like_url }}" data-likes="{{ company.likes.count … -
django search using raw mysql
i am trying to create a custom search engine with 4 fields of search. I want to search inside the mysql table. this is part of my views.py for the search, pagination and it lists the entire table data. def addview(request, table_id): try: table_name = Crawledtables.objects.get(id=table_id) tbl_details = "SELECT * FROM " + table_name.name tbl_detail = AllTables.objects.raw(tbl_details) paginator = Paginator(list(tbl_detail), 100) page = request.GET.get('page') try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) q = request.GET.get("q") title_search = """SELECT * FROM """ + table_name + """ WHERE `Title` LIKE '\%""" + q + """\%' """ # title_search = """SELECT id,description, MATCH (title) AGAINST (""" + q + """ IN BOOLEAN MODE) " \ # FROM """ + table_name + """ ORDER BY id DESC;""" search_title = AllTables.objects.raw(title_search) return render(request, 'tables/table_list.html', {'tbl_name': table_name, 'details': tbl_detail, 'search': search_title, 'detail_page': details}) except AllTables.DoesNotExist: raise Http404() and this is part of my models.py with the dynamic table class. @python_2_unicode_compatible class AllTables(models.Model): title = models.TextField(db_column='Title', blank=True, null=True) url = models.CharField(db_column='Url', unique=True, max_length=250, blank=True, null=True) description = models.TextField(db_column='Description', blank=True, null=True) class Meta: managed = False def __str__(self): return self.url def __unicode__(self): return self.title the error that i get using any of … -
Django:How to get url parameters passed to views from jquery
This is my url pattern: url(r'^(?P<pk>\d+)/view/$', views.leave_view, name='leave_view') my views.py def leave_view(request,pk): leaves=leave.objects.get(id=pk); data=dict() if request.method == 'POST': data['html_form']= render_to_string('m_manage/view_modal.html', {'leaves':leaves}, request=request) return JsonResponse(data) My js call js----call to on click of button <script> $("#table").on('click', '.view', function (e) { var btn = $(this); console.log(btn); var url = btn.attr("data-url"); console.log(url); $.ajax({ // url: '/m_manage/leave_view/', url: btn.attr("data-url"), dataType: 'json', type: 'get', success: function (data) { console.log('You Did it!!!!'); console.log(data); $("#modal-leave .modal-content").html(data.html_form); } }); }); </script> My console.log(data) prints nothing though I am collecting primary key from url and writing query...Why there is no data in it... -
How to robustly set Django secret key as environment variable
My Django project's secret key contains special characters such as #, @, ^, * etc. I'm trying to set this as an env variable at /etc/environment. I include the following in the file: export SECRET_KEY='zotpbek!*t_abkrfdpo!*^@#plg6qt-x6(%dg)9p(qoj_r45y8' I.e. I included single quotes around the string since it contains special characters (also prescribed by this SO post). I exit the file and do source /etc/environment. Next I type env in the terminal: SECRET__KEY correctly shows. I log out and log back in. I type env again. This time SECRET_KEY still shows, but is cut off beyond the @ character. It's excluding everything beyond (and including) the # character. How do I fix this issue? Trying with double quotes didn't alleviate anything either. My OS is Ubuntu 14.04 LTS. p.s. I'm aware environment variables don't support access control; there's a bunch of reasons not to set the Django secret key as an env var. For the purposes of this ques, let's put that on the back burner. -
db.sqlite3 file encoding in django
I am beginner with Django and I'm using PyCharm IDE. I was watching a tutorial following along when I noticed my sqlite file that comes with Django had a question mark next to it (the guy in the video didnt have that). So I clicked it and it prompted me to associate my sqlite file with a certain file type. To experiment I selected the python(.py) file type. Now when I open up I get an error with corrupt code (or at least that's how it looks to me. The error is "File was loaded in the wrong encoding: 'UTF-8.' When I click on that error message I am able to select from dozens of different encodings. I'm assuming that's the issue but I don't know for sure. Does anybody have a solution to this issue. Thanks. I will add two screenshots to clarify what I mean. Screenshot 1, list of options if I right click Screenshot 2 -
django channels: WebSocket is closed before the connection is established
I am pretty new in django channels. I read this tutorial to create a realtime chat application, but I have this error in Chrome: WebSocket connection to 'ws://127.0.0.1:8000/chat/stream/' failed: WebSocket is closed before the connection is established. in Firefox: Firefox can't establish a connection to the server at ws://127.0.0.1:8001/chat/stream/. The connection to ws://127.0.0.1:8001/chat/stream/ was interrupted while the page was loading. Please help me. Thanks a lot. -
Move file without opening in django-storages and S3
I am using django with django-storages and S3 to manage some uploaded files. These files can be uploaded in an "feature" folder, for example: /uploads/products/product_code/feature/filename.pdf and I want to move the files out of this feature folder, delete the original file (and eventually the containing folder when all files have been processed) so they can be found at: /uploads/products/product_code/filename.pdf I currently have the following code to do this: def move_files_in_folders(path, folder): files = default_storage.listdir(path+"/"+folder) returnable_file_list = list() for filename in files[1]: if filename is not '': movable_file = default_storage.open(path+'/'+folder+'/'+filename) default_storage.save(path+'/'+filename, movable_file) default_storage.delete(path+'/'+folder+'/'+filename) returnable_file_list.append(filename) default_storage.delete(path + '/' + folder) return returnable_file_list This works but it is very slow with long file lists as the system will have to open each file and re-save it. Is there a way I can refactor this code to avoid the expensive open and save calls? -
Django get_or_create and increment right after
I've got a problem. I want to store searched expression and increment its count right after. I use get_or_create method, but it throws an error everytime. models.py class TopSearch(models.Model): expression = models.CharField(max_length=255) count = models.IntegerField(default=0) and I want to do this: If searched expression exists, increment its count by 1. Otherwise, create it and immidietly increment its count by 1. Thank you ! -
django get parameters and pass int type
I have the below entry in urls.py url(r'^profile/(?P<price_id>[0-9]+)$', views.profile_view, name='profile'), Where the price_id parameter is generated by the below template snippet: 'Proceed' This is rendered by the below view: class QuotesResultsView(ListView): template_name = 'pages/quotes_results.html' paginate_by = 20 context_object_name = 'quotes_results' def get_queryset(self): session = self.request.session quotes = get_quotes(session) # return iterable from external api quotes_results = quotes['searchResults'] return quotes_results When the button is clicked in the rendered template it passes (via the url to the below view): def profile_view(request, price_id): request.session['price_id'] = int(price_id) .... However the price_id parameter arrives in the view as a string eg '8234234' instead of an int which I have to covert. In the earlier QuotesResultsView the price_id is an int within quotes_results, but between then and it appearing in the next view its a string? Do GET parameters always get passed as strings? -
Can't import django on PythonAnywhere
I'm trying to deploy a django app on PythonAnywhere, and I need to run manage.py in order to migrate the db. However, here's my current situation: It looks like Django is installed, but I can't import it. Any solution? -
Foreign key defaults to Auth User in Django
I'm using Django 1.11 I have a business model. class Business(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE) class Meta: verbose_name = 'business' verbose_name_plural = 'businesses' db_table = 'businesses' def __str__(self): return self.name When I run python3 manage.py makemigration business It gives You are trying to add a non-nullable field 'user' to business without a default; I want to set this field to use the logged in user id as foreign key by default. How to use Auth user id as default for user specific data record? -
How can I give the number two decimal in my template?
I use the total_prices in my template {{ data.total_prices }} # there shows 300 But how can I give it both float number? I means it looks like 300.00 in template. How to do with that? -
Django QuerySet reverse join
I have two models: class UserProducts(models.Model): user_id = models.ForeignKey('User', db_column='user_id', related_name='user_name') product_id = models.ForeignKey('Products', db_column='product_id', related_name='user_products') category_id = models.ForeignKey('categories', db_column='category_id', related_name='user_products') name = models.CharField(max_length=220, blank=True, null=False, default='') url = models.CharField(max_length=220, blank=True, null=True) grade = models.CharField(max_length=220, blank=True, null=True) price = models.CharField(max_length=220, blank=True, null=True) location = models.CharField(max_length=220, blank=True, null=True) quantity = models.CharField(max_length=220, blank=True, null=True) quantity_unit = models.CharField(max_length=220, blank=True, null=True) start_time = models.DateTimeField(blank=True, null=True) end_time = models.DateTimeField(blank=True, null=True) image = models.CharField(max_length=255, blank=True, null=True) is_verified = models.IntegerField(blank=True, null=True) is_organic = models.IntegerField() details = JSONField(blank=True, null=True) # This field type is a guess. created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(blank=True, null=True) image_id = models.ForeignKey('Files', db_column='image_id', related_name='image_products', blank=True, null=True) #variety_id = models.ForeignKey(ProductVarieties, db_column='variety_id', related_name='product_variety', blank=True, null=True) and class UserProductVarieties(models.Model): user_product = models.ForeignKey('UserProducts', db_constraint=False, related_name='product_variety') product_variety = models.ForeignKey('ProductVarieties', db_constraint=False) moq = models.IntegerField() moq_unit = models.CharField(max_length=10) created_by = models.ForeignKey('User', default=94, related_name='create_product_variety_name') updated_by = models.ForeignKey('User', default=94, related_name='update_product_variety_name') I want to nest all the UserProductVarieties inside the UserProduct queryset. I am trying to create a queryset and not just a specific field. Here are the things I've tried: Using a reverse serializer field. -> only shows the specific field A nested serializer inside UserProductsSerializer -> works with .create but not for listing. .select_related() on the queryset. The documentation only shows how … -
Django file myme types
I'm trying to validate mime types of files uploaded with a predefined list of validate mime types. I need to do the check the file in the buffer before save. I found magic-python and python mimetypes library. From docs looks like is just checking extensions and not the encoding. Using magic is easy: magic.from_buffer(open("testdata/test.pdf").read(1024)) but is dependent on the installation of libmagic: ImportError: failed to find libmagic. Check your installation My concern is that for libmagic I need to copy magic1.dll, regex2.dll, zlib1.dll onto the PATH or install depending on the OS environment, so can be an issue with predefined hosting environment. What is the best solution for this, and also please an example or link to a tutorial/example. -
Django model object is deleted when I update the model object that has as foreign key
I have this two models in my models.py archive: class Ticket(models.Model): name = models.CharField(max_length=50) description_issue = models.CharField(max_length=1000) pub_date = models.DateTimeField("publication date", default=timezone.now) class PossibleSolution(models.Model): title = models.CharField(max_length=50) description_solution = models.CharField(max_length=1000) final = models.BooleanField() sol_date = models.DateTimeField("solution date", default=timezone.now) tickets = models.ForeignKey(Ticket, blank=True, null=True) Example: I have a Ticket, with a name, description and the publication date, and then I create a PossibleSolution, and in the form from which I create the PossibleSolution, I choose the related ticket. Then, in another form, I update the original Ticket, changing it's name, and then I lose the PossibleSolution I created. What can be happening here? I can provide the forms related, if they are needed. -
Django-Oscar dashbaord perms - check request on every view
I have a multisite (django sites framework) oscar project, that uses the permission based dashboard. Each Site belongs to one Partner. I understand that users with is_staff==True have access to all views in the dashboard. And non-staff users with the partner.dashboard_access permission set, have access to a subset of views. I can set them using the permissions_map. As I have multiple sites, my users can log in several of them. They'd see the list views filtered, to show only the elements related to his partners. My scenario requieres one more thing. When the user access to a details or update view, this object must belong to one his partners. How can I achieve this? For example, by checking the request, I know if the current site belongs to a user's partner. The problem is I can't pass the request or any other argument to the elements in the permissions_map. So, what other choices I have? I may create a mixin that overrides dispatch() and checks the request, but then I'd need to override a lot of dashboard views to inherit the mixin. Maybe a decorator that wraps the urls in app.py files? a mixin for a dashboard parent view or … -
__str__ returned non-string (type NoneType)
when i try to save a step in the course, i am getting an error str returned non-string (type NoneType) you can download the screenshots using the below urls step page details when i try to save: error page my code is url patterns: urlpatterns = [ url(r'^$', views.course_list), url(r'(?P<pk>\d+)/(?P<pk>\d+)/$', views.step_details), url(r'(?P<pk>\d+)/$', views.course_details), ] models.py: class Course(models.Model): created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length = 255) description = models.TextField() order = models.IntegerField(default=0) course = models.ForeignKey(Course) class Meta: ordering = ['order', ] def __str__(self): self.title views.py: def step_details(request, course_pk, step_pk): step = get_object_or_404(Step, course_id = course_pk, pk=step_pk) return render(request, 'courses/step_details.html', {'step':step}) step_details.html: {% extends "layout.html"%} {% block title%} {{step.title}} - {{ step.course.title }} {% endblock title %} {% block content %} <article> <h2> {{ step.course.title }} </h2> {{ step.description }} {{ step.content|linebreaks }} {{ step.course.created_at }} {##} {# <section>#} {# {% for step in course.step_set.all %}#} {# <h3> {{ step.title}}</h3>#} {# {{step.description}}#} {# {% endfor %}#} {# </section>#} </article> {% endblock %} Thank you... -
Django app not responding on Apache with wsgi_mod
I'm trying to setup a Django website through Apache. For this I'm using a virtual machine running CentOS7 and use Apache 2.4.6. I've created a virtual environment with Python (3.6.2), installed Django (1.10.05) and mod-wsgi (4.5.18). Started new Django project, migrated database, launched developer server on address 0.0.0.0:8003 and from outside the VM I can connect to <VMs IP>:8003 without problem. However without the developer server, trying to relay on Apache, it does not work. My browser just says that it's unnable to connect to website and indeed, Apache's access log does not contain any trace of connection attempt. Same Apache hosts also another application written in Perl and it's working properly over its dedicated port. Bit of my settings.py that might be informative for you ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]', '<VMs address>'] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") And my httpd.conf looks like this: <VirtualHost *:8003> # using port 8003, because 80 is used by another app. Both ports are open on firewall Alias /static /var/www/zdm_ebok/static <Directory /var/www/zdm_ebok/static> Require all granted </Directory> <Directory /var/www/zdm_ebok/zdm_ebok> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess zdm_ebok python-path=/var/www/zdm_ebok:/var/www/zdm_ebok/venv/lib/python3.6/site-packages WSGIProcessGroup zdm_ebok WSGIScriptAlias / /var/www/zdm_ebok/zdm_ebok/wsgi.py </VirtualHost> I've granted access (664) access and ownership to … -
Have set up Django on Ubuntu 16.04 and now can't login
I have set up a simple Django project with MySQL on Ubuntu 16.04 using wsgi Have created a superuser as per the docs, and have verified that the user exists in the auth_user table, and that the status is superuser. Everything looks great! However, I can't login via the admin url - I just get a 500 server error and don't know of a way to check what could possibly be going wrong. However, if I run the site with the Django server (python manage.py runserver 0.0.0.0:8000), I can login with no problem. It doesnt make a difference whether DEBUG is set to True or False. I hope someone who's had the same type of issue can help! Many thanks. -
AttributeError: 'BigIntegerField' object has no attribute 'to_field'
i am newbie on peewee but have to solve a problem. I defined a table of my database: class Attendees(BaseModel): uid = BigIntegerField(null=False) email = CharField() first_name = CharField() last_name = CharField() location_id = BigIntegerField(null=False) preferred_language = CharField() is_current_employee = SmallIntegerField() company_id = BigIntegerField(null=False) department_number = BigIntegerField(null=False) team_name = CharField() In a second class i try to fetch using a select. def attended_by_department(departmentNumber): cond_attendance_join_first = rDB.Attendees.id = rDB.Attendances.attendee_id cond_events_join_sec = rDB.Attendances.event_id = rDB.Events.id cond_trainings_joins_third = rDB.Events.training_id = rDB.Trainings.id query = (rDB.Attendees.select().join(rDB.Attendances, on=cond_attendance_join_first) .join(rDB.Events, on=cond_events_join_sec) .join(rDB.Trainings, on=cond_trainings_joins_third) .where(rDB.Attendees.department_number == departmentNumber)) When i run the code until here, i got no error. But when i want to iterate over via for line in query: print (line.uid) i got an AttributeError. This is the last call: File "/home/xxx/Projekte/virtual_env_1/lib/python3.5/site-packages/peewee.py", line 875, in _join_metadata primary_key = fk_field.to_field AttributeError: 'BigIntegerField' object has no attribute 'to_field' I already tried to figure out the source of the missfortunes but i did't get it. Please help me. -
How Can I change the studio port number from 18010 in Openedx?
I am trying to Create a content group inside cohort but it is taking 18010 port http://localhost:18010/group_configuration/courseID_test but i need to open it in default studio port localhost:8001/group_configuration/courseID_test from where can i change this port. -
Docker running Django, rabbitmq, celery and flower in separate containers and linking?
im trying to setup celery/flower and rabbitmq in a dockerized setup. I am using nginx and my Django app in seperate containers and I have a rabbitmq instance setup in its own container. I looked into flower and they have a docker usage section in documentation (http://flower.readthedocs.io/en/latest/install.html) So I'm then assuming I can have celery and flower running on a separate container and send my tasks from my django container to this one. Ive search and haven't found a tutorial for this yet for my celery/flower container I have thus far run a python latest image, then installed celery and flower via pip. Running flower fails [I 170921 10:16:48 command:139] Visit me at http://localhost:5555 [I 170921 10:16:48 command:144] Broker: amqp://guest:**@localhost:5672// [I 170921 10:16:48 command:147] Registered tasks: as I haven't set the broker url. I do not know were I should place the configuration files for flower/celery to run from the container? also in my docker compose file how would I link this container in my Django app so I could use it? docker compose file: version: '3' services: nginx: image: django-ngnix:latest container_name: ngnix ports: - "8000:8000" depends_on: - web networks: - default web: image: itapp:latest container_name: itapp working_dir: /itapp/itapp command: … -
Django management command for running scrapy crawl
He I can trying to create a django management command for running my scrapy script. But I'm getting following error while running the script, File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\myProject\scraper\management\commands\extract_data.py", line 13, in run_from_argv self.execute() File "C:\Users\Anaconda3\lib\site-packages\django\core\management\base.py", line 314, in execute if options['no_color']: KeyError: 'no_color' This is my code from __future__ import absolute_import from django.core.management.base import BaseCommand class Command(BaseCommand): def run_from_argv(self, argv): self._argv = argv self.execute() def handle(self, *args, **options): from scrapy.cmdline import execute execute(self._argv[1:]) -
Django Got an unexpected keyword argument 'id_speaker'
I have a template that shows a list of speaker names that are urls, I want to click on these urls and go to the speaker page, I get the speaker by a unique id that looks like this "832fc2ca-787f-484b-b815-f82959607311", the problem is that I get the error get_speaker_by_id() got an unexpected keyword argument 'id_speaker' I think the problem is ether on urls.py or the speakers.html href. I looked at every relative question but I couldn't file a solution. urls.py url(r'^speakers', views.speakers_list, name='speakers'), url(r'^speaker/(?P<id_speaker>[0-9a-z\-]+)/$', views.get_speaker_by_id, name='get_speaker_by_id_url') This is the template that shows the list of speaker names speakers.html {% for speaker in all_speakers_list%} <div class="container"> <div class="row"> <div class="col-sm-6"> <a href="{% url 'get_speaker_by_id_url' speaker.speaker_id %}">{{ speaker.greek_name }}</a> </div> </div> </div> {% endfor %} views.py get_speaker_by_id(request, id_speaker): ''' Get speaker info by id ''' requested_speaker = Speaker.objects.get(speaker_id=id_speaker) template = loader.get_template('greekparliament/speaker.html') context = { 'requested_speaker': requested_speaker } return HttpResponse(template.render(context, request)) models.py class Speaker(models.Model): speaker_id = models.CharField(max_length=200, default='') english_name = models.CharField(max_length=200, default='', blank=True) image = models.CharField(max_length=200, default='', blank=True) email = models.EmailField(max_length=254, default='', blank=True) wiki_el = models.URLField(max_length=200, default='', blank=True) twitter = models.URLField(max_length=200, default='', blank=True) greek_name = models.CharField(max_length=200, default='') wiki_en = models.URLField(max_length=200, default='', blank=True) website = models.URLField(max_length=200, default='', blank=True) -
Groups in Django admin
Django==1.11.5 Django admin by default contains a section "AUTHENTICATION AND AUTHORIZATION". Inside it are Groups and Users. I'd like to group my models in the same way. I tried to find in Django how it is organized: 1) looked for a template in django/contrib/admin/templates/admin; 2) looked into django/contrib/auth.admin.py. Well, I failed. Could you tell me where to look for the example in Django. And maybe just give me a kick here: how to organize such a grouping in admin?