Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search string in database with django. icontains and iexact lookups not fulfill my requirements
I have products database in Django. A Product name Eg-(ABCD-E34F). If user search 'abcd34'. How will i get the object of ABCD-E34F product. -
save slug for product and company as soon as they are saved
I have a product and company model where slug is included for better detail view in the url. I have used pre_save signal to save the slug as soon as the product and company are saved to the database. The code I have written is not saving the slug so when I post product form I get an error regarding slug Here is my code class Product(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) company = models.ForeignKey('Company', related_name='products', blank=True, null=True, on_delete=models.SET_NULL) website = models.URLField(unique=True) slug = models.SlugField(unique=True) class Meta: verbose_name= 'Product' verbose_name_plural= 'Products' def __str__(self): return self.name def hits(self): self.hits += 1 self.save(update_fields=['hits']) class Company(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) slug = models.SlugField(unique=True) description = models.CharField(max_length=400) editor = models.ForeignKey(User, related_name='company') # product = models.ForeignKey(Product, related_name='company') def get_absolute_url(self): return reverse("products:view-company", kwargs={"slug": self.slug}) def create_slug(instance, new_slug=None): slug = slugify(instance.name) if new_slug is not None: slug = new_slug qs = Company.objects.filter(slug=slug).order_by('-id') if qs.exists(): new_slug = "%s-%S" %(slug, qs.first().id) return create_slug(instance, slug=new_slug) return slug def pre_save_slug_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) from django.db.models.signals import pre_save pre_save.connect(pre_save_slug_receiver, sender=Company) def create_slug(instance, new_slug=None): slug = slugify(instance.name) if new_slug is not None: slug = new_slug qs = Product.objects.filter(slug=slug).order_by('-id') if qs.exists(): new_slug = "%s-%S" %(slug, … -
How to display comments and it's replies in django templates?
I want to display comment and it's replies in the template. But there is an issue, every reply may have some other replies. The below snippet is my Comment and CommentReply model: class Comment(models.Model): author = models.ForeignKey(Profile, related_name="c_sender", on_delete=models.CASCADE, unique=False) comment = models.CharField(max_length=500, unique=False) created_date = models.DateTimeField(auto_now_add=True) edited_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.comment @property def replys(self): return CommentReply.objects.filter(comment_id=self) class CommentReply(models.Model): comment_id = models.ForeignKey(Comment, related_name='sender', on_delete=models.CASCADE) reply_id = models.ForeignKey(Comment, related_name='reply', on_delete=models.CASCADE) My question is how to display comments and it's replies under it, and every reply may have some other replyies that I want to display them too. -
How can i call a html template without any view in django
I want to call index.html template to particular URL without calling any view. is it possible in django? -
Error in installing My-SQL Python in my Django Project
I am new to django ,and i having this error installing My-SQL Python in my django environment . I tried most of the answers posted earlier . When i do 'pip install MySQL-python' on cmd i am getting this error error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279 , but i have already installed windows sdk 7.1 and Microsoft Visual C++ x64Redistributable 10.0 from the link , Kindly help me out here . This is what i am getting (env) C:\Users\HP\prj\env\plm>pip install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-python Running setup.py bdist_wheel for MySQL-python ... error Complete output from command c:\users\hp\prj\env\scripts\python.exe -u -c "im ort setuptools, tokenize;__file__='C:\\Users\\HP\\AppData\\Local\\Temp\\pip-bui d-n_ns79ya\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__) code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exe '))" bdist_wheel -d C:\Users\HP\AppData\Local\Temp\tmpbu_gvnsapip-wheel- --pyth n-tag cp34: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.4 copying _mysql_exceptions.py -> build\lib.win-amd64-3.4 creating build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.4\MySQLdb creating build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.4\MySQLdb\cons ants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.4\MySQLdb\co stants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.4\MySQLdb\constant copying MySQLdb\constants\REFRESH.py -> … -
How to access request.FILES in my views?
Trying to upload an image to a model image field with AJAX. Here's my code: js $('input#id_banner_image').on('change', function(e) { $.ajax({ type: 'POST', url: '/change_banner_image/', data: { image: URL.createObjectURL(e.target.files[0]), csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() } }) }); views def change_banner_image(request): if request.is_ajax(): print('AJAX') #prints image = request.FILES['id_banner_image'].name #this is wrong profile = get_object_or_404(Profile, user=request.user) profile.image = image profile.save() return HttpResponse() How do I correctly grab the image in my views? I know that's the bit that's wrong. -
Django Status 200 but 'Failed to Load Response Data" On Certain Image Uploads
I'm making an ajax post request to the Python Django view below which always return a success json response. # views.py @csrf_exempt def success_response(request): """ Returns a http response with a JSON success state :param request: :return: """ return JsonResponse({'success': True}) In each ajax post request, i'm attaching an image file in enctype=multipart/form-data format. As you can see, here is an example request payload: ------WebKitFormBoundarymYCuLcqA6kEkqMA7 Content-Disposition: form-data; name="file"; filename="willprobablycrash.png" Content-Type: image/png ------WebKitFormBoundarymYCuLcqA6kEkqMA7-- How is it possible that images below a certain image dimension (below 960px x 1141px) return the intended response {"success": true} while images above the said dimension return Failed to Load Response Data? In both success and error cases, the status_code in the response is 200. -
After parsing JSON with Volley library i don't have any error but result is not displaying
I'm trying to access json data via Android using Volley Library,and for the backend of the webserver i've used python.Here is my server side code: def showAndroid(request): users=User.objects.all() data = serializers.serialize('json', users, fields=('nom', 'prenom', 'postnom', 'adresse','tel','mail')) return HttpResponse(data, content_type='application/json') When i access the URL i obtain the folllowing result: See also my android code: package com.example.lislis.mesexercices; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class UserJson extends AppCompatActivity { EditText nom,prenom,postnom,email; Button ajouter,voir; TextView list; RequestQueue requestQueue; String insertUrl="http://192.168.1.14:8000/webservices/insert-users/"; String showUrl="http://192.168.1.14:8000/webservices/afficher-users/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_json); nom=(EditText)findViewById(R.id.nom); prenom=(EditText)findViewById(R.id.prenom); postnom=(EditText)findViewById(R.id.postnom); email=(EditText)findViewById(R.id.email); ajouter=(Button) findViewById(R.id.ajouter_user); voir=(Button)findViewById(R.id.afficher_users); list=(TextView)findViewById(R.id.list_users); requestQueue= Volley.newRequestQueue(this); voir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, showUrl, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray users=response.getJSONArray("data"); for(int i=0;i<users.length();i++) { JSONObject user=users.getJSONObject(i); String fname=user.getString("prenom"); String lname=user.getString("nom"); String mname=user.getString("postnom"); String mail=user.getString("mail"); list.append(fname+" "+lname+" "+mname+" "+mail+"\n"); System.out.println("Tototo\n"+fname+" "+lname+" "+mname+" "+mail+"\n"); } list.append("===\n="); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue.add(jsonObjectRequest); } }); } } But when … -
deepcopy Django request
What I want to do is to make a copy of the Django request, and change the sensitive information within it, and then log it in a file. So I make a middleware to do that. from django.utils.deprecation import MiddlewareMixin import copy class RecordMiddleware(MiddlewareMixin): """ record the request,but hide the sensitive info """ def process_request(self, request): # in this case, the original request is changed dic = request.__dict__.copy() # in this case, TypeError: can't pickle uwsgi._Input objects # dic = copy.deepcopy(request.__dict__) hide_auth_token(dic) hide_auth_token(dic.get('META', None)) # here you can log it in a file print('middleware, request is {}'.format(dic)) print('original is {}'.format(request.__dict__)) def hide_auth_token(dic): if not isinstance(dic, dict): return if 'HTTP_AUTHORIZATION' in dic: ha = dic['HTTP_AUTHORIZATION'] if len(ha) > 10: dic['HTTP_AUTHORIZATION'] = ha[0:len(ha) - 10] + 'XXX-XXX-XX' The problem is shallow copy will not keep the original request, while deepcopy will raise an error. Does anyone has experience for this problem? -
django static file directory
in Django template file, I can use <link href="/static/css/bootstrap.min.css" rel="stylesheet"> to include my css file in /static/css I have such a javascript which load background img, $.backstretch([ "/static/img/backgrounds/a.jpg" , "/static/img/backgrounds/b.jpg" , "/static/img/backgrounds/c.jpg" ], {duration: 3000, fade: 750}); but this script can not find the img path. So I wonder what is the root path for javascript regarding my web -
Clumsy repeat-myself django permission check
I have a class based view for a Problem object. I only want the author of the Problem to be able to view the Problem cbv. Other logged-in users should be redirected to a forbidden page. I achieve this by checking the ownership in the get_template_name() method. But if I want to pass in context to the forbidden template, I also need to check ownership in the get_context_data() and make the appropriate context. This works, but it seems like way too much semi-repetitive code, and just very non-Pythonic/Djangonic. Can any suggest a nicer way to do this? It's an issue for many ClassBasedViews I created. I have both "Problem" objects and "Board" objects that I want to ensure the logged-in user == the author of the Problem or Board object. Almost seems like I could have some kind of Mixin or something. Anyway, here is an example of my approach: class ProblemStudyView(UpdateView): model = Problem fields = "__all__" def get_template_names(self): problem = self.get_object() if problem.author != self.request.user: # User should not see this entry context = {'original_author': problem.author, 'request_user': self.request.user} template_name = "board/forbidden.html" return template_name else: # This user is OK template_name = "board/study.html" return template_name def get_context_data(self, **kwargs): context … -
Django+Postgres: Table Lock "Allow only 1 http request access the rows"
I want to allow only the first server that selects the first 100 rows to modify from status_log=0 to status_log=2 on the database. And if 10 other servers get the same query wont be able to make updates. Currently I've 10 servers that pull data from a main server but its a whole mess because all of them get the same data and even if I use django: select_for_update() it's worthless. It's like all these servers get the data and don't care if the earliest got it with status = 0 the still make the update and change the status for all the servers. I want to lock the query make the update and prevent others from touching those rows ever again if the status_log != 0 This is my Query. try: logs = sms_log.objects.filter(status_log__in=[1], direction=2, server=0, retry=0)[0:100] if len(logs) != 0: for items in logs: send_sms.apply_async(args=[items.id, items.to_phone, items.body, items.account.auth_token, "4"], queue="high") except sms_log.DoesNotExist: return -
webpack and django on Heroku: bundling before collectstatic
I am building a django+react app on Heroku, using django-npm which automatically installs all modules from package.json to node-modules dir and then copies everything to staticfiles/ during python manage.py collectstatic (which is triggered by Heroku during deploy). However, for this configuration to work I need to pre-bundle my React app before deployment and put it into my static folder along with all the CSS, fonts, etc. to be picked up by collectstatic later. But I don't want to pollute my git diffs with new bundle versions. So, is there a way to make webpack create a bundle during deployment? I know there is a release command on Heroku where I can put my npm run build. But the problem is it only fires AFTER collectstatic, so my bundle will not be picked up by it. -
IndentationError: expected an indented block (Django and Python)
I'm currently working with Django on a proyect, when I'm about to import the models en the file models.py into the database this error shows up: File "/home/hansen/Escritorio/SIDECO/sideco/models.py", line 31 class Empresa(models.Model): ^ IndentationError: expected an indented block* The code is the following: from django.db import models class Sistema(models.Model): def lista_empresa(): pass def lista_desempleado(): pass def dar_de_alta_desempleado(): pass def dar_de_alta_empresa(): pass def enviar_informacion_desempleado(): pass def listado_desempleado(): pass def almacenamiento_historico(): pass class Persona(models.Model): DNI = models.CharField(max_length=10) tipo_de_trabajo = models.TextField() fecha_de_nacimiento = models.TextField() class Empleado('Persona'): empresa = models.ForeignKey('Empresa') class Desempleado('Persona'): class Empresa(models.Model): cuil = models.CharField(max_length=12) razon_social = models.TextField() rubro = models.TextField() def contratar_desempleado(): pass class OfertaLaboral(models.Model): empresa = models.ForeignKey('Empresa') tipo_de_trabajo_solicitado = models.TextField() -
VueJS props are undefined in component
I am trying to integrate VueJS with my frontend for my Django applications. I have the following Vue code in a javascript file: window.onload = function() { Vue.component('discuss-post', { props: ['post'], template: `<div class="card"> <div class="grid-x margin-x"> <div class="cell small-4"> <img class="avatar-img" :src="post.by.profile.img_url"> <p style="font-family: Abel;font-size: 24px">{{ post.by }}</p> </<div> </div> <div class="grid-x margin-x"> <div class="cell small-4"> <p style="font-family: Abel;font-size: 18px">{{ post.content }}</p> </div> </div> </div>` }) var postDiv = new Vue({ el: "#post-div" }) } And the following code in an HTML file: <div class="card-section"> {% for feed in feeds %} {% for post in feed %} <div id="post-div"> <discuss-post post="{{ post }}"></discuss-post> </div> {% endfor %} {% endfor %} </div> However, when I load my page I get these errors in my console: What in my code could be causing these errors to be raised? -
Why does opening the Chrome Console solve long wait issue?
My colleagues & I are building an Angular 4 app with a Django back-end. Periodically we have to wait a long time for a request to go out from the UI to the web-server. Yet if one opens up the Chrome Console then this seems to effect the request to immediately go out and provide the desired response. We're trying to get a handle on what's going on. Any ideas? Robert -
Django/Postgres - No function matches the given name and argument types
I'm trying to create a search system in my Django and Postgresql project but I keep running into an error when I try to make a query. Whenever I try these commands in the shell: vector = SearchVector('title','tags') query = SearchQuery('book') | SearchQuery('harry') My_Library.objects.annotate(similarity=TrigramSimilarity(vector,test),).filter(similarity__gt=0.3).order_by('-similarity') I get the error: "No function matches the given name and argument types. You might need to add explicit type casts." I've been testing other options for a while, and the only way I can successfully pass a search query without an error is by using two strings in the place of query and vector. My_Library.objects.annotate(similarity=TrigramSimilarity('title','my search query'),).filter(similarity__gt=0.3).order_by('-similarity') This will successfully pass my search with no error. Why am I getting this error, and how can I fix it? I've been basing my code off of this Full Text Search documentation -
how to save JQuery sortable() into MySQL via python?
I built an application using Python/Django/MySQL with Javascript. I am now learning jQuery and implementing it in my app. I am using the sortable() function to sort the rows on my HTML table. Now, the rows on the HMTL table is being rendered from database-> views.py -> HTML using a for loop. Let’s say I have a table with columns: first name, last name, priority. 'ORDER BY priority.’ With the help of jQuery, I am able to drag and drop the rows accordingly using the sortable(). I have added a button that should help me save the new priority of the orders according to my selection. Each person gets a unique priority number. Since most of the answers I see online are PHP/MySQL, it's hard to find answer to my question. Can someone please help me on how to save the new order into my database? What happens if the order of priority are non-consecutive numbers? How will they be save? This is the only Jquery code I have and it is sorting my rows accordingly $(document).ready(function(){ $( "#sortable" ).sortable(); $( "#sortable" ).disableSelection(); }); Thanks a lot for the help! -
How can I Customize Django Admin?
I'm a php developer, now I'm learning python and building web site with Django the biggest question for me is that i want customize the admin template at all,is there any way?,or is it right to oweride it with custom app?. What you can suggest?,please answer asap -
Python Django ValueError: source code string cannot contain null bytes
I have put down a Django project I was working on for a couple months, when I attempted to re run the server I got this error: ValueError: source code string cannot contain null bytes The Traceback is: C:\Users\Broja\Desktop\mynewenv\computersite>manage.py runserver Traceback (most recent call last): File "C:\Users\Broja\Desktop\mynewenv\computersite\manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "C:\Users\Broja\AppData\Local\Programs\Python\Python35\lib\site- packages\django\__init__.py", line 3, in <module> from django.utils.version import get_version ValueError: source code string cannot contain null bytes I am not too familiar with the Django Framework so this error confuses me, any help would go a long way. Thanks. -
django_rq jobs are not added to the queue
I am using: django-rq: 0.9.6 rq_scheduler: 0.6.1 I am fairly new to docker and django_rq. The issue that I am having is, my jobs are not executing or getting in the queue. docker-compose.yml redis: container_name: projapi-redis restart: always image: redis:latest ports: - '6379:6379' rq: container_name: projapi-rq build: . command: python manage.py rqworker default volumes: - .:/src links: - redis rqscheduler: container_name: projapi-rqscheduler build: . command: python manage.py rqscheduler volumes: - .:/src links: - redis settings.py RQ_QUEUES = { 'default': { 'URL': 'redis://redis/0', } } In the python shell, I ran :do_task.delay() and the RQ Queues' finished jobs jumps up in number by a large amount. When I run: scheduler.schedule(datetime.utcnow(), 'do_task', interval=20), I don't get any response. tasks.py from django_rq import job, get_scheduler from datetime import datetime scheduler = get_scheduler() @job def do_delay_task(): return 'do_delay_task' @job def do_task(): return 'do a task' do_delay_task.delay() scheduler.schedule(datetime.utcnow(), 'do_task', interval=2000) -
Django Admin: Dynamically remove inline fields
I'm trying to dynamically remove an inline if the user doesn't have the specified permission to edit that data. However, the inline only shows up when I'm logged in as a super user. How would I fix this? Currently I'm doing: class ClientAdmin(NestedModelAdmin): """ Admin for Clients. adp_id is only editable if the user has the permission. """ fieldsets = [ (None, {'fields': [('user', 'company', 'external_id',)]}), ] inlines = [EventInline] def get_form(self, request, obj=None, **kwargs): """ Removes the EventInline if user doesn't have the edit_event permission. """ if not request.user.has_perm('app.edit_event'): self.inlines = [] return super(ClientAdmin, self).get_form(request, obj, **kwargs) class EventInline(NestedStackedInline): model = Event fk_name = 'client' ordering = ['completion_time'] fieldsets = [ (None, {'fields': [('training', 'status', 'due_date'), ('authorized_by', 'completion_time'), 'comments']}) ] extra = 0 I want to remove the EventInline from inlines or make all the fields in the EventInline read only. Does anybody have any ideas? -
Why simple Django iterate table has memory leak
I have a simple table in Django project. If doing: for item in mytable.objects.all(): print item It has memory leak like followings: Warning: 64 bytes lost at 0x6421460, allocated by T@0 at @ 0x7f5f0327d075 my_malloc @ 0x7f5f0325ff68 my_multi_malloc @ 0x7f5f0321fe3b mysql_options4 @ 0x7f5f0321e04e set_connect_attributes @ 0x7f5f0321c1df mysql_real_connect @ 0x7f5f192f281b _mysql_ConnectionObject_Initialize @ 0x49ccdf wrap_init Warning: 160 bytes lost at 0x65bc980, allocated by T@0 at @ 0x7f5f0327d075 my_malloc @ 0x7f5f0321a95e mysql_options @ 0x7f5f0321dfa5 set_connect_attributes @ 0x7f5f0321c1df mysql_real_connect @ 0x7f5f192f281b _mysql_ConnectionObject_Initialize @ 0x49ccdf wrap_init Memory lost: 17536 bytes in 15 chunks How to avoid it? -
What are the disadvantages of using AWS ELB directly with Gunicorn (no nginx)?
Typical setups I've found on Google to run a django application on AWS all suggest a setup like ELB -> nginx -> gunicorn -> django I was wondering why the nginx part is really needed here? Isn't ELB sufficient as proxy? In our case, we are running multiple Gunicorn/django instances in individual docker containers on ECS. -
Running makemigrations when using multiple databases
I've set up my Django project to use two databases. One is read-only and other is the "default" django database for the rest of the project. Here are the settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sipf', 'USER': 'myusername', 'PASSWORD': 'secret', 'HOST': '127.0.0.1', 'PORT': '5432', } , 'my_read_only_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_read_only_db', 'USER': 'myusername', 'PASSWORD': 'mypassword', 'HOST': 'remote.host.edu', } } Here is router.py for the read-only DB: class MyReadOnlyDBRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'my_read_only_db': return 'my_read_only_db' return None and for the default DB: class PrimaryRouter(object): def db_for_read(self, model, **hints): return 'default' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): db_list = 'default' if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): return True And finally the routing in settings: DATABASE_ROUTERS = ['my_read_only_db.router.MyReadOnlyDBRouter', 'common.router.PrimaryRouter'] I understand that when running migrate one needs to specify which database to run against like so: $ ./manage.py migrate --database=default However, before even getting that far one needs to run makemigrations. Here, it is clearly attempting to create tables in the read-only database and I'm getting: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to …