Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Difference between SET_DEFAULT and SET options of on_delete parameter [duplicate]
This question already has an answer here: what does on_delete do on Django models? 3 answers As the title says What is the difference between SET_DEFAULT and SET options of on_delete parameter -
Issue ckeditor with mail address in text
I am using django-ckeditor==5.3.1 and Django==1.11.2. My problem is, when I put email address (mailto) to text (yes, I am using safe filter), text disapear on the list. But on detail page is OK. html code: <div class="feed-list"> <div class="feed-list-item"> <h3>{{ task.title }}</h3> <p>{{ task.text|safe }}</p> </div> </div> Strange, because without safe is OK but with My settings: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Simple', 'autoParagraph': False, 'shiftEnterMode': 2, 'enterMode': 2, }, } -
how can i user set_password in custom non-admin model?
Attribute error : 'User' object has no attribute 'set_password' Code in views.py ... from .models import User ... def post(self, request): # Data is here form = self.form_class(request.POST) if form.is_valid(): # create object of form user = form.save(commit=False) # cleaned/normalised data # user = form.cleaned_data[form] username = form.cleaned_data['username'] password = form.cleaned_data['password'] # convert plain password into hashed user.set_password(user.password) user.save() ... -
Error in setting foreign key for table using Django
I was trying to set foreignkey of one column of one table but encountered a problem. I defined four classes as follow: class Genes(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Genes' class Metabolites(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255, blank=True, null=True) compartment = models.CharField(max_length=255, blank=True, null=True) charge = models.CharField(max_length=255, blank=True, null=True) formula = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Metabolites' class Reactions(models.Model): id = models.CharField(max_length=255, blank=True, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) metabolites = models.TextField(blank=True, null=True) lower_bound = models.CharField(max_length=255, blank=True, null=True) upper_bound = models.CharField(max_length=255, blank=True, null=True) gene_reaction_rule = models.TextField(blank=True, null=True) subsystem = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'Reactions' class Reactionsmeta(models.Model): id = models.CharField(max_length=255, blank=True, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) metabolite1 = models.ForeignKey(Metabolites, on_delete = models.CASCADE) stoichiometry1 = models.IntegerField(blank=True, null=True) metabolite2 = models.CharField(max_length=255, blank=True, null=True) stoichiometry2 = models.IntegerField(blank=True, null=True) #... class Meta: managed = False db_table = 'ReactionsMeta' And as for the Reactionsmeta class, the data of metabolite1, metabilite2,...are the id of each metabolites. So, I want to set the metabolite1,2,3....as the foreignkey which point … -
django model. Update status of choicefield
How to update choice field with condition. For example i need to update status of choice field from reserved to pending if end_date < timezone.now() I tried to do this but that's did not worked for me :( class ReservedRooms(models.Model): RESERVED = 'reserved' PENDING = 'pending' ROOM_STATUS = ( (RESERVED, 'Reserved'), (PENDING, 'Pending') ) status = models.CharField(max_length=20, choices=ROOM_STATUS, default=RESERVED) reserved_by = models.ForeignKey(Visitor, on_delete=models.PROTECT) room = models.ForeignKey(Room, on_delete=models.PROTECT) reserved_date = models.DateField(default=timezone.now) begin_date = models.DateTimeField(default=timezone.now) end_date = models.DateTimeField() def check_for_status(self): if self.end_date < timezone.now(): self.status.update() -
media image rendered by django template broken
There are several answers along broken image lines that didn't help me. settings.py INSTALLED_APPS = [...#'django.contrib.staticfiles',] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my_app/urls.py urlpatterns = [ url(r'^welcome/', views.upload, name='upload'),] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) my_app/templates/template.html <img src='media/my_image.jpeg'> my_app/views.py def upload(request): if request.METHOD == 'POST: ... return redirect(to another page) return render(request, 'template.html') The template.html renders correctly, but the image is broken. When I tried curl -D - http://127.0.0.1:8000/my_app/welcome/media/my_image.jpeg I get a 200 and when I go the /welcome in the browser the backend returns [22/Mar/2018 13:31:57] "GET /my_app/welcome/ HTTP/1.1" 200 411 [22/Mar/2018 13:31:57] "GET /my_/welcome/media/my_image.jpeg HTTP/1.1" 200 411 so I don't think it's a url problem. Chrome is showing images. Any Ideas? -
How can i use this condition in Django models.forms?
Im using the next piece of code, to validate Profile values, but now i need to valide when the user update his profile. the question is how i can return true, if "username" is equals to current profile whith the same email address, or more simple, if current username is the same, and taken by same profile in model. maybe if im make a clean_username function , asking by username and email? class ProfileForm(forms.ModelForm): phone = forms.RegexField(regex=r'^\+?1?\d{9,15}$', required=False) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') -
How do I post to Django using Axios?
I'm moving from Jquery AJAX to Axios since I'm using ReactJS so I think it's cleaner, I am having some troubles posting a simple request to the server, the post method goes through my view but whenever I print(request.POST) I have an empty queryset (<QueryDict: {}>). Here's the JS: axios({ method: 'post', url: SITE_DOMAIN_NAME + '/my_url_name/', #http://127.0.0.1:8000/my_url_name data: { 'tes1':'test', 'tes2':'test' }, headers: { "X-CSRFToken": CSRF_TOKEN, "content-type": "application/json" #tried without content-type too. } }).then(function (response) { console.log(response) }).catch(function (error) { console.log(error) }); Django view is a simple ClassBasedView. What am I doing wrong? -
websocket-client: socket.error: [Errno 104] Connection reset by peer
I am using Django channels to build an realtime chat application. I have installed websocket-client and when I try to connect using ws.connect(), it throws error 104. connection reset by peer. It first does handshaking but immediately disconnects. My routing.py file: from channels.routing import route from channels import Group def ws_connect(message): print 'ssssssssssssss' Group('users').add(message.reply_channel) message.reply_channel.send({"accept": True}) def ws_disconnect(message): Group('users').discard(message.reply_channel) def message_handler(message): print(message['text']) channel_routing = [ route("websocket.receive", message_handler), route('websocket.connect', ws_connect), route('websocket.disconnect', ws_disconnect), ] putty ran in parallel: root@in:/home/django/django_project# python manage.py runserver Performing system checks... System check identified no issues (0 silenced). March 22, 2018 - 13:24:20 Django version 1.11.10, using settings 'django_project.settings' Starting Channels development server at http://127.0.0.1:8000/ Channel layer default (asgi_redis.core.RedisChannelLayer) Quit the server with CONTROL-C. 2018-03-22 13:24:20,346 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-03-22 13:24:20,348 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-03-22 13:24:20,348 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-03-22 13:24:20,350 - INFO - server - HTTP/2 support enabled 2018-03-22 13:24:20,350 - INFO - server - Using native Twisted mode on channel layer 2018-03-22 13:24:20,351 - INFO - server - Listening on endpoint tcp:port=8000:interface=127.0.0.1 2018-03-22 13:24:20,353 - INFO - worker - … -
Javascript stateful button in bootstrap
I have a django website where a slow proceedure (an ML model) is called. I want to show the user something to let them know the 10s wait is normal and the site hasn't crashed. I'm using the example from here: bootstrap docs so question There are two issues: The method is depreciated. The button is a submit button on a form. When there are form erros caught by my custom validation a new state is created and the loading animation stops immediately. If it is a required field that isn't filled, the forms internal checks find it, never pass the info to the validators and the state of the form isn't changed, thus requiring the user to wait for the timeout of the loading animation. How can I capture these errors as well to trigger the change in loading state, or better let the loading animation know that the form was not submitted. So trigger the state change only once my views.py says that the form was valid. Side note, I'm from an optimization background and know virtually no javascript, so please point me to some simple solutions, less fancy the better. Currently the site only uses the bootstrap.js … -
How to change the default media url for a in django file field?
I am using django-sendfile to protect certain files. The problem is that when the file is displayed on the frontend it uses the MEDIA_ROOT location which is not where the file actually is. The actual link (that checks permissions) that I want to use is: http://127.0.0.1:8000/leave/supporting_doc/57 yet the link displayed is: http://127.0.0.1:8000/media/leave/user_2/2018-09-06-logo.png The field in the model is: supporting_doc = models.FileField( upload_to=user_leave_directory_path, storage=SENDFILE_STORAGE, blank=True, validators=[FileExtensionValidator(ACCEPTED_FILE_TYPES)] ) The upload to method give a link relative to MEDIA_ROOT: def user_leave_directory_path(instance, filename): '''Get the user directory for leave supporting document''' # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'leave/user_'\ f'{instance.user.id}/{instance.start_date}-{filename}' -
How to draw earth globe in django
I am trying to draw earth globe on my site which can tell what is twitter traffic. How can I draw earth glob in Django, which tell us twitter traffic around the world? -
Django forms.ChoiceField() I'm overlooking something
Probably I'm making some beginner mistake. I'm trying to get forms.ChoiceField() working. The user should be able to select from a dropdownlist so as to select 1, 2, 3 or four collectors in a row. I defined choices.py as follows: COLLECTORS_PER_ROW_CHOICES = ( (1, 'one collector'), (2, 'two collectors'), (3, 'three collectors'), (4, 'four collectors') ) The System model is defined as follows: from .choices import * class System(models.Model): project = models.ForeignKey('solgeo.Project', related_name='systems', on_delete=models.CASCADE) system_name = models.CharField(max_length=200) number_collector_rows = models.IntegerField(default=1) number_collectors_per_row = models.IntegerField(choices = COLLECTORS_PER_ROW_CHOICES) The form is defined as follows: from .choices import * class SystemForm(forms.ModelForm): number_collectors_per_row = forms.ChoiceField(required=True, choices = COLLECTORS_PER_ROW_CHOICES) class Meta: model = System fields = [ 'system_name', 'number_collector_rows' ] -
TemplateSyntaxError at Could not parse the remainder
In my django app I am trying to get the name of image to be loaded from JSON variable.In its HTML key there is name of the image to be displayed. I am reading that key and appending in the static path.But I get this error TemplateSyntaxError at Could not parse the remainder JSON var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; My loop used for extracting image name and other required parameters for(var index=0;index<json.length;index++) { gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static \'images/'+json[index].html+'\' %}"></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row); }; Check in this loop the variable I get var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": … -
Django query conditional filed selector
class Parent(models.Model): name = models.CharField(max_length=255, blank=False) class Child(models.Model): parent = models.ForeignKey(Warehouse, related_name="children") name = models.CharField(max_length=255, blank=True) Need to apply search from Child by some term stating: If Child's name is not empty or not NULL then we compare term with Child's name else - compare term with Parent's name. Something like: search_result = Child.objects.filter( if Q(name__isnull=True) | Q(name='') then parent__name__icontains=term else name__icontains=term ) -
How to make join in django
I have next models: class User(models.Model): id = models.IntegerField(primary_key=True) class UserMarketSubscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) market = models.ForeignKey('Market', on_delete=models.CASCADE) date_in = models.DateField(default=year_back) date_out = models.DateField(default=year_back) class Market(models.Model): name = models.CharField(max_length=50) Shortly to say, I have User that can be subscripted on several markets. At the end I want to get QuerySet that contains all users and their information about subscription(1 user per row). So i want to get nearely next field_names('id', 'market1_date_in', 'market1_date_out', 'market2_date_in' ..., 'marketN_date_out) I have tried annotations, but it does not work since, it requires exact field name on annotation, and i can't do it in cylce over each Market. 'values_list' method returns many objects of one user with different subscription details, I want all details in one object. How can i do this? -
Error 404 before deleting specific module folder in Odoo 10
I have placed an Odoo 8 module in the applications folder and then I have deleted it because i found a 10 version from that, then it shows me the following error: GET https://dm06069.mywebsite.com/web/image/ir.ui.menu/443/web_icon_data 500 (INTERNAL SERVER ERROR) web.assets_common.js:561 GET https://dm06069.mywebsite.com/web/static/lib/fontawesome/fonts/fontawesome-webfont.woff2?v=4.5.0 net::ERR_ABORTED (anonymous) @ web.assets_common.js:561 fire @ web.assets_common.js:541 fireWith @ web.assets_common.js:546 ready @ web.assets_common.js:554 completed @ web.assets_common.js:555 web.assets_common.js:561 GET https://dm06069.mywebsite.com/backend_theme_v10/static/src/font/Roboto-Regular.ttf net::ERR_ABORTED (anonymous) @ web.assets_common.js:561 fire @ web.assets_common.js:541 fireWith @ web.assets_common.js:546 ready @ web.assets_common.js:554 completed @ web.assets_common.js:555 web.assets_common.js:2939 GET https://dm06069.mywebsite.com/web_editor/static/src/xml/ace.xml 404 (NOT FOUND) load_xml @ web.assets_common.js:2939 add_template @ web.assets_common.js:2923 loadXML @ web.assets_common.js:3053 (anonymous) @ web.assets_common.js:3719 process_job @ web.assets_common.js:3000 process_jobs @ web.assets_common.js:3006 (anonymous) @ web.assets_common.js:3001 (anonymous) @ web.assets_common.js:547 fire @ web.assets_common.js:541 fireWith @ web.assets_common.js:546 deferred.(anonymous function) @ web.assets_common.js:548 (anonymous) @ web.assets_common.js:3737 fire @ web.assets_common.js:541 fireWith @ web.assets_common.js:546 ready @ web.assets_common.js:554 completed @ web.assets_common.js:555 web.assets_common.js:3038 GET https://dm06069.mywebsite.com/web/webclient/locale/es_ES net::ERR_ABORTED loadJS @ web.assets_common.js:3038 load_js @ web.assets_common.js:3151 (anonymous) @ web.assets_common.js:3151 (anonymous) @ web.assets_common.js:547 fire @ web.assets_common.js:541 fireWith @ web.assets_common.js:546 deferred.(anonymous function) @ web.assets_common.js:548 fire @ web.assets_common.js:541 fireWith @ web.assets_common.js:546 (anonymous) @ web.assets_common.js:547 fire @ web.assets_common.js:541 fireWith @ web.assets_common.js:546 (anonymous) @ web.assets_common.js:547 fire @ web.assets_common.js:541 fireWith @ web.assets_common.js:546 done @ web.assets_common.js:937 callback @ web.assets_common.js:957 XMLHttpRequest.send (async) send @ web.assets_common.js:954 ajax @ web.assets_common.js:930 (anonymous) @ web.assets_common.js:3030 genericJsonRpc @ … -
AJAX call to GET data from a Django view as JSON, then POST it to another view
I have a Django view function similar to the following, which scrapes data and returns it as JSON: def get_data(request): #scraping code here scraped_data = {"Name": "John"} return JsonResponse(scraped_data) I need AJAX assigned to .submit method of a form that calls this view using "GET" method, gets the scraped_data and sends it to another view for further processing. I would appreciate if someone would help me develop the following skeleton code of such AJAX call: $("#my_form").submit(function(e) { $.ajax({ type: "GET", url: "/get_data", data: // need scraped_data here, how do I phrase it? success: function(data) { //send scraped_data to another Django view, possibly using jQuery ".post"?; } }); }); -
How do I find only objects that have a related object in Django ORM?
I am trying to figure out the best way to get only the questions that have at least one answer. (I don't need to know how many.) I have the following model. class ChallengeQuestionAnswer(models.Model): """Basic forum thread of questions and answers""" challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) original_question = models.ForeignKey('self', blank=True, null=True, related_name='answers') creator = models.ForeignKey(settings.AUTH_USER_MODEL) creation_date = models.DateTimeField(auto_now_add=True) text_data = models.TextField(blank=False) def __str__(self): return self.text_data I can get the current list of all parent questions easy enough with this query: questions = ( PublicChallengeQuestionAnswer.objects .filter(challenge=challenge, original_question__isnull=True, answers__isnull=True, marked_hidden=False) .order_by('-creation_date') .all() ) Is there a simple way to modify this query by adding to it a filter that removes all questions that don't have answers? -
how to build an android app from django web application
i want to build an android app from django web application project.I want to implement the back end code of my android app and connect with the database. -
Allowing user/users to only view one table of DB with Django?
I am very new with Django and trying to learn from various sources on internet. My project folder structure goes like I am using sqlite.db and made 6 models that are linked to backend DB. One of the table i have is Execution_Results. class Execution_Results(models.Model): class Meta: permissions = ( ('view_results', 'User can view results'), ) verbose_name_plural = "Execution_Results" config_id = models.ForeignKey(Config_Details, on_delete=models.CASCADE) exec_time = models.DateTimeField() path = models.CharField(max_length=100) With Admin login i can only provide access to add, edit and delete for that particular or group of users. For my case i just want view access for users. And based on whatever config_id they choose i want to read data from other tables based on mapping and present it for user. I gave permissions = ( ('view_results', 'User can view results'), ) but i am not getting what next shall be done so that user can just view this table data. -
Django staticfiles some are working and some are not, why?
I am a beginner in coding. I have been working on my own project for a month, I haven't had this problem before. Some of my static files are working and some the server is giving me 404 on them, and I have no idea why. Sorry if my question does not make sense. -
How to update a model when I insert a another model?
I am using django framework for cricket statistics system I need to update player scores when ever I add a match detail how can do this. -
Django cms 3 how to have user able to select multiple model in plugin instanciation
I just followed the tutorial of django-cms to create a plugin and I'm facing a (probably) silly problem. I'm creating an app that aim to display jobs. Thus, in your django Admin (even in plugin) you can create jobs with title, description etc. So following the tuto my models look like this: class Job(models.Model): title = models.CharField(max_length=200) location = models.CharField(max_length=200) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) description = HTMLField(blank=False) def __str__(self): return self.title class JobPluginModel(CMSPlugin): job = models.ForeignKey(Job) def __unicode__(self): return self.job.title So my aim is, on the user side, you create a title, then you use your plugin to select the jobs related to title to display. Following the tutorial I've on the CMS side: @plugin_pool.register_plugin class JobPlugin(CMSPluginBase): model = JobPluginModel module = _("Jobs") name = _("Jobs Plugin") render_template = "template_job.html" inlines = (ItemInlineAdmin,) def render(self, context, instance, placeholder): context = super(JobPlugin, self).render(context, instance, placeholder) context.update({'instance': instance}) return context But the problem here is that I have only one select box to select a job from jobs and I don't get / can't find in the doc how to be able to have more job selection! And then in your template you would simply display the selected jobs. Any … -
Pushing my docker image Django app to Heroku gives me Application Error
After much trial and error, I finally managed to push a Docker image to my Heroku app. I opened the app hoping to see my app, but instead saw Heroku's generic "Application Error" page. I'm not sure where or how to proceed, and I believe it's because I'm missing a fundamental understanding of how Docker, Docker containers, Docker-container-registry on Heroku, and servers work. I had hoped I can push the image and then start making incremental updates to my app and keep pushing them up to the Heroku page--even run commands like migrate, runserver, etc. But I don't see the option for that anywhere on the Heroku console. Can someone clue me in as to why I might be seeing an empty page? I thought a Docker image is a snapshot of my project, as it runs on my local device. When I docker-compose -f local.yml build or docker-compose -f production.yml build and then docker-compose -f local.yml up or docker-compose -f production.yml up, they work. local.yml up command will allow it to work on my localhost as well. Strangely, in order to make it push to Heroku's container-registry, I had to use the docker build command as opposed to docker-compose. …