Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
count views for anonymous users in django
I am creating a blog just for practice and i recently added the views counter function the problem is when an anonymous user open the post django raise an error because in the post_detail view i request the username this is the view: def post_detail(request, post_id): post = Post.objects.get(id=post_id) if UserSeenPosts.objects.filter(post=post, user=request.user).exists(): print "all ready" else: post.views += 1 post.save() UserSeenPosts.objects.create(user=request.user, post=post) return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)}) the UserSeenPosts model: class UserSeenPosts(models.Model): user = models.ForeignKey(User, related_name='seen_posts') post = models.ForeignKey(Post) -
unable to install mysqlclient on mac
Hi guys i'm attempting to install mysqlclient using the command: pip install mysqlclient but i get the following error: Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found I uninstalled python3 using brew uninstall --force python3 and downloaded the binary from pythons website but to no avail. I also attempted to download mysql connector from oracle website and again to no avail. I have tried upgrading pip again still doesnt work. PS mysql is running in a docker container and i'm running django on my local machine. Any suggestions on why i'm getting an error attempting to install mysqlclient -
Django-admin inline default value
admin.py class CaseNoteInline(admin.TabularInline): model = CaseNote extra = 1 max_num = 5 i have a some column in CaseNote which is "User" and i want to set default value for that. -
Caching a frequently used queryset in django
I have a model which is being used a lot in my app (and the data in it almost never changes, unless a dev wants to change something). I'd like to cache this queryset to see what difference it will make for the speed of my views, but can't really get my head around it. I'm using redis and i set the cache like this: m = MyModel.objects.all() cache.set('m', m, timeout=None) And then I get it like this: c = cache.get('m') for x in range(1,200): o = c.get(pk=x) ... which of course leads to 200 DB queries. How can I store everything in the cache so that every lookup I do gets the data from the cache? Should I set each individual entry in the cache such as cache.set(primary_key, object)? Or should I convert it to a dictionary or something? -
How to create models in django with interrelationship between tables?
Most of the examples i googled were related to blogpost and i couldnt figure out how i could use django model/views(ORM) for practicing custom application. I have three tables:- user,license and common. Here is the use case i thought of mysql> describe user; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | userid | int(11) | NO | PRI | NULL | | | email | varchar(55) | NO | UNI | NULL | | | fname | varchar(22) | NO | | NULL | | | lname | varchar(22) | NO | | NULL | | +--------+-------------+------+-----+---------+-------+ mysql> describe license; +-----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+---------+-------+ | licenseid | int(11) | NO | PRI | NULL | | | category | varchar(11) | NO | UNI | NULL | | +-----------+-------------+------+-----+---------+-------+ mysql> describe common; +-----------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+---------+------+-----+---------+-------+ | licenseId | int(11) | NO | | NULL | | | userId | int(11) | NO | | NULL | | The common table will store the userid and licenseid which will be … -
CSRF verification failed. Request aborted. Django 1.9
i'm just starting to implement post request on my project but i have trouble with the csrf token. Even if it seem i used it correctly (I use render, have cookie enable, {% csrf_token %} is in the html code and i have the middleware in django settings) view.py : form = mouvementForm(request.POST or None) if form.is_valid(): pont = form.cleaned_data['pont'] dateheure = form.cleaned_data['dateheure'] poid = form.cleaned_data['poid'] dsd = form.cleaned_data['dsd'] typepesee = form.cleaned_data['typepesee'] #Connection to 'erp-site' DB return render(request, 'mouvementCreation.html', locals()) template : <form name="Form1" method="post" action="" enctype="text/plain" id="Form1"> {% csrf_token %} <input type="text" id="Editbox9" style="position:absolute;left:87px;top:46px;width:86px;height:16px;line-height:16px;z-index:173;" name="pont" value="" spellcheck="false"> <input type="text" id="Editbox34" style="position:absolute;left:87px;top:80px;width:86px;height:16px;line-height:16px;z-index:174;" name="dateheure" value="" spellcheck="false"> <input type="text" id="Editbox35" style="position:absolute;left:87px;top:114px;width:87px;height:16px;line-height:16px;z-index:175;" name="poid" value="" spellcheck="false"> <input type="text" id="Editbox36" style="position:absolute;left:88px;top:153px;width:84px;height:16px;line-height:16px;z-index:176;" name="dsd" value="" spellcheck="false"> <input type="text" id="Editbox37" style="position:absolute;left:87px;top:187px;width:86px;height:16px;line-height:16px;z-index:177;" name="typepesee" value="" spellcheck="false"> <input type="submit" id="Button14" name="submit" value="Submit" style="position:absolute;left:361px;top:65px;width:96px;height:25px;z-index:178;"> </form> Middleware settings : MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] i have searched on multiple post and tried alot of fix but so far nothing worked and i'm still getting "Reason given for failure: CSRF token missing or incorrect." -
Django retrieve saved image as base64 string
I am trying to upload image to file system using python django as base64 string and retrieve the same as base64 string. in my model.py: Class Test(object): mission = models.TextField(blank=True) image = models.ImageField(upload_to='documents/images/',blank=True) account = models.OneToOneField(Account, related_name='account') def __str__(self): return '{}:{}'.format(self.mission, self.image) in my view.py def add_image(request, account): req = get_request_json(request) data = Test.objects.add_image(account, req) in my manager.py Class TestManager(models.Manager): def add_image(self, account, input): acc = self.get(account=account) format, imgstr = input_data.get('image').split(';base64,') ext = format.split('/')[-1] img = ContentFile(imgstr, name='temp.' + ext) acc.save() return acc; def get_doctor_profile(self, account): try: profile = self.get(account=account) except self.model.DoesNotExist: profile = [] except (MultipleObjectsReturned, ValueError, Exception) as e: profile = [] raise IndivoException(e) else: pass finally: return profile The path where the image is saved is added in the database but while returning the response I get the following error after saving and while using get TypeError: <ImageFieldFile: documents/images/temp_fRRD2oc.jpeg> is not JSON serializable. I think the error is in my models.py def __str__(self): but I am not aware of how to fix this. I need to return the saved image file as base64 string in the response. Can anyone point me in the right direction on how to fix this. -
Wagtail admin icons disappear when running collectstatic and putting everything on S3
I've been working locally and on my server and everything looks good. Then I configure django-storages to store static files and media on my S3 bucket. Everything works except for the icons/glyphicons on the admin interface. Instead of the nice pretty graphic icons, I see letters. For example once you log in, you have the search bar on the left side. Normally you would see a looking glass in the search box. I lost the looking glass and now I just see a lowercase f. My question is this. What do I search for to start debugging this? What wagtail file is collectstatic not collecting? Steps to Reproduce Set up a wagtail site Set up a bucket on s3 Install django-storages Configure django-storages to use your bucket ./manage.py collectstatic Technical details Python version: 3.5.2 Django version: 1.11.5 Wagtail version: 1.12.2 Browser version: firefox, chromium, chrome -
Input from is only 1 in html
Input from is only 1 in html.Im making Login form in index.html like <form class="my-form" action="{% url 'accounts:regist_save' %}" method="POST"> <div class="form-group"> <label for="id_username">Username</label> {{ form.username }} {{ form.username.errors }} </div> <div class="form-group"> <label for="id_email">Email</label> {{ form.email }} {{ form.email.errors }} </div> <div class="form-group"> <label class="control-label" for="id_password1">Password</label> {{ form.password1 }} {{ form.password1.errors }} </div> <div class="form-group"> <label class ="control-label" for="id_password2">Password(Conformation)</label> {{ form.password2 }} {{ form.password2.errors }} <p class="help-block">{{ form.password2.help_text }}</p> </div> <div class="form-group"> <div> <input type="submit" class="btn btn-default" value="SEND"> </div> </div> {% csrf_token %} </form> in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' in urls.py like urlpatterns = [ url(r'^login/$', login,{'template_name': 'index.html'},name='login'), ] Only Username field is shown in browser, but others are not there.By using Google validation,only Username field has input tag, but others do not have.Why does it happen?How should i fix this? -
Django: how to use a template tag as an arguments for another template tag
I need to use a template tag inside another tag that is a custom tag and it gives me this error: Could not parse the remainder: '{{message.tags}}' from '{{message.tags}}' How can I fix this? TIA for any help! html: <div class="bootstrap-iso"> {% if messages %} <div class="messages "> {% for message in messages %} <div {% if message.tags %} class="alert {{ message.tags }} alert-dismissible" role="alert" {% endif %}> <strong> {% get_message_print_tag {{message.tags}} %}: </strong> {{ message }} <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> </div> {% endfor %} </div> {% endif %} </div> -
Unknown code being added to HTML template when running local server
I was building a profile picture feature, it was working fine so I left it for a while, probably a week. I came back to it and ran the local server, but when I do there's a few lines that appear in the console. But do not exist on the source file. Source file: <script type='text/javascript'> Dropzone.options.myDropzone = { autoProcessQueue : false, paramName: 'uploaded_image', dictDefaultMessage: "Drag and drop files or click here to upload picture", init: function() { var submitButton = document.querySelector("#submitBtn") myDropzone = this; submitButton.addEventListener("click", function() { myDropzone.processQueue(); }); // Automatically overwrites file so the user can only upload one this.on("addedfile", function() { document.getElementById('submitBtn').style.visibility = "visible"; }); this.on('addedfile', function(){ if (this.files[1]!=null){ this.removeFile(this.files[0]); } }); } }; </script> <!-- Modal --> <div id="picModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close"></span> <form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="my-dropzone">{% csrf_token %} <!-- submit button stays hidden by default, until user selects a picture --> <button id='submitBtn' type='submit' class='pic-submit-button' style='visibility: hidden;'> Submit </button> <input id='submit-all' type='file' name='uploaded_image'/> {{form}} </form> </div> </div> Now the code I'm seeing when I run the server is only a few lines, and it's in the HTML that creates the modal: <!-- Modal --> <div … -
saving html content as json in django db
I'm using DJango to save some html designs in my db. For example here 'Body' has some html content: When I serialize the content into json, it seems like the html tags get eliminated: from django.core import serializers def list_templates(request): # retrieve all the templates from the DB all_templates = Template.objects.all() return HttpResponse(serializers.serialize('json', all_templates)) Here is what I see: Any recommendations on best practices for saving html codes and their serialization? -
Filtering on the basis of tags in Django Rest Framework
I have an array of tags as a model field, I want to filter out based on those array elements. here is the model in which tag field is an array type I guess. class Mineral(models.Model): name=models.CharField(max_length=500) tags=TaggableManager() def __unicode__(self): return self.name Now in my view, I want to filter out based on this tag field I can do that using Django way like this class MineralList(APIView): queryset = Mineral.objects.all() serializer_class = MineralSerializer permission_classes = [AllowAny] def get(self, request, format=None): mineral = Mineral.objects.all() tags = request.query_params.get('tags', None) name= request.query_params.get('name',None) if tags is not None: tags = tags.split(',') mineral = mineral.filter(tags__name__in=tags).distinct() if name: mineral = mineral.filter(name=name) serializer = MineralSerializer(mineral, many=True) return Response(serializer.data) How can I do that in REST way using filter backends and Filter class -
Default value for a field, based on another field's value
How can I define the default for a Django model field, to be based on the value of another field on the same instance? I want to define a code for the model based on the created timestamp: from django.db import models class LoremIpsum(models.Model): code = models.CharField( max_length=100, default=( lambda x: "LOREM-{0.created:%Y%m%d-%H%M%S}".format(x)), ) created = models.DateTimeField( auto_now_add=True, ) That doesn't work because the function defined for default receives no argument. How can I define a default for the code field such that it is derived from that instance's created field value? -
Django custom template tag throwing an error
I am trying to use a custom template tag and it gives me this error when I am trying to get a rendered page: Invalid block tag on line 29: 'get_message_print_tag', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I am trying to get a simple title for my flash messages based on {{message.tags}} and make it bold in my template. Where am I making a mistake? apptags.py: from django import template register = template.Library() def get_message_print_tag(value): '''return a string for a message tag depending on the message tag that can be displayed bold on the flash message''' if 'danger' in value.lower(): return 'ERROR' elif 'success' in value.lower(): return 'SUCCESS' else: return 'NOTE' html: {% load apptags %} <div class="bootstrap-iso"> {% if messages %} <div class="messages "> {% for message in messages %} <div {% if message.tags %} class="alert {{ message.tags }} alert-dismissible" role="alert" {% endif %}> {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Error: {% endif %} <strong> {% get_message_print_tag {{message.tags}} %} </strong> {{ message }} <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> </div> {% endfor %} </div> {% endif %} </div> -
Store numpy array in session (Alternatives)
I have a class in a view that does some calculations. The instance of this class is passed to a Django template context and the results are displayed in the html. On the other hand, I need to store these results somewhere for later use in another view, where a pdf document is generated using these results. The results are large lists of data. For example: def view_one(request): # some code class_instance = SomeClass(form.cleaned_data) html = render_to_string('results.html', {'instance': class_instance}) return JsonResponse({"result": html}) def view_two(request): # some code class_pdf = GeneratePdf(class_instance) # How can I pass the class_instance data? # some code The results are large lists of data. Should I use Django request session to store the data? Can I use Celery? There is another alternative? -
apache does not pass request to Django (404 not found)
I have a custom 404 page setup for the site, which works fine, like this: when I hit mysite.com/fdsafsadfdsa which doesn't exist, the custom 404 page shows up. However if I add a urlencoded '/' which is '%2f' at the end of url, mysite.com/fdsafsadfdsa%2f, and this gives me the apache 404 not found. it looks like apache decided to handle this 404 itself instead of passing down to Django Anybody has idea why this is happening? -
How to force 'django.contrib.sites' to be migrated first?
When using python manage.py makemigrations on a project that uses functions from the django.contrib.sites, I always received the error: django.db.utils.OperationalError: no such table: django_site. If I comment out the parts of my code that use app, and run makemigrations it works, and then I can uncomment. This (bad) approach works, but I would like to make it work correctly. I already put this app in the top of settings.INSTALLED_APPS, but it does not solve it. -
Adding charaters to a string in specified places - Django
I have a simple python action that I want to take. I have a string. something like 2364968438. I want to take that string that I have and add a - between specific places in the string to make it look like a phone number. something like this 236-496-8438 within my django/python project. I know i am going to have to splice the string into parts but I am having trouble with it. Does it matter if it is a string or integer? -
django-mama-cas and django-cas-ng: NotImplementedError
I'm developing a SSO project with django-mama-cas and django-cas-ng. I've followed the installation requirements for each package, and followed this article: https://medium.com/@adiletmaratov/central-authentication-service-cas-implementation-using-django-microservices-70c4c50d5b6f. I'm getting the following error: NotImplementedError: mama_cas.services.backends.SettingsBackend.service_allowed() not implemented Any ideas of what is the cause? -
Django / duplicate key value violates unique constraint
I try to extend django auth user model with OneToOneField but couldn't solve this problem. duplicate key value violates unique constraint "users_profile_user_id_key" DETAIL: Key (user_id)=(67) already exists. I look through this issue , some people say the db out of sync. views.py def create_profile(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = UserProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): registration = user_form.save() profile = profile_form.save(commit=False) profile.user = registration profile.save() return redirect('index') else: user_form = UserRegistrationForm() profile_form = UserProfileForm() return render(request, 'registration/registration.html', {'user_form': user_form, 'profile_form': profile_form}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_image = models.ImageField(upload_to="blog/assets", default="blog/assets/people-photo.jpg", null=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class UserRegistrationForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password') widgets = { 'password': forms.PasswordInput(), } class UserProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('user_image', 'birth_date',) -
User.py Exception Type: TypeError Exception Value: 'Manager' object is not iterable
Hello I have a little problem in Django, I created a database and now I want to print the queries of this, so I have in my user.py file the following code def user(request): user_list = User.objects user_dict = {'user_data': user_list} return render(request,'AppTwo/User.html',context=user_dict) here i get the following error: User.py Exception Type: TypeError Exception Value: 'Manager' object is not iterable. To fix this, I need to change the code to this: def user(request): user_list = User.objects.order_by('first_name') user_dict = {'user_data': user_list} return render(request,'AppTwo/User.html',context=user_dict) but I can not understand why the simple adding of order_by('first_name'), casts the object to a list? Why do I need this? I have trouble to understand, maybe somebody could help me and explain to me what is happening here. Thank you very much in advance -
Python starting two instances of webview when using multithreading with django
import os from threading import Thread import webview def start_backend(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_great_app.settings") from django.core.management import call_command from django.core.wsgi import get_wsgi_application application = get_wsgi_application() call_command('runserver', '127.0.0.1:8080') def start_frontend(): webview.create_window("web app", "http://127.0.0.1:8080/") if __name__ == "__main__": backend_thread = Thread(target = start_backend) backend_thread.start() start_frontend() In this simple examble the webview is started twice, e.g. there are two windows starting after the django server starts. Though I only want one. Does someone know whats incorrect in this code? Tested on Ubuntu and python3.6. -
How do you change the size of permissions boxes in Django Admin section of Authentication and Authorization?
As we know Django has an in-built Admin. I am using it but I cannot seem to get access to its code (perhaps I'm being an idiot, likely,- new to django and inherited an existing project). Crucially, since we are porting a legacy database to this new one there are permissions etc that are assigned to users and groups. As show in the picture below the display boxes for the permissions is too small preventing the administrator from being able to adequately assess the permissions options. How do I change this? -
How can i implement real time notifications in django?
I have read many blogs regarding this but could not understand. Can someone help me in this like what are the different ways of doing it and how to implements this.