Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django wont start with Docker, new to Docker
Docker starts my django server and says its up at 0.0.0.0:8000, but i cant reach it in my browser, neither 0.0.0.0:8000 nor 127.0.0.1:8000 work web_1 | You have unapplied migrations; your app may not work properly until they are applied. web_1 | Run 'python manage.py migrate' to apply them. web_1 | April 30, 2017 - 03:36:35 web_1 | Django version 1.8.5, using settings 'my_project.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. -
How to add the high cahrt function in my function in view.py?
I have follow this tutorial How to pass all the data in dataframe that extract from excel sheet to highchart? and now I need to build high chart function in another function, which mean in my interface I have my dataframe now I need to add the high chart under the dataframe but not able. This is my code for datafarme def read_raw_data(request): Wb = pd.read_exce(r"C:/Users/S/Desktop/excel/okAhead.xlsm") Step1_Result = Wb.replace(np.nan, 0, regex=True) drop_column = Step1_Result.drop(['facility','diecodename','rev','step], 1) uniquevaluesproduct = np.unique(drop_column[['Product']].values) total_count=drop_column['Product'].nunique row_array=[] for name, group in drop_column.groupby('Product'): # print the name of the regiment print(name) # print the data of that regiment group=group.values.tolist() row_array.append(group) print(group) i=1 temp=row_array[0] while i<total_count: newb = temp + row_array[i] temp=newb i = i + 1 print(newb) print(temp) b = ['indicator', 'month', 'ww', 'test_time', 'phi', 'Product'] #dataframe = pd.DataFrame.from_records(newb, columns=b) superstupidkia=temp test=pd.DataFrame.from_records(superstupidkia, columns=b) table = test.style.set_table_attributes('border="" class = "dataframe table table-hover table-bordered"').set_precision(10).render() context = { "result": table } return render(request, 'result.html', context) I wish to add this code in above function but not able: class BarView(HighChartsBarView): categories = ['Orange', 'Bananas', 'Apples'] @property def series(self): result = [] for name in ('Joe', 'Jack', 'William', 'Averell'): data = [] for x in range(len(self.categories)): data.append(random.randint(0, 10)) result.append({'name': name, "data": data}) return … -
confusion on which serializer to use to update user profile
I have a profile model for user to update. I want to have a rest api for that. I have a profile model which is too big than usual. I am working to update the user profile but I am having confusion on which serializer should i use to update the profile. Here is what i have done till now I created the serializer for user and user profile. class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('token', 'user','current_location', 'permanent_location', 'dob', 'about_me', 'gender_status', 'create_profile_for', 'marital_status', 'height', 'weight', 'body_type', 'complexion',) # # def update(self, instance, validated_data): # # instance = super(ProfileSerializer, self).create(validated_data) # profile = Profile.objects.update(user=instance.user, **validated_data) # return profile class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) class Meta: model = User fields = ('id', 'profile', 'username', 'first_name', 'last_name',) def update(self, instance, validated_data): profile = validated_data.pop('profile') Profile.objects.update(**profile) This is my view class UserProfile(APIView): serializer_class = UserSerializer def get(self, request, token=None, format=None): """ Returns a list of profile of user """ reply={} try: profile_instance = Profile.objects.filter(user=self.request.user) if token: profile = profile_instance.get(token=token) reply['data'] = self.serializer_class(profile).data else: reply['data'] = self.serializer_class(profile_instance, many=True).data except: reply['data']=[] return Response(reply, status.HTTP_200_OK) def post(self, request, token=None, format=None): """ update a profile """ profile=None if not token is None: try: profile = … -
Force Remove Phpmyadmin and PHP7.0 Sub-process Error
I'm just tired of PHP7.0 forcing itself on me! I've deleted all files relating to php7.0 on my vps and I've tried uninstalling it with different command lines yet it will bring up the below error..even after I deleted it folders. I wanted to install supervisor but I couldn't because of the below error that PHP is still giving. I Don't want to use phpmyadmin and PHP7 anymore.! I'm on Ubuntu 16.04. What am I missing to clear this? Reading package lists... Done Building dependency tree Reading state information... Done supervisor is already the newest version (3.2.0-2ubuntu0.1). 0 upgraded, 0 newly installed, 0 to remove and 54 not upgraded. 2 not fully installed or removed. After this operation, 0 B of additional disk space will be used. Do you want to continue? [Y/n] y Setting up php7.0-fpm (7.0.18-1+deb.sury.org~xenial+1) ... Not replacing deleted config file /etc/php/7.0/fpm/php.ini Job for php7.0-fpm.service failed because the control process exited with error code. See "systemctl status php7.0-fpm.service" and "journalctl -xe" for details . invoke-rc.d: initscript php7.0-fpm, action "start" failed. dpkg: error processing package php7.0-fpm (--configure): subprocess installed post-installation script returned error exit status 1 dpkg: dependency problems prevent configuration of phpmyadmin: phpmyadmin depends on libapache2-mod-php | … -
Pytest uploaded files being placed in MEDIA_ROOT folder even though @override_settings(MEDIA_ROOT) has a different directory
I overrode my save() method on my model for profile image resizing after being uploaded. However, when I run my test using pytest, the files are placed directly into my media directory instead of the @override_settings test directory. What am I doing wrong? Below is my code: MODEL: def user_directory_path(instance, filename): ext = filename.split('.')[-1] new_name = '{0}_{1}.{2}'.format('profile', instance.profile.user.username, ext) return 'user_{1}_{0}/avatar/{2}'.format(instance.profile.user.id, instance.profile.user.username, new_name) class ProfileAvatar(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(upload_to=user_directory_path, default='generic/default.jpg') def save(self, *args, **kwargs): ext = self.avatar.name.split('.')[-1] image = Image.open(self.avatar) image_resize = ImageOps.fit(image, (300, 300), Image.LANCZOS) image_resize_io = BytesIO() if ext in ['jpg', 'jpeg']: image_resize.save(image_resize_io, format='JPEG') elif ext in ['png']: image_resize.save(image_resize_io, format='PNG') temp_name = self.avatar.name self.avatar.save(temp_name, content=ContentFile(image_resize_io.getvalue()), save=False) super(ProfileAvatar, self).save(*args, **kwargs) TEST: @override_settings(MEDIA_ROOT='/tmp/django_test') def test_avatar_upload_image_saves(self, client): image = SimpleUploadedFile(name='test.jpg', content=open( 'profiles/tests/test_images/test.jpg', 'rb').read()) response = client.post(reverse('profiles:av-upload', kwargs={ 'pk': self.user.id, 'username': self.user.username}), {'avatar': image}, follow=True) avatar = ProfileAvatar.objects.select_related( 'profile').get(profile_id=self.user.id) assert avatar.avatar.name == 'user_Testy2McT_3/avatar/profile_Testy2McT.jpg', 'Should return new filename and path.' -
Django migration and MariaDB: SQL Error (1005): Can't create table
MariaDB: 10.2.22, Django: 1.10.6, HeidiSQL: 9.4.0.5125 What can be the cause of the following error and how could it be prevented? SQL Error (1005): Can't create table databasename.#sql-a71_1824 (errno: -1 "Internal error < 0 (Not system error)") I'm using Django and MariaDB. In a Django model, I've chaned the field lenght of a CharField. While 'makemigrations' runs fine, 'migrate' aborts with above error. Afterwards, I tried to modify the field size directly (I'm using HeidiSQL),but got the same error msg. -
How to upload a file in django and run a python script on it?
I have worked on a project on python that takes input as an Excel file and returns its output as an Excel file in the same folder.I am a rookie in Django and want to make a website so that a user can upload his file and get the output file downloaded when the python script has finished working. Kindly help me with, 1. How to pass uploaded file to a python script ? 2. How to run the python script in django ? 3. How to get the file downloaded once processing has been done?