Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin static files
I want to deploy a server using nginx, django & gunicorn. I created a django project in /home/myproj/ with STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static'), did all the migrations, and then python3 manage.py collectstatic then I changed the nginx configuration: server { listen 80; server_name www.myserver.com; access_log /home/nginx.log; location /static/ { alias /home/myproj/static/; autoindex on; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } when I start the server gunicorn myproj.wsgi:application the start page is displayed correctly, but the admin panel does not load the css styles. What am I doing wrong? I've also noticed that if in settings.py -> debug = False, I get a 404 error P.S. I'm still not good in linux, so please write the full commands. -
Not getting the nav parent-page active when I'm in child-page
Parent page is good like so: When I click on the child page it does not behave like parent does: Although I have the base.html in child page it wont show as wished. I have tried several solutions with no luck so hopefully you can guide me in the right way. Still a newbie and appreciate all your help, folks! base.html <script> $(document).ready(function() { $('li.active').removeClass('active'); $('a[href="' + location.pathname + '"]').closest('li').addClass('active'); }); </script> ... <ul class="nav navbar-nav"> <li class="active"><a href="{% url 'member_overview' %}"> {% trans 'Members' %}</a></li> ... </ul> member_overview.html {% extends 'base.html' %} ... <div class="row"> <a class="btn btn-primary btn-lg" href="{% url 'member_signup' %}"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> {% trans 'New Member' %} </a> </div> ... member/urls.py (if it helps) urlpatterns = [ url(r'^member_overview/$', views.member_overview.as_view(), name='member_overview'), url(r'^member_signup/$', views.member_signup, name='member_signup'), ... ] -
Django not response to Ajax call while doing a computing intensive task
I am recently using Django to program my web interface for my "scientific computing engine". I wrap the "computing engine" as a python module and call it inside the Django Framework. The compute() function of the "engine" takes several minutes to run (I use ajax to trigger it) , at the same time, I let the front-end make extra ajax call every 0.5 second to update the CPU and Memory status to the front-end. But I find the server is not respond to the extra ajax call until the compute() finishes. After search around, I think I might use the idea of asynchronous or multithreading so I make the function in views.py like below. def submit(request): #some prepare ........ # call the engine t = Thread(target = compute) t.start() return HttpResponse("started") But the system still not response to my extra ajax call until the compute() finish (The "engine" only use around 20% of the CPU, so there is plenty of computing power left). I am a newbie in back-end programming, I am not sure about how Django or backend server handle request internally. Thank you so much if anyone can give me some hint about how to handle this situation. -
OperationaLError MySQL Failed to Connect With Localhost
I'm having a very hard time in making MySQL work again. I installed MySQL server and was able to get it to work at first. When navigating through my site, I got the below error. OperationalError at / (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") I changed the bind-address to localhost, yet it failed to pick up. read through different answers online, yet none worked for me. I'm still finding hard to figure out why it stopped working all of a sudden. When I run this command sudo service MySQL restart, I will get the below error, Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details. When I run the systemctl status mysql.service, I get the below error details, mysql.service - MySQL Community Server Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: en Active: activating (start-post) (Result: exit-code) since Sun 2017-04-30 11:4 Process: 12946 ExecStart=/usr/sbin/mysqld (code=exited, status=1/FAILURE) Process: 12937 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exi Main PID: 12946 (code=exited, status=1/FAILURE); : 12947 (mysql-systemd Tasks: 2 Memory: 328.0K CPU: 406ms CGroup: /system.slice/mysql.service └─control ├─12947 /bin/bash /usr/share/mysql/mysql-systemd-start post └─13009 sleep 1 See my config [mysqld_safe] socket = /var/run/mysqld/mysqld.sock nice = … -
How do I upload files of arbitrary size to mezzanine.core.fields.FileField
The featured image on the mezzanine.blog.models.BlogPost content type is of type mezzanine.core.fields.FileField. When I try to upload a featured image there is a 2.5MB limit on the size of the file. Where is this value defined? I want to increase or remove this restriction. -
Disable or hide an entry from model temporarily in Django
How can it be possible to disable or hide an entry from model temporarily when certain conditions are satisfied in the view function like if statement. -
How create dynamic choices field?
I am tring to create dynamic choices to my symbol field. I have form with MultipleChoiceField where users add new data. I want to take all data from Dictionary modal put it inside choices and show in my form but in the same time I dont need to show data which is already in Requirement modal. How to make it?! Right know next code only show all data from Dictionary modal. Also as you can see from models.py Requirement has project field. It means that in every project there will be different requirements. models.py: class Dictionary(models.Model): symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) class Requirement(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) forms.py: class RequirementForm(forms.ModelForm): symbol = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) class Meta: model = Requirement fields = ('symbol',) def __init__(self, choices, *args, **kwargs): super(RequirementForm, self).__init__(*args, **kwargs) self.fields['symbol'].choices = [(x.symbol, x.name) for x in Dictionary.objects.all()] -
No Acheteur matches the given query
My models.py : class Acheteur(models.Model): id_compte=models.OneToOneField(User, on_delete=models.CASCADE,null=True ) id_panier=models.OneToOneField(Panier, on_delete=models.CASCADE,null=True ) My views.py : panierListeNonUtilise=Panier.objects.filter(utiliser="false") for panier in panierListeNonUtilise: client1 = get_object_or_404(Acheteur,id_panier=panier) client1.delete() I have this Errors : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/home/ Raised by: produit.views.produit_list No Acheteur matches the given query. Any Help, Please :) -
Django can't figurout how to pass paramater from url
I am trying to pass parameter from url. I have tried many tutorials and can't figure out what am i doing wrong. my url from url.py: url(r'^reports/(?P<test>\d+)/$', views.reports,name='reports'), # report view my view from view.py: def reports(request, test=0 ): title = "Reports" # title shown in browser window view ="admin/pc/reports.html"# where is the page view user_name = request.user.get_username() #User name return render(request, 'admin/home.html', {"title":title,"USER_NAME" : user_name,"page" : view, 'pid':test}) and my template: {% block content %} REPORTSz id = {{pid }} {% endblock %} but no matter what I do I always get: Reverse for 'reports' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['admin/reports/(?P\d+)/$'] So my question is how to correctly pass parameter from url? -
Browserify doesn't works in Docker container
I'm setting up my project and i set browserify to works with my front end assets and refresh the browser. For the back end i'm using django, so, i made a proxy between both for works in the same time: gulfile.js // Start a server with BrowserSync to preview the site in function server(done) { browser.init({ // server: PATHS.dist, //port: PORT proxy: 'localhost:8000', notify: false }); done(); } But it doesn't works when i rise up the project with composer, simply doesn't show me anything when i rise up composer: sass_1 | [BS] Proxying: http://localhost:8000 sass_1 | [BS] Access URLs: sass_1 | ----------------------------------- sass_1 | Local: http://localhost:3000 sass_1 | External: http://172.18.0.7:3000 sass_1 | ----------------------------------- sass_1 | UI: http://localhost:3001 sass_1 | UI External: http://172.18.0.7:3001 sass_1 | ----------------------------------- sass_1 | [BS] Couldn't open browser (if you are using BrowserSync in a headless environment, you might want to set the open option to false) It works fine when i rise up since my computer, without using Docker, but in docker it can open my browser and i can't get into 3000 port. I got the same problem with django-debug-toolbar, but i solved it putting the internal ips got from docker configuration. I tried … -
Latex templates for python/django book?
Does anyone have advices on latex samples/templates for setting up a document with Python/Django code inside it ? -
how does i redirect to network
I am trying to add user in one app and then calling network app to to display the user profile. but i am not able to access my network app. what am i doing wrong here. def post(self, request, *args, **kwargs): form = LoginForm(request.POST) if form.is_valid(): if request.POST['username'] and request.POST['password']: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponse(reverse("network")) else: return HttpResponse("alpha") else: return LoginForm() and my url file is urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^login', views.LoginView.as_view(), name='login'), url(r'^register', views.RegistrationView.as_view(), name='registration'), url(r'network', include('network.urls', namespace="network", app_name='network')), how do i access my network url becosause this is not working -
Django how to create an invoice model from vehicle model
I have a model called vehicle. class Vehicle(models.Model): name = models.CharField(max_length=200) price = models.models.DecimalField(max_digits=19, decimal_places=2) the following is sample data stored. id name price 1 cycle 100 2 bus 10000 3 car 1000 Now i want make invoice based on the order. Someone orders for 2-cycles, 1 bus and 3 cars. I want to have a model named Invoice which will have 2-cycles, 1 bus and 3 cars. in it. and at the end create the invoice in the browser like below: id vehicles no_of_ordered unit_price total_price 1 cycles 2 100 200 2 bus 1 1000 1000 3 car 3 10000 30000 How to create the model: class Invoice(models.Model): vehicles = models.ManyToManyField(Vehicle, null=True, blank=True) After that how to create that list of invoice using the above model -
Django - create instance of model with user_id
I have two models, player and game. The model player is an extended Django Auth User Model. I am trying to create an instance of game with the User ID and not the player ID which is automatically created. Is it possible to do that in a single query? Django Version: 1.11. new_game = Game(active=False, ### user_id=request.user.id, display_every=display_every, lead_to_win=lead_to_win, p1_coins=num_of_coins, p2_coins=num_of_coins, created=django.utils.timezone.now()) new_game.save() This command creates the instance. Its the user_id which is not working and it only works with player_id which I have to fetch with another query. I have commented it to highlight the line. class Game(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) active = models.BooleanField(default=False) over = models.BooleanField(default=False) winner = models.SmallIntegerField(null=True) player1 = models.OneToOneField(Player, related_name='player1') player2 = models.OneToOneField(Player, related_name='player2', null=True) p1_coins = models.IntegerField(default=100) p2_coins = models.IntegerField(default=100) array = models.TextField(default=json.dumps([(None, None) for x in range(100)])) round_no = models.IntegerField(default=0) display_every = models.IntegerField(default=1) lead_to_win = models.IntegerField(default=5) created = models.DateTimeField(default=django.utils.timezone.now) class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='/static/images/anon.jpg', upload_to='static/images/profile-pics/', null=True, blank=True) created = models.DateTimeField(default=django.utils.timezone.now) last_seen = models.DateTimeField(default=django.utils.timezone.now) matches = models.IntegerField(default=0) wins = models.IntegerField(default=0) losses = models.IntegerField(default=0) win_string = models.TextField(blank=True, default='') Also, I have both the models in different apps if it matters. Please help. Thanks. -
Unable to use login method in django
I am trying to use the Login method to log in a user who is validated from an external API. def whmcs_login(request): if request.method == 'POST': username1 = request.POST['username']; password1 = request.POST['password']; whmcs1 = whmcs() login = whmcs1.login(username1=username1,password1=password1) if login['result'] == 'success': userid = login['userid'] try: whmcs_i = Profile.objects.get(whmcsid=userid) user = User.objects.get(id=whmcs_i.user_id) user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) except Profile.DoesNotExist: whmcs_data = whmcs1.getuser(userid=userid) user = User.objects.create(username='random', password='33e32121', first_name=whmcs_data['firstname'], last_name=whmcs_data['lastname']) user.profile.whmcsid = userid user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) I keep getting the following error when ever I use the login method "'dict' object is not callable" -
@shared_task decorator doesn't work
The problem: @shared_task decorator doesn't work, when I import data from custom files. I mean, when I start celery, all tasks under @shared_task doesn't appear in list of tasks. For example, in this case @shared_task decorator doesn't work: from __future__ import absolute_import, unicode_literals from celery import shared_task from .models import foo @shared_task def my_foo_backup(id): my_foo = foo(....) ... ... This is example, when @shared_task works: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def my_foo_backup(id): my_foo = foo(....) ... ... Why?!? -
javascript is not acting on HTML content loaded via jquery ajax
I am trying to create a form filled with ajax requests, but my javascript is not acting on the HTML that i loaded with the ajax call to my server. ---template---- <form id="my_form" class="pure-form pure-form-stacked"> <fieldset> <legend>Book Tickets</legend> <div> <label for="state">Theatre:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <select id="state" class="pure-input-1-2"> {% for mul in film.multiplexes.all %} <option id="op{{ forloop.counter }}" title="{{ mul.name }}">{{ mul.name }}</option> {% endfor %} </select> </div> <br> <div id="date-input"> </div> <br> <div> <input type="radio" name="time" value="morning" checked> 10:00 &nbsp;&nbsp; <input type="radio" name="time" value="evening"> 1:00 &nbsp;&nbsp; <input type="radio" name="time" value="night"> 6:00 </div> <br/> <input type="submit" class="button" value="Book Ticket"> </fieldset> the html is loading just fine inside div with id date-input this is my views.py ----views.py--- def bookdate(request): if request.is_ajax(): mov = request.POST.get('mov') multiplex = request.POST.get('multiplex') movie = Movies.objects.get(title = mov) for mult in movie.multiplexes.all(): try: if mult.name == multiplex: date = mult.date.all() return render(request, 'jtc/bookdate.html', {'dates':date}) except: pass return render(request, 'jtc/bookdate.html',{}) This is my script that is acting on my current page to load radio buttons for the selected dropdown -------template------- <script> //for date $(document).ready(function(){ $("#state").on('change', function(){ console.log($(this).find("option:selected").prop("title")); $.ajaxSetup({cache:'true'}); $.ajax({ url: "{% url 'bookdate' %}", type: "post", data: { 'multiplex' : $(this).find("option:selected").prop("title"), 'mov': $("#mymovie").text(), 'csrfmiddlewaretoken': getCookie('csrftoken') }, success: function(data){ document.getElementById("date-input").innerHTML=data; }, failure: function(){ … -
Design of web application
I'm building a web application(django) that provides interface to call some data analytic APIs. The APIs are developed together as part of the web application. However, I plan to use Ajax to invoke these web services(expensive task) since i do not want the UI to be blocked. Currently while i was researching i came across this tool celery and I'm not sure how it fits into the picture or if I'll even need it since I'll be invoking the web services via Ajax. -
How to handle json response in Django
I have views, that in case of error return JsonResponse({'success': True}) I want, in case of error, the error alert to appear. How would i do that using json? Right now, I in case of error only get this in the browser: How could i handle json response with ajvascript, to activate alert? -
(django) create static variable stored in database and accessible through admin
I have a blog that should publish articles in a weekly rythm. I ordered these articles with a number attribute which is a PositiveIntegerField that's not editable through admin. (And it's 1-based) Now I want to get the pub_date. (Which is simply the day the article becomes published. It should be a value in the normal date-formate.) There is always the day, I start the blog (I don't want to hard-code this because I'm still in beta, and it didn't worked when I tried it) and every week one article should be published. Let's call the day I start the ZERODAY. pub_date is now ZERODAY + timedelta(days=7*(self.number-1)). (Remember, self.number is 1-based.) Because I can do that simple math I don't want pub_date becoming a database field. (It would mean trouble because at least the two are the same information and it would mean to have more db fields than needed.) So I think I should create a static variable ZERODAY (a models.DateField) that I can acces and change through admin. -
No Acheteur matches the given query
My models.py : class Acheteur(models.Model): id_compte=models.OneToOneField(User, on_delete=models.CASCADE,null=True ) id_panier=models.OneToOneField(Panier, on_delete=models.CASCADE,null=True ) My views.py : panierListeNonUtilise=Panier.objects.filter(utiliser="false") for panier in panierListeNonUtilise: client1 = get_object_or_404(Acheteur,id_panier=panier) client1.delete() I have this Errors : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/home/ Raised by: produit.views.produit_list No Acheteur matches the given query. Any Help, Please :) -
If loop is not working in template
If loop within the for loop of template is not working.It is still showing unavailable items. This is the code of my template form-template.html {% for field in form %} {% if eventprojector.projector.available %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }} </span> </div> <label class="control-label col-sm-2">{{ field.label_tag }} </label> <div class ="col-sm-10">{{ field }} </div> </div> {%endif %} {% endfor %} -
Django Foreign Key err 150
I have an article app article/models.py looks like: class Person(models.Model): PersonID = models.BigAutoField(primary_key = True) # Some other fields. class Blog(models.Model): BlogID = models.BigAutoField(primary_key = True) person_blog = models.ForeignKey(Person) When I migrate it using: python manage.py makemigrations article python manage.py migrate I am using Django 1.10 and MariaDB. I ran python manage.py sqlmigrate article 0002 to check out the SQL commands being executed. I found that the error was due to mismatch in datatypes of person_blog field and PersonID field. PersonID is BigInt whereas person_blog is Int(11). The problem is that Foreign key field conversion to SQL code is a 3 step process: Create a field Create an INDEX Alter Table and add constraint for foreign key. There is no way in django migration to create an normal INDEX. How can I create foreign key manually using django migrations. -
How to pass a view function with arguments in a decorator to another decorator in django
I have been trying to find a solution for this for hours. I have already gone through many SO posts like this, this and this. I am using django-guardian to implement object level permissions in my django app. I am trying to implement permission_required decorator dynamically. The idea is to create another decorator which can switch between permission required decorators and then pass view function to respective permission_required decorator. urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', Test.as_view()), url(r'(?P<handle>[-\w]+)/(?P<method>[-\w]+)/(?P<id>[-\w]+)/$', Test.as_view(), name='handler'), ] Views.py class Test(View): @decorator_switch def get(self, request, *args, **kwargs): return HttpResponse('Test View') decorator_switch from api.mappings.permission_mappings import perm_mappings def decorator_switch(func): def wrapper(instance, request, *args, **kwargs): print(kwargs) permission_decorator = \ perm_mappings.get('handles').get(kwargs.get('handle')).get('actions').get(kwargs.get('method')) return permission_decorator(func)(request)(args)(kwargs) return wrapper permission_mappings from django.contrib.auth.decorators import permission_required as django_perm_req from api.decorators.guardian_perm_req import permission_required as guardian_perm_req from pyteam.models import Team perm_mappings = { 'handles': { 'team': { 'actions': { 'get': guardian_perm_req('pyteam.retrieve_team', (Team, 'id', 'id')), 'create': django_perm_req('pyteams.add_team', raise_exception=True), 'update': guardian_perm_req('pyteam.change_team', (Team, 'id', 'id')), 'delete': guardian_perm_req('pyteam.delete_team', (Team, 'id', 'id')) } } } } After this I opened url http://localhost:8000/team/get/1/ But I got an exception GuardianError at /team/get/1/ Argument id was not passed into view function I checked in kwargs of views as well as kwargs of decorator of decorator switch for … -
PHP vs Python for web application development [on hold]
I am starting out to build an application for university students as my last semester project. A lot of online research tells me that Python has an edge over PHP in the long run, and I'm quite keen on choosing Python along with Django based on that feedback. I would really like some more insight from experienced programmers on this. P.S. I have worked on building a web application with JSP and some front end previously, and have some basic HTML, CSS, JavaScript, jQuery and Ajax knowledge. (None with Bootstrap, angularJS or Node.js). I have some basic Python knowledge as well, and absolutely none in PHP. I have about a month to finish this project, so as much as I want to learn from this, I also want to deliver it by the deadline.