Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a Bootstrap theme with Django
I have an Admin theme from Themeforest and I wanted to create it's backend with Python using the Django framework. However when I copy the theme files into the template folder the CSS does not load. The structure is this: Mysite/myapp/templates/myapp/...here is where the index.html is and a folder for CSS, JS and Images. The href in the html is Anyone knows how to load the css, JS and images so that it doesn't give me plain text when I start the server -
Difference between first() and filter() in django models
I have InstituteDetailsModel which have just one entry in it. I have another table StudentDetails which is using InstituteDetailsModel as FK in one of its column like below: institute = models.ForeignKey('institute.InstituteDetailsModel', to_field="sys_id", on_delete = models.PROTECT, null=False, blank=True) Now when storing student details I tried to get the only entry from Institute table using below two methods. Second method threw error Select a valid choice. That choice is not one of the available choices. while first one worked fine. I wanted to know what is the difference between InstituteDetailsModel.objects.filter(sys_id=1) & InstituteDetailsModel.objects.first() And why one of them worked and another didn't worked. -
Django multiple tests + migrations
I am really puzzled by this: I use Django 1.11.2. I have a couple of tests inside the same test class. They (and the actual code) rely on data, that I inject using migrations. In particular, I create some security groups. Migrations work perfectly when run by ./manage.py migrate. They also seem to work just fine for the first test in the class. However, when setUp is run for the second test, it complains that the group doesn't exist. This is my setup function from a test class: class MyDjangoTest(TestCase): def setUp(self): # Every test needs access to the request factory. self.client = Client() self.password = 'top_secret' group: Group = Group.objects.get_by_natural_key("SomeGroup") self.user1: User = User.objects.create_user( username='john', email='john@…', password=self.password) self.user1.groups.add(group) self.user2: User = User.objects.create_user( username='jane', email='jane@…', password=self.password) self.user2.groups.add(group) -
django login_required decorator, always redirect to login page, even after logging in
code in views.py def custom_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('main') else: return redirect('login') else: user = AuthenticationForm() return render(request, 'index.html', {'form': user}) @login_required def main(request): return render(request, 'main.html') urls.py urlpatters =[url(r'^$', views.custom_login, name='login'), url(r'^main', views.main, name='main')] in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',] MIDDLEWARE = [ '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',] LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'main' If I don't put login_required decorator on main, I am able to redirect to main. but if I use login_required decorator, I am getting redirected back to login page after login with URL http://localhost:9000/sample_app/?next=/sample_app/main I am using python3 with django -
How does Django know which model manager to use?
So I am interested in using the example code below in a Django project, but am puzzled when trying to understand how I would call one model manager explicitly. class AuthorManager(models.Manager): def get_queryset(self): return super(AuthorManager, self).get_queryset().filter(role='A') class EditorManager(models.Manager): def get_queryset(self): return super(EditorManager, self).get_queryset().filter(role='E') class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor')))) people = models.Manager() authors = AuthorManager() editors = EditorManager() I know the view calls the models and the models calls the model manager, but its kind of confusing to me. Can I specify which view calls which manager or does the model take care of that implicitly through some other way? -
How to create groups for only one connection
The scenario is I have a view which takes a pk, and I want to create individual groups for each pk value, and only one person can connect to the group. I've read the documentation, But It's not very clear for a begginner and lacks some additional informations. def panel(request,pk): #some code that is going to call the group whenever I need info = { "state": 'touched' } Group('panel-%s ' % pk).send({ 'text': json.dumps(info) }) #end return render(request, "index.html") Looks like It's all okay, But how do I write my cosumers in cosumers.py to connect and desconnect to the group. def ws_connect(message): message.reply_channel.send({"accept": True}) Group('panel-%s' % pk).add(message.reply_channel) def ws_disconnect(message): Group('panel-%s' % pk).discard(message.reply_channel) -
Django ORM object
I used Django ORM. And when I type from app.models import Weather Weather.objects.all() It printed: DEBUG 2017-06-11 09:43:44,051 utils 12912 384 (0.083) SELECT `weather`.`id`, `weather`.`time`, `weather`.`tpr`, `weather`.`wet`, `weather`.`uv` FROM `weather` LIMIT 21; args=() And when I type print(Weather.objects.all()) It printed: [<Weather: Weather object>, <Weather: Weather object>, <Weather: Weather object>, <Weather: Weather object>, <Weather: Weather object>, <Weather: Weather object>, <Weather: Weather object>, <Weather: Weather object>, <Weather: Weather obj] And then I added def unicode(self) in the Weather class here is the following code: class Weather(models.Model): tpr = models.CharField(max_length=5) wet = models.CharField(max_length=5) ur = models.CharField(max_length=5) li = models.CharField(max_length=5) observe_time = models.DateTimeField(blank=True, null=True) def __unicode__(self): return self.tpr def __unicode__(self): return self.wet def __unicode__(self): return self.uv def __unicode__(self): return self.li But the result wasn't change. How can I do next? -
Can't add data to Sqlite using Django
I have a table called Movies in Sqlite it consists of movieid, title, genres, overview, poster, cast, trailer and FinalRate . I have another table called ratings that gives the rating of every movie from different users.I want to make a Top Rated movies which should take the ratings and sort it from higher rate to lower rate but the rating we have are not the final rate thats why i made a new raw called FinalRate which takes the rate of the same movie from different user and calculate its average to give us the final rate i done a function which take the rate from every movie and calculate its average but i can't put it in the sqlite database and this error pops up saying ModuleNotFoundError: No module named '' enter image description here -
AWS S3 upload boto status
I am using Flask and Boto with AWS S3 to upload files. I would like to know the progress so I can show it to the user. I am boto.s3client and s3.put_object(Body=body, Bucket= BUCKET_NAME, Key=key, ContentType='image/png') For example. How can I know the progress of uploading? -
Django REST API - How to stay "logged in" on refresh?
I am using DJANGO Rest API and an AngularJS client and I cannot figure out how to remain logged in when I refresh the page! (Django does this when they render html on their back-end stuff)... I have authtoken and my default auth classes are: 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' I have ng-Cookies in AngularJS and I've tried a few things I've read online about keeping headers and such but nothing has seemed to work. :( Ideas? -
Django SQL injection and XSS when do they take place
Hi!! The only form of sécurity I used in django so far is {% csrf_token %} for forms.py and in the settings.py I use 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] if you know of any cases where django can't be secured anymore please share it I heard that you just need to be carefull doing certain things when programming. XSS It is also important to be particularly careful when using is_safe with custom template tags, the safe template tag, mark_safe, and when autoescape is turned off. csrf Be very careful with marking views with the csrf_exempt decorator unless it is absolutely necessary. sql injection you should always be careful to properly escape any parameters that the user can control. In addition, you should exercise caution when using extra() and RawSQL. sorry for asking this but I don't really know what they mean by be carefull need some examples any exemple to when something bad happens while using django? those were my question? Thanks!! -
Django SlugField are displayed partially
I'm stuck from a couple hours and I can't solve this problem. The following code works well, but Url is only partially displayed when redirecting. For example, When Slugfiled is blah-1, url is Displayed as /blah/(without -1). Model: class Post(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(unique=True, allow_unicode=True) image = models.ImageField(null=True, blank=True, width_field = "width_field", height_field = "height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) hit_count = models.IntegerField(default=0) class Meta: ordering = ['-timestamp'] def __unicode__(self): return self.title @property def is_past_due(self): from datetime import date if date.today() == self.timestamp.date(): return True return False def get_unique_slug(self): slug = slugify(self.title, allow_unicode=True) unique_slug = slug counter = 1 while Post.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) View: def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "succes.") #This redirecting is the problem return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } return render(request, "blog/post_form.html", context) url: urlpatterns = [ url(r'^$', views.post_list, name="list"), url(r'^create/$', views.post_create), url(r'^(?P<slug>[\w-]+)/$', views.post_detail, name='detail'), url(r'^(?P<slug>[\w-]+)/edit/$', views.post_update, name='update'), url(r'^(?P<slug>[\w-]+)/delete/$', views.post_delete), How can I solve this problem? -
orm query in django
Hi im new using django and i dont know how make a good query . this is my model: class Product(models.Model): client = models.ForeignKey('Client') subcategory = models.ForeignKey('SubCategory') product = models.CharField(max_length=30) description = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.product and when i type Product.object.all() just i receive as output de field product and i need as output product,description,client. something like the output from mysql select * from Products -
Generic Django view - how to change field's visibility
I have a view derived from CreateView. I'd like the field B appear only and if a file in file A has been uploaded. I would use javascript in a template (to toggle the B's visibility based upon the state of A) - if it weren't for generic view. I'd be grateful if you suggested me something as I've got stuck. The flow I am aiming at: 1. the form is loaded, there is no B field or it is hidden 2. user provides inputs for x, y, z (required) and optionally for A. 3. if input has been provided for A, B is displayed. the present code is sth like that: class CreateItem(forms.CreateView): class Meta: model = Item fields = [x, y, z, A, B] Django 1.10, python 3.5 -
How to filter foriegnkey objects by current user in django admin page
This is the class CategoryAdmin: class CategoryAdmin(admin.ModelAdmin): list_display = ['name','desc','text'] fieldsets = [(None, {'fields': ['name', 'desc', 'text']}),] def save_model(self, request, obj, form, change): if not obj.id: obj.user = request.user obj.save() def get_queryset(self, request): qs = super(CategoryAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) Model class Product: class Product(models.Model): user = models.ForeignKey("auth.User", db_index=True) name = models.CharField(max_length=64) text = models.CharField(max_length=512) pub_dt = models.DateTimeField('date published', help_text="Please use the following format: <em>YYYY-MM-DD</em>.") cate = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) Model class Category: class Category(models.Model): user = models.ForeignKey("auth.User", db_index=True) name = models.CharField(max_length=64) desc = models.CharField(max_length=128) text = models.CharField(max_length=512) def __str__(self): return self.name When I add a Product and cate field is a dropdown list. How can I filter the dropdown list of the category by current user. -
Google SDK gcloud crashed (UnicodeDecodeError): 'utf8' codec can't decode byte 0xf8 in position 29: invalid start byte
When trying to run gcloud app deploy, I'm getting the error: gcloud crashed (UnicodeDecodeError): 'utf8' codec can't decode byte 0xf8 in position 29: invalid start byte I have no clue whats happening with it. Works fine in my local server. The full error is: Updating service [default]...DEBUG: Converted YAML to JSON: "{ "handlers": [ { "securityLevel": "SECURE_OPTIONAL", "staticFiles": { "path": "static/static_files/\\1", "uploadPathRegex": "static/static_files/.*" }, "urlRegex": "/static/(.*)" }, { "script": { "scriptPath": "Bctpython.wsgi.application" }, "securityLevel": "SECURE_OPTIONAL", "urlRegex": "/.*" } ], "libraries": [ { "name": "MySQLdb", "version": "1.2.5" } ], "runtime": "python27", "threadsafe": true }" Updating service [default]...failed. DEBUG: 'utf8' codec can't decode byte 0xf8 in position 29: invalid start byte Traceback (most recent call last): File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 798, in Execute resources = args.calliope_command.Run(cli=self, args=args) File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line 871, in Run resources = command_instance.Run(args) File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\surface\app\deploy.py", line 61, in Run args, runtime_builder_strategy=runtime_builder_strategy) File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 425, in RunDeploy all_services, app.gcrDomain) File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 254, in Deploy endpoints_info) File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\appengine_api_client.py", line 132, in DeployService service_config, manifest, version_id, image, endpoints_info) File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\appengine_api_client.py", line 541, in _CreateVersionResource json_version_resource) File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\..\lib\third_party\apitools\base\py\encoding.py", line 135, in PyValueToMessage return JsonToMessage(message_type, json.dumps(value)) File "C:\Users\Kcan2\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython\lib\json\__init__.py", line 243, in dumps return _default_encoder.encode(obj) … -
Django - Custom permissions to Class based views
First of all sorry for my bad English! Well i start using class based views, and i'm having a problem to add custom permissions to access to the view. Lets suppose I just want to allow access to the users that have activated in their usersprofile the self_store option. When i use function views is very easy i put this in the beginning of the view and works fine if not request.user.is_authenticated(): return redirect('auth_login') if not request.user.userprofile.self_store: return do_something_here Well like i said is very easy to use and do different things for different options activated or not in my userprofile But i cant find the way to do this in class based views, if i want to allow access to the users that have activated the self_store option in the usersprofile how can i do for example in this updateview i can use logginrequired mixxin perfect but i want to check like i said custom users properties that i use in the userprofile. class ClientUpdateView(UpdateView): model = Client template_name = "clients/update.html" pk_url_kwarg = 'client_id' fields = [ 'first_name', 'last_name', 'email', 'phone', 'phone_2', 'address', ] Thanks very much!!! -
How to have all django allauth forms and dialogs to show in a popup
So right now I'm implementing django-allauth on my website by extending my base.html and having the templates show on allauths different URLs like (mydomain/accounts/login/) and so on. I'm looking for a method to have all of allauths dialogues and forms to show in a modal popup instead, my initial thought was to use ajax calls and I was wondering if there is some easy way to integrate with allauths views that I missed in their docs or some other methods or ideas for doing that? Anything that could put me on the right path would be nice really, thanks. -
Django m2m_changed pk_set is empty
Django version 1.10.7, I have a problem where sometimes my receiving m2m_changed signal on a ManyToMany field has pk_set empty. The model m2m part (note it's a self reference): class Profile(TimeStampedModel): following = models.ManyToManyField( "self", verbose_name=_("Following"), related_name="followers" ) Signal beginning part with logger: @receiver(m2m_changed, sender=Profile.following.through) def profile_following_change(sender, instance, action, pk_set, **kwargs): logger.debug("profile_following_change - sender %s, instance %s, action %s, pk_set %s, kwargs: %s", sender, instance, action, pk_set, kwargs) Below an example log line with pk_set containing the added primary key: DEBUG:socialhome:profile_following_change - sender <class 'socialhome.users.models.Profile_following'>, instance Profile A (profile_a@a.domain.tld), action post_add, pk_set {2}, kwargs: { 'signal': <django.db.models.signals.ModelSignal object at 0x7fa73e033908>, 'model': <class 'socialhome.users.models.Profile'>, 'using': 'default', 'reverse': False } And an example with an empty pk_set. DEBUG:socialhome:profile_following_change - sender <class 'socialhome.users.models.Profile_following'>, instance Profile B (profile_b@b.domain.tld), action post_add, pk_set set(), kwargs: { 'model': <class 'socialhome.users.models.Profile'>, 'reverse': False, 'using': 'default', 'signal': <django.db.models.signals.ModelSignal object at 0x7f001c173908> } The two saves are both from the same code, using the following line. Note this code runs in an RQ background process, should that matter: profile.following.add(user.profile) Why is the pk_set sometimes empty, any ideas? Note that both Profile objects also exist before the RQ job is processed (event is triggered by doing a "follow" in the UI). … -
django template blocks for messaging app
Im trying to change the template of my inbox app. Currently i have it looking like this. this is the code that comes as default with django-postman: {% extends "postman/base_folder.html" %} {% load i18n %} {% block pm_folder_title %}{% trans "Received Messages" %}{% endblock %} {% block pm_undelete_button %}{% endblock %} {% block pm_recipient_header %}{% endblock %} {% block pm_date %}{% trans "Received" %}{% endblock %} {% block pm_recipient_cell %}{% endblock %} however im trying to implement this code: {% block content %} <h1>{% trans "Inbox" %}</h1> <div class="container"> <div class="row"> <div class="col-sm-3 col-md-2"> <div class="btn-group"> <div class="pull-right"> </div> </div> </div> </div> {{ pm_folder_title }} <hr /> <div class="row"> <div class="col-sm-3 col-md-2"> <a href="{% url 'postman:write' %}" class="btn btn-warning btn-sm btn-block" role="button">COMPOSE</a> <hr /> <ul class="nav nav-pills nav-stacked"> <li class="active"><a href="{% url 'postman:inbox' %}"> Inbox </a> </li> <li><a href="{% url 'postman:sent' %}">Sent Mail</a></li> <li><a href="{% url 'postman:trash' %}">Trash</a></li> </ul> </div> <div class="col-sm-9 col-md-10"> <div class="tab-content"> {% block pm_folder_title %}{% trans "Received Messages" %}{%endblock %} {% block pm_undelete_button %}{% endblock %} {% block pm_recipient_header %}{% endblock %} {% block pm_date %}{% trans "Received" %}{% endblock %} {% block pm_recipient_cell %}{% endblock %} </div> </div> </div> </div> {% endblock %} As you … -
Retroactively set new ManyToManyField default values to existing model
I have a Django model (called BiomSearchJob) which is currently live and I want to add a new many-to-many relation to make the system more customizable for the user. Previously, users can submit a job without specifying a set of TaxonomyLevelChoices but to add more features to the system, users should now be able to select their own taxonomy levels. Here's the model: class TaxonomyLevelChoice(models.Model): taxon_level = models.CharField( verbose_name="Taxonomy Chart Level", max_length=60) taxon_level_proper_name = models.CharField(max_length=60) def __unicode__(self): return self.taxon_level_proper_name class BiomSearchJob(models.Model): ... # The new many-to-many relation taxonomy_levels = models.ManyToManyField( 'TaxonomyLevelChoice', blank=False, max_length=3, default=["phylum", "class", "genus"]) name = models.CharField( null=False, blank=False, max_length=100, default="Unnamed Job", validators=[alphanumeric_spaces]) ... Currently, all existing BiomSearchJobs implicitly have the three taxonomy levels listed in the default= term (which are not user-selectable) and hence are all the same in the database. After running migrate, I find that the previous jobs don't immediately have the three taxonomy level relations, they only return an empty set upon calling job.taxonomy_levels.all() (if job were an instance of BiomSearchJob). Is there a way to retroactively add this relationship without manually going through everything? Ideally, by just running migrate I would like the existing BiomSearchJobs to have phylum, class, and genus listed in … -
My form does not select image file
So far everything works well But the only problem i am facing is uploading imagefile..Image field does not import selected images .Please help and thanks here is my model.py of my profile form class UserProfile(models.Model): user = models.OneToOneField(User,unique=True,on_delete=models.CASCADE) bio = models.TextField(max_length=500,null=True,blank=True) picture = models.ImageField(upload_to="profile_image",null=True) company = models.CharField(max_length=500,null=True) def __str__(self): return self.user.username # Sending a new signal when ever a user is created to create a new profile @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) And here is my view.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST,instance=request.user.userprofile) if profile_form.is_valid(): profile_form.save() messages.success(request,'Your Profile has been Updated') return redirect('success:profile_account') else: messages.error(request,'fill out the fields correctly') else: profile_form = ProfileForm(instance=request.user.userprofile) return render(request,"success/user_account/edit_profile.html", {'profile_form':profile_form}) Here is the form.py class ProfileForm(forms.ModelForm): class Meta: model= UserProfile exclude=['user',] fields =['bio','picture','company'] And here is the hmtl file to render my updates <h4>{{ user.get_username }}</h4> <h4> {{ user.get_full_name}}</h4> <h4> {{ user.first_name}}</h4> <h4> {{ user.email}}</h4> <h4> {{ user.bio}}</h4> <h4> {{ user.userprofile.company }}</h4>SS <h4>{{user.userprofile.bio}}</h4> {% if user.userprofile.picture %} <image src="{{user.userprofile.picture.url}}" width="40" height="40"> {% else %} <p> Chose a profile</p> {% endif %} </image> <a href="{% url 'success:Profile_update' %} ">Update</a> </li> And here is my Edit.html file {% csrf_token %} {{ profile_form.as_p }} Save changes -
django-select2 not working properly for a form in formset
I am using ModelSelect2MultipleWidget provided by django-select2 for rendering a ModelChoiceMultiple field.I have used the widget at 2 places : in a single form and in a form which is used in creating formset. The single form part widget works completely fine and as desired. But in case of formset form, it doesn't render as expected and also the queryset doesn't load which is explained by the images below : -
Iframe is not working then pointing Heroku URL
I have a Python Django app running on https://dj-node-project.herokuapp.com/catalog/, when I put this into an iframe, I'm seeing a blank page. Do I need to enable "iframe" settings on Heroku? <iframe src="https://dj-node-project.herokuapp.com/catalog/"> <p>Your browser does not support iframes.</p> </iframe> -
python manage.py runserver Segmentation fault
I just installed python and Django. and now when i running $ python manage.py runserver it is showing me this error Segmentation fault Please help me get out of this. i appreciate your help thanks!