Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and media files on different hosting
I have bought hostgator shared hosting, and I wanted to install django python 2.7. but they do not support python 2.7 on shared hosting. So I want to ask can I install my Django application on DigitalOcean and host my media files on Hostgator. Thanks in Advance -
How to set default value in Django while filtering objects from models
I am trying to create one function where I am expecting user to enter some details and on the basis of that I need to filter out those data and return it. For example if in my model name Profile I have: Name. age, gender then I am trying to do: Profile.objects.filter(name=name, age=age, gender=gender) name, age and gender are values which will be provided by user. Now if user types name = 'Shashank' and leaves age and gender blank then I need to query it like: Profile.objects.filter(name='Shashank') While ignoring all those blank values. So I am not sure how to achieve such kind of behaviour. What type of inital value I can set so that it doesn't effect the search result. `Profile.objects.filter(name='Shashank', age=, gender=) Where can be ignored by filter function. -
Adding ForeignKey item with blank fields
I have few models that all have ForeignKey to another model. This allows me to create "Jobs" with mutliple items of multiple options. Problem is: I can't add item when I don't fill text boxes with data. But in my case, data is optional⦠Is there any solution (or hack) to force adding field? I'm attaching model example I have, and screenshot of admin panel that shows what I mean. class Job(models.Model): name = models.CharField(max_length=128) class FtpJob(models.Model): host = models.CharField(max_length=128) username = models.CharField(max_length=64) password = models.CharField(max_length=64, null=True, blank=True) job = models.ForeignKey(Job, on_delete=models.CASCADE) class PopulateFileListJob(models.Model): issue_subid = models.CharField(max_length=1024, null=True, blank=True) job = models.ForeignKey(Job, on_delete=models.CASCADE) class CreateZipJob(models.Model): issue_subid = models.CharField(max_length=1024, null=True, blank=True) job = models.ForeignKey(Job, on_delete=models.CASCADE) Screenshot shows example when item won't be added when fields is empty. -
Django filter queryset in template
I'm still studying in school and still new in Python language & Django framework and I'm trying doing projects to learn the best practice for it. Right now I'm building a project like following : Topics Model => which is user can write a new topic Replies Model => which is user can write a new reply for a specific topic Likes Model => which is user can vote up or down for a topic or reply it's a little bit close from stackoverflow site . Models.py class Topic(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=400) like = models.IntegerField(default=0) dislike = models.IntegerField(default=0) image = models.FileField(blank=True, null=True) created_date = models.DateTimeField(auto_now=True) def __str__(self): return self.title[0:51] class Reply(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) reply = models.TextField() created_date = models.DateTimeField(auto_now=True) def likes(self): return Likes.objects.filter(reply=self, reply_flag=1).count() likes.short_description = 'likes' def dislikes(self): return Likes.objects.filter(reply=self, reply_flag=-1).count() dislikes.short_description = 'dislikes' def __str__(self): return self.reply class Likes(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) reply = models.ForeignKey(Reply, on_delete=models.CASCADE) reply_flag = models.CharField(max_length=5, choices=( ('0', 'No'), ('1', 'Positive'), ('-1', 'Negative'))) # 1 = vote up , -1 vote down Views.py # get all topics def Topics(request): topics = models.Topic.objects.all() return render(request, 'Topics.html', {'topics': topics}) # get detail of specific topic def β¦ -
upgrading from django 1.9 to 1.11 broke crossbar guest worker
After upgrading from django 1.9.6 to 1.11.11, running crossbar 17.10.1 with the following guest worker configuration fails due to not finding the DJANGO_SETTINGS_MODULE ("simpl_calc_model.settings"). How to I ensure django-admin 1.11.11 can find the settings module when called from crossbar? { "type": "guest", "executable": "django-admin", "arguments": ["run_guest"], "options": { "workdir": "..", "env": { "inherit": "True", "vars": { "HOSTNAME": "localhost", "PORT": "8080" } } } } The error log looks like: Traceback (most recent call last): File " ~/.virtualenvs/simpl-calc-model/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File " ~/.virtualenvs/simpl-calc-model/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File " ~/.virtualenvs/simpl-calc-model/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File " ~/.virtualenvs/simpl-calc-model/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File " ~/.virtualenvs/simpl-calc-model/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File " ~/.virtualenvs/simpl-calc-model/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File " ~/.virtualenvs/simpl-calc-model/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'simpl_calc_model' -
How to add attachments to a Slack Message?
We're developing this internal app in Slack, where typing certain command and subcommand (i,e. /hello world) we obtain several things, one of them is /hello stats, where I'm going to obtain all the stats from my users (this info is obtained through a Django Rest API). The problem I'm facing right now is that I'm able to obtain all my users through my command line, but when I type the command in Slack, it only return me the last user. The problem in here is that a coworker create a method called slack.Message but right now he's away and we're stucked at this point. Right now my main function that returns me all the users from my API looks like this: class StatsCommand(CommandMixin, slack.Command): def execute(self): """Returns projects stats""" self.send_response('stats') # return slack.Message('Working on stats command') respuesta = requests.get('http://proj.herokuapp.com/api/v1/activities/?format=json', auth=('xxxx','xxxx')) upworkresponse = respuesta.json() for project in upworkresponse: #Iterate over projects for team in project["members"]: #Iterate over members print(team["first_name"] + " " + team["last_name"] + " has been working on " + project["title"]) return slack.Message(team["first_name"]+" "+ team["last_name"] + " has been working on " + project["title"]) The instructions that he leave us where the following: if you see about slack command, β¦ -
Django tests fails when using a specific model in a migration file
I've manually created a data migration file for a specific Django 1.11 app: from __future__ import unicode_literals from django.db import migrations, models def set_item_things(apps, schema_editor): MyModel = apps.get_model('my_app', 'MyModel') # NOTE: if I remove this line then the tests will work MyOtherModel = apps.get_model('my_other_app', 'MyOtherModel') for item in MyModel.objects.all(): # NOTE: if I remove this line then the tests will work thingy = MyOtherModel.get(example_field=item.color) item.other_thing = thingy item.save() class Migration(migrations.Migration): dependencies = [ ('contracts', '0014_my_previous_migration'), ] operations = [ migrations.RunPython(set_item_things), ] When I run python manage.py migrate everything works as expected. But whenever I run my test using pytest I get this: test setup failed self = <django.db.migrations.state.StateApps object at 0x10714b2b0> app_label = 'my_other_app' def get_app_config(self, app_label): """ Imports applications and returns an app config for the given label. Raises LookupError if no application exists with this label. """ self.check_apps_ready() try: > return self.app_configs[app_label] E KeyError: 'my_other_app' So it looks like the app config is not properly configured, and that's already weird because the migrate command ran smoothly. Anyway: this is the content of my_other_app/apps.py: from django.apps import AppConfig class MyOtherAppConfig(AppConfig): name = 'my_other_app' And basically is very similar to all the others apps.py sitting in the other apps directories, β¦ -
Print out Django Admin list results only
Is there a way to print out Django Admin's change_list page without including the filers? i.e, the page at 0.0.0.0:8000/admin/<app>/<object>/ -
Django Page Not found error : Sudden in process of learning
I was in motion of learning Django, suddenly encountered Page not found Error in all pages. This is my URL pattern file code: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^analysis/', include('analysis.urls')), url(r'^music/', include('music.urls')), ] but while accessing any of the pages page not found error is coming: I have run the server on port 8084, python .\manage.py runserver 8084 Accessing urls: http://127.0.0.1:8084/admin http://127.0.0.1:8084/music http://127.0.0.1:8084/analysis All of the views are available and pages were previously displayed but now it is not working. I have tried re-starting the server also but no help. Kindly suggest me what could be the possibility of error. -
Single endpoint post array with multiple type of dictionary
I am creating the RESTful endpoints for supporting frontend payload. My payload is an order of build your own dish and ready-made single dish Problem: In single POST of frontend. He wants to put everything to the single time. That's mean in the given list will contains 2 types of dictionary one for build your own and one for ready-made single dish IMO: He can POST 2 times for each type of payload. By this method the endpoint will do one thing and I prefer that way. He has only 1 reason to POST everything to single endpoint because he is lazy Question: What is your best practice for this sort of problem? -
django models. ForeignKey(User, default=request.user)
How to get default user? For example user = models.ForeignKey(User, on_delete=models.PROTECT, default=request.user) Of course this code will not work. This question was asked before but i could not find answer that satisfy me Are there are any solutions for that situations? -
list of tuples to django queryset like object
I have a two lists something like the following: month = ["Jan", "Feb" , ..., "Dec"] temperature = [34, 35, .... , 29 ] I can use above lists to make a list of tuple using zip month_temperature = list(zip(month, temperature)) # month_temperature = [ ("Jan", 34), ("Feb", 35), ..., ("Dec", 29)] Consider an object mon_temp (like a django queryset) very similar to month_temperature which lets me do this: print(mon_temp[0].month) # Jan print(mon_temp[0].temperature) # 34 Is it possible? Any Hints? -
How to save html for sub Web Site in Django?
where can i save my HTML site for the call http://127.0.0.1:8000/contact/thanks/ if I have html for http://127.0.0.1:8000/contact/? -
Django Admin Model save duplicates any entry
Today I have finished upgrading my project from Django 1.7.4 to Django 2.0.2. Now, in Django Admin any model save duplicate new entry. Is it a bug or did I miss something while doing upgrade? -
How to integrated django API with facebook messanger
i have created django API and integrated with Facebook messenger using of ngrok tunnel problem is when i send message it's doesn't give respond API link is successfully integrated with WEBHOOK but it's doesn't give response my webhook look like this my view.py file from django.http.response import HttpResponse class curia_msViews(generic.View): def get(self, request, *args, **kwargs): if self.request.GET['hub.verify_token'] == 'myapp': return HttpResponse(self.request.GET['hub.challenge']) else: return HttpResponse('Error, invalid token') Setting.py INSTALLED_APPS = ['testapp'] This is my setting.py urlpatterns = [url(r'^225c8a4f05d51ab8f329277412061e36e593c3bbb30ad6a138/?$',testappViews.as_view())] integrating local machin link is suceessfully but when i send messages it's doesn't respond any one have idea how to integrating django API with messenger ? -
Trouble deploing django with django rest framework in azure
when i deploy django in azure i put 'rest_framework' in INSTALLED_APPS i got the following error File "D:\home\site\wwwroot\env\Lib\site-packages\django__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "D:\home\site\wwwroot\env\Lib\site-packages\django\apps\registry.py", line 78, in populate raise RuntimeError("populate() isn't reentrant") but when i remove 'rest_framework' it works fine and also i put djangorestframework==3.5.2 in requirements.txt -
Trying to add persistence to django channel layers, failing to read from Redis
I'm trying to add persistence to django's channel-layers. I am overriding two functions to achieve this: group_add and group_send. Group_send should now store the latest message that it has sent in redis (which it is doing, successfully). Group_add should read this message from redis, and send it each time a new entity joins the group. However, it is failing to read from redis. from channels_redis.core import RedisChannelLayer from channels.exceptions import ChannelFull import time class RedisChannelLayerGroupPersistence(RedisChannelLayer): async def group_send(self, group, message): """ Sends a message to the entire group. """ assert self.valid_group_name(group), "Group name not valid" # Retrieve list of all channel names key = self._group_key(group) pers_key = key + bytes("_PERS", 'utf-8') async with self.connection(self.consistent_hash(group)) as connection: # Discard old channels based on group_expiry await connection.zremrangebyscore(key, min=0, max=int(time.time()) - self.group_expiry) # Return current lot channel_names = [ x.decode("utf8") for x in await connection.zrange(key, 0, -1) ] # TODO: More efficient implementation (lua script per shard?) try: await connection.persist(pers_key) await connection.set(pers_key, str(message)) for channel in channel_names: try: await self.send(channel, message) except ChannelFull: pass async def group_add(self, group, channel): """ Adds the channel name to a group. """ # Check the inputs assert self.valid_group_name(group), "Group name not valid" assert self.valid_channel_name(channel), "Channel name not β¦ -
What is the meaning of 's' in method_name.s(param1, param2)
I am working in a legacy application which is implemented with python Django framework. In that application I found several method calls which has the following format. method_name.s(param1, param2) What is meant by 's' in this command line. def send_push_message(self, message, cmd_type): if not self.is_active: return None wrapper = MessageWrapper(message, cmd_type=cmd_type, max_message_size=2000) return group( push_sns_message.s(self.sns_connection, json.dumps(m), self.sns_arn) for m in wrapper)() -
How can I delete a single file in Django?
I have a template which displays the files that a user has uploaded. I managed to make a view that allows me do delete all the files the user has uploaded, but I also would like to make it possible to delete each one individually. I have a bootstrap card, and in the body I display each file with the delete link on the right: <div class="card-body text-light"> {% for doc in docs %} <ul> <a href="/media/{{doc}}" download style="color:lightblue"><font face="Ubuntu">{{doc.document|filename}}</font></a> <a href="#"><font face="Ubuntu" color="red">Delete</font></a> </ul>&nbsp; {%endfor%} </div> And in the card footer I use the view that deletes all files: <div class="card-footer bg-transparent border-light"> <a href="{% url 'main:delete' %}"><i class="fas fa-trash-alt" style="color:red"></i> <font face="Ubuntu" color="red"><b>Delete All Files</b></font></a> </div> My delete view is as follows: def delete(request, **kwargs): documents = Document.objects.filter(owner=request.user.id) documents.delete() cleanup_post_delete.connect(delete, request) return redirect('main:user_panel') The problem is, I can't figure how to delete each file individually, thought of using the objects.get() method but it really can't help me. I would need some view that targets that specific file and deletes it. -
field back to zero after save
I have this class in a module1: class A(models.Model): _name="a" b_id = field.Many2one("b") tax_old = fields.Float() tax_value = fields.Float(string="Tax", related = 'b_id.tax_value', store=True) all_taxes = fields.Float(_compute='compute_all') @api.depends('tax_value') def compute_all(self): all_taxes = self.tax_value + self.tax_old self.update() In module2 I have this class: class B(models.Model): _name="b" a_ids = fields.One2many("a","b_id") tax_value = fields.Float(string="Tax") Now in A view when I change b_id value, tax_value works fine and compute_all works fine, but when I save this record, all_taxes doesn't take tax_value field, only tax_old. And when I open the record form view again and manually write a value in tax_value, it works totally fine. -
Filtering through models where value is not full
i have a table which filled with data from db. Now I'm creating search form. Which search everything i want but only if i give it exactly the string which match value in db. For example i type review in search and it will search: qs = Model.objects.filter(status=review) Then i return data with response and my Vue page rendering it as i want. My is choice field, review, registering, cancelled etc. But user can see them as Reviewing, Registering etc. So they not match and user will type Reviewing, which will return empty qs. Also i want search to find result after user types 'viewi'. Is there a way to do it through django server side, cos i couldn't find information in documentation -
Upload image to cloudinary in Django
I am trying to send individual image from HTML to my django view, using ajax, and upload the image to cloudinary! It keeps throwing me below error of encoding! not sure what it is! Can somebody really help! 'ascii' codec can't decode byte 0xff in position 475: ordinal not in range(128) <input type="file" name="live" id="live-upload" /> var dataimg = new FormData(); dataimg.append('img', $('#live-upload')[0].files[0]); $.ajax({ url: '/event/creatives/', type: 'POST', processData: false, // important contentType: false, // important dataType: 'json', data: dataimg }); import cloudinary import cloudinary.uploader import cloudinary.api cloudinary.config( cloud_name="name", api_key="key", api_secret="secret") @login_required def update_creatives(request): try: cloudinary_response = cloudinary.uploader.upload(request.FILES['img']) except Exception as e: print str(e) -
django get exactly that user who create, updated, deleted post
In my project i have Post model. So there are many users. They can do create, update, delete. I need to get users activity. For example someone created post, someone updated How to show exactly that user? class Post(MPTTModel, models.Model): IOS = 'ios' ANDROID = 'android' FRONTEND = 'frontend' BACKEND = 'backend' TYPES = ( (IOS, 'iOS'), (ANDROID, 'Android'), (FRONTEND, 'Frontend'), (BACKEND, 'Backend') ) project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) type = models.CharField(max_length=100, choices=TYPES) name = models.CharField(max_length=255) slug = models.SlugField() parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): if self.parent is None: return self.name return '{0} | {1}'.format(self.parent, self.name) class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name = 'Platform' verbose_name_plural = 'Platforms' I tried do it through {{ request.user }} but that's giving me only current user, current that logged in website? -
Django , I have created a post model and a basic user authentication, for my index page i want to show only posts by current user ,
Create your models here. from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts',on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title In my html <!-- templates/home.html --> {% extends 'base.html' %} {% block content %} <h1>Homepage.</h1> <ul> {% if user.is_authenticated %} {% for post in deeppost %} <li>{{post.title}}</li></a><p>{{post.body}}</p>Created by- {{post.author}} {% endfor %} {% else %} <p>You are not logged in. Please goto the login Page by clicking on the login link above {% endif %} </ul>- {% endblock %} I want to understand how do i only return posts of the user who is currently logged in , I cant understand as i am new to django and programming in general -
Run Django tests with nosetests
My python apps testing is performed on remote server with command nosetests. I cannot modify the way tests are started nor can I add options to it. I have Django app with tests, but tests are not working properly. My project structure: project βββ README.md βββ setup.py βββ mysite β βββ blog β β βββ __init__.py β β βββ models.py β β βββ tests.py | | βββ ... β βββ db.sqlite3 β βββ manage.py β βββ mysite β β βββ __init__.py β β βββ settings.py | | βββ ... Command nosetests is executed in project directory. I want it to properly run tests.py which has 2 Django testcases. I tried creating tests directory in project root and invoke tests with DiscoverRunner): os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' test_dir = os.path.dirname(os.path.dirname(__file__)) # one level up sys.path.insert(0, os.path.join(test_dir, 'mysite')) class ServerTest(unittest.TestCase): def test_runtests(self): django.setup() self.test_runner = DiscoverRunner(verbosity=1, interactive=True, failfast=False) failures = self.test_runner.run_tests(['mysite']) self.assertEqual(failures, 0) It works but the problem is all the tests are considered as single test and wrong reports are produced by server. Another solution: if I add empty __init__.py to project/mysite nose discovers tests.py but the tests fail because 'Apps are not loaded yet' which probably means I have to invoke django.setup() β¦